PdbToXml.cs 49.7 KB
Newer Older
P
Pilchie 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Xml;
16 17
using Microsoft.VisualStudio.SymReaderInterop;
using CDI = Microsoft.VisualStudio.SymReaderInterop.CustomDebugInfoReader;
18
using CDIC = Microsoft.Cci.CustomDebugInfoConstants;
P
Pilchie 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
using PooledStringBuilder = Microsoft.CodeAnalysis.Collections.PooledStringBuilder;

namespace Roslyn.Test.PdbUtilities
{
    /// <summary>
    /// Class to write out XML for a PDB.
    /// </summary>
    public sealed class PdbToXmlConverter
    {
        // For printing integers in a standard hex format.
        private const string IntHexFormat = "0x{0:X}";

        private readonly MetadataReader metadataReader;
        private readonly TempPdbReader pdbReader;
        private readonly PdbToXmlOptions options;
        private readonly XmlWriter writer;

        // Maps files to ids. 
        private readonly Dictionary<string, int> m_fileMapping = new Dictionary<string, int>();

        private PdbToXmlConverter(XmlWriter writer, TempPdbReader pdbReader, MetadataReader metadataReader, PdbToXmlOptions options)
        {
            this.pdbReader = pdbReader;
            this.metadataReader = metadataReader;
            this.writer = writer;
            this.options = options;
        }

47
        public unsafe static string DeltaPdbToXml(Stream deltaPdb, IEnumerable<int> methodTokens)
P
Pilchie 已提交
48 49 50 51 52 53 54
        {
            var writer = new StringWriter();
            ToXml(
                writer, 
                deltaPdb, 
                metadataReaderOpt: null,
                options: PdbToXmlOptions.IncludeTokens, 
55
                methodHandles: methodTokens.Select(token => (MethodDefinitionHandle)MetadataTokens.Handle(token)));
P
Pilchie 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

            return writer.ToString();
        }

        public static string ToXml(Stream pdbStream, Stream peStream, PdbToXmlOptions options = PdbToXmlOptions.ResolveTokens, string methodName = null)
        {
            var writer = new StringWriter();
            ToXml(writer, pdbStream, peStream, options, methodName);
            return writer.ToString();
        }

        public static string ToXml(Stream pdbStream, byte[] peImage, PdbToXmlOptions options = PdbToXmlOptions.ResolveTokens, string methodName = null)
        {
            var writer = new StringWriter();
            ToXml(writer, pdbStream, new MemoryStream(peImage), options, methodName);
            return writer.ToString();
        }

        public unsafe static void ToXml(TextWriter xmlWriter, Stream pdbStream, Stream peStream, PdbToXmlOptions options = PdbToXmlOptions.Default, string methodName = null)
        {
A
angocke 已提交
76
            IEnumerable<MethodDefinitionHandle> methodHandles;
P
Pilchie 已提交
77 78 79 80 81 82 83
            var headers = new PEHeaders(peStream);
            byte[] metadata = new byte[headers.MetadataSize];
            peStream.Seek(headers.MetadataStartOffset, SeekOrigin.Begin);
            peStream.Read(metadata, 0, headers.MetadataSize);

            fixed (byte* metadataPtr = metadata)
            {
A
angocke 已提交
84
                var metadataReader = new MetadataReader(metadataPtr, metadata.Length);
P
Pilchie 已提交
85 86 87 88 89 90 91

                if (string.IsNullOrEmpty(methodName))
                {
                    methodHandles = metadataReader.MethodDefinitions;
                }
                else
                {
92 93 94 95 96 97
                    var matching = metadataReader.MethodDefinitions.
                        Where(methodHandle => GetQualifiedMethodName(metadataReader, methodHandle) == methodName).ToArray();

                    if (matching.Length == 0)
                    {
                        xmlWriter.WriteLine("<error>");
98
                        xmlWriter.WriteLine(string.Format("<message>No method '{0}' found in metadata.</message>", methodName));
99 100 101 102 103 104 105 106
                        xmlWriter.WriteLine("<available-methods>");

                        foreach (var methodHandle in metadataReader.MethodDefinitions)
                        {
                            xmlWriter.Write("<method><![CDATA[");
                            xmlWriter.Write(GetQualifiedMethodName(metadataReader, methodHandle));
                            xmlWriter.Write("]]></method>");
                            xmlWriter.WriteLine();
107
                        }
108 109 110 111 112 113 114 115

                        xmlWriter.WriteLine("</available-methods>");
                        xmlWriter.WriteLine("</error>");

                        return;
                    }

                    methodHandles = matching;
P
Pilchie 已提交
116 117 118 119 120 121 122 123 124 125
                }

                ToXml(xmlWriter, pdbStream, metadataReader, options, methodHandles);
            }
        }

        /// <summary>
        /// Load the PDB given the parameters at the ctor and spew it out to the XmlWriter specified
        /// at the ctor.
        /// </summary>
A
angocke 已提交
126
        private static void ToXml(TextWriter xmlWriter, Stream pdbStream, MetadataReader metadataReaderOpt, PdbToXmlOptions options, IEnumerable<MethodDefinitionHandle> methodHandles)
P
Pilchie 已提交
127 128 129 130 131 132 133 134 135 136 137 138
        {
            Debug.Assert(pdbStream != null);
            Debug.Assert((options & PdbToXmlOptions.ResolveTokens) == 0 || metadataReaderOpt != null);

            XmlDocument doc = new XmlDocument();
            XmlWriter writer = doc.CreateNavigator().AppendChild();

            using (TempPdbReader pdbReader = TempPdbReader.Create(pdbStream))
            {
                if (pdbReader == null)
                {
                    Console.WriteLine("Error: No Symbol Reader could be initialized.");
139
                    return;
P
Pilchie 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
                }

                var converter = new PdbToXmlConverter(writer, pdbReader, metadataReaderOpt, options);

                converter.WriteRoot(methodHandles ?? metadataReaderOpt.MethodDefinitions);
            }
                        
            writer.Close();

            // Save xml to disk
            doc.Save(xmlWriter);
        }

        private static byte[] GetImage(Stream stream)
        {
            MemoryStream memoryStream = stream as MemoryStream;
            if (memoryStream == null)
            {
                memoryStream = new MemoryStream((int)stream.Length);
                stream.Position = 0;
                stream.CopyTo(memoryStream);
            }

            return memoryStream.GetBuffer();
        }

A
angocke 已提交
166
        private void WriteRoot(IEnumerable<MethodDefinitionHandle> methodHandles)
P
Pilchie 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        {
            writer.WriteStartDocument();

            writer.WriteStartElement("symbols");

            WriteDocList();
            WriteEntryPoint();
            WriteAllMethods(methodHandles);

            if ((options & PdbToXmlOptions.IncludeMethodSpans) != 0)
            {
                WriteAllMethodSpans();
            }

            writer.WriteEndElement();
        }

        // Dump all of the methods in the given ISymbolReader to the XmlWriter provided in the ctor.
A
angocke 已提交
185
        private void WriteAllMethods(IEnumerable<MethodDefinitionHandle> methodHandles)
P
Pilchie 已提交
186 187 188 189 190 191 192 193 194 195 196
        {
            writer.WriteStartElement("methods");

            foreach (var methodHandle in methodHandles)
            {
                WriteMethod(methodHandle);
            }

            writer.WriteEndElement();
        }

A
angocke 已提交
197
        private void WriteMethod(MethodDefinitionHandle methodHandle)
P
Pilchie 已提交
198 199 200
        {
            int token = metadataReader.GetToken(methodHandle);

201 202 203
            byte[] cdi = pdbReader.SymbolReader.GetCustomDebugInfo(token, methodVersion: 0);
            ISymUnmanagedMethod method = pdbReader.SymbolReader.GetMethod(token);
            if (cdi == null && method == null)
P
Pilchie 已提交
204 205 206 207 208 209 210 211
            {
                // no debug info for the method
                return;
            }

            writer.WriteStartElement("method");
            WriteMethodAttributes(token, isReference: false);

212
            if (cdi != null)
P
Pilchie 已提交
213
            {
214
                WriteCustomDebugInfo(cdi);
P
Pilchie 已提交
215 216
            }

217
            if (method != null)
P
Pilchie 已提交
218
            {
219
                WriteSequencePoints(method);
P
Pilchie 已提交
220 221 222 223

                // TODO (tomat): Ideally this would be done in a separate test helper, not in PdbToXml.
                // verify ISymUnmanagedMethod APIs:
                var expectedSlotNames = new Dictionary<int, ImmutableArray<string>>();
224
                WriteLocals(method, expectedSlotNames);
P
Pilchie 已提交
225

226
                var actualSlotNames = method.GetLocalVariableSlots();
P
Pilchie 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

                Debug.Assert(actualSlotNames.Length == (expectedSlotNames.Count == 0 ? 0 : expectedSlotNames.Keys.Max() + 1));

                int i = 0;
                foreach (var slotName in actualSlotNames)
                {
                    if (slotName == null)
                    {
                        Debug.Assert(!expectedSlotNames.ContainsKey(i));
                    }
                    else
                    {
                        Debug.Assert(expectedSlotNames[i].Contains(slotName));
                    }

                    i++;
                }

245
                ImmutableArray<ISymUnmanagedScope> children = method.GetRootScope().GetScopes();
P
Pilchie 已提交
246 247 248 249 250
                if (children.Length != 0)
                {
                    WriteScopes(children[0]);
                }

251
                WriteAsyncInfo(method);
P
Pilchie 已提交
252 253 254 255 256 257 258 259 260 261 262
            }

            writer.WriteEndElement(); // method
        }

        /// <summary>
        /// Given a byte array of custom debug info, parse the array and write out XML describing
        /// its structure and contents.
        /// </summary>
        private void WriteCustomDebugInfo(byte[] bytes)
        {
263 264
            var records = CustomDebugInfoReader.GetCustomDebugInfoRecords(bytes).ToArray();
            
P
Pilchie 已提交
265 266
            writer.WriteStartElement("customDebugInfo");

267
            foreach (var record in records)
P
Pilchie 已提交
268
            {
269
                if (record.Version != CDIC.CdiVersion)
P
Pilchie 已提交
270
                {
271
                    WriteUnknownCustomDebugInfo(record);
P
Pilchie 已提交
272 273 274
                }
                else
                {
275
                    switch (record.Kind)
P
Pilchie 已提交
276 277
                    {
                        case CustomDebugInfoKind.UsingInfo:
278
                            WriteUsingCustomDebugInfo(record);
P
Pilchie 已提交
279 280
                            break;
                        case CustomDebugInfoKind.ForwardInfo:
281
                            WriteForwardCustomDebugInfo(record);
P
Pilchie 已提交
282 283
                            break;
                        case CustomDebugInfoKind.ForwardToModuleInfo:
284
                            WriteForwardToModuleCustomDebugInfo(record);
P
Pilchie 已提交
285
                            break;
286
                        case CustomDebugInfoKind.StateMachineHoistedLocalScopes:
287
                            WriteStatemachineHoistedLocalScopesCustomDebugInfo(record);
P
Pilchie 已提交
288 289
                            break;
                        case CustomDebugInfoKind.ForwardIterator:
290
                            WriteForwardIteratorCustomDebugInfo(record);
P
Pilchie 已提交
291 292
                            break;
                        case CustomDebugInfoKind.DynamicLocals:
293
                            WriteDynamicLocalsCustomDebugInfo(record);
P
Pilchie 已提交
294
                            break;
295
                        case CustomDebugInfoKind.EditAndContinueLocalSlotMap:
296
                            WriteEditAndContinueLocalSlotMap(record);
297
                            break;
P
Pilchie 已提交
298
                        default:
299
                            WriteUnknownCustomDebugInfo(record);
P
Pilchie 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312
                            break;
                    }
                }
            }

            writer.WriteEndElement(); //customDebugInfo
        }

        /// <summary>
        /// If the custom debug info is in a format that we don't understand, then we will
        /// just print a standard record header followed by the rest of the record as a
        /// single hex string.
        /// </summary>
313
        private void WriteUnknownCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
314 315
        {
            writer.WriteStartElement("unknown");
T
TomasMatousek 已提交
316 317
            writer.WriteAttributeString("kind", record.Kind.ToString());
            writer.WriteAttributeString("version", record.Version.ToString());
P
Pilchie 已提交
318 319 320

            PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
            StringBuilder builder = pooled.Builder;
321
            foreach (byte b in record.Data)
P
Pilchie 已提交
322 323 324
            {
                builder.AppendFormat("{0:X2}", b);
            }
325

P
Pilchie 已提交
326 327 328 329 330 331 332 333 334 335 336 337
            writer.WriteAttributeString("payload", pooled.ToStringAndFree());

            writer.WriteEndElement(); //unknown
        }

        /// <summary>
        /// For each namespace declaration enclosing a method (innermost-to-outermost), there is a count
        /// of the number of imports in that declaration.
        /// </summary>
        /// <remarks>
        /// There's always at least one entry (for the global namespace).
        /// </remarks>
338
        private void WriteUsingCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
339
        {
340
            Debug.Assert(record.Kind == CustomDebugInfoKind.UsingInfo);
P
Pilchie 已提交
341 342 343

            writer.WriteStartElement("using");

344
            ImmutableArray<short> counts = CDI.DecodeUsingRecord(record.Data);
P
Pilchie 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

            foreach (short importCount in counts)
            {
                writer.WriteStartElement("namespace");
                writer.WriteAttributeString("usingCount", importCount.ToString());
                writer.WriteEndElement(); //namespace
            }

            writer.WriteEndElement(); //using
        }

        /// <summary>
        /// This indicates that further information can be obtained by looking at the custom debug
        /// info of another method (specified by token).
        /// </summary>
        /// <remarks>
        /// Emitting tokens makes tests more fragile.
        /// </remarks>
363
        private void WriteForwardCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
364
        {
365
            Debug.Assert(record.Kind == CustomDebugInfoKind.ForwardInfo);
P
Pilchie 已提交
366 367 368

            writer.WriteStartElement("forward");

369
            int token = CDI.DecodeForwardRecord(record.Data);
P
Pilchie 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382
            WriteMethodAttributes(token, isReference: true);

            writer.WriteEndElement(); //forward
        }

        /// <summary>
        /// This indicates that further information can be obtained by looking at the custom debug
        /// info of another method (specified by token).
        /// </summary>
        /// <remarks>
        /// Appears when there are extern aliases and edit-and-continue is disabled.
        /// Emitting tokens makes tests more fragile.
        /// </remarks>
383
        private void WriteForwardToModuleCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
384
        {
385
            Debug.Assert(record.Kind == CustomDebugInfoKind.ForwardToModuleInfo);
P
Pilchie 已提交
386 387 388

            writer.WriteStartElement("forwardToModule");

389
            int token = CDI.DecodeForwardRecord(record.Data);
P
Pilchie 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402
            WriteMethodAttributes(token, isReference: true);

            writer.WriteEndElement(); //forwardToModule
        }

        /// <summary>
        /// Appears when iterator locals have to lifted into fields.  Contains a list of buckets with
        /// start and end offsets (presumably, into IL).
        /// TODO: comment when the structure is understood.
        /// </summary>
        /// <remarks>
        /// Appears when there are locals in iterator methods.
        /// </remarks>
403
        private void WriteStatemachineHoistedLocalScopesCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
404
        {
405
            Debug.Assert(record.Kind == CustomDebugInfoKind.StateMachineHoistedLocalScopes);
P
Pilchie 已提交
406

407
            writer.WriteStartElement("hoistedLocalScopes");
P
Pilchie 已提交
408

409
            var scopes = CDI.DecodeStateMachineHoistedLocalScopesRecord(record.Data);
P
Pilchie 已提交
410

411
            foreach (StateMachineHoistedLocalScope scope in scopes)
P
Pilchie 已提交
412
            {
413 414 415
                writer.WriteStartElement("slot");
                writer.WriteAttributeString("startOffset", AsILOffset(scope.StartOffset));
                writer.WriteAttributeString("endOffset", AsILOffset(scope.EndOffset));
P
Pilchie 已提交
416 417 418
                writer.WriteEndElement(); //bucket
            }

419
            writer.WriteEndElement();
P
Pilchie 已提交
420 421 422 423 424 425 426 427 428
        }

        /// <summary>
        /// Contains a name string.
        /// TODO: comment when the structure is understood.
        /// </summary>
        /// <remarks>
        /// Appears when are iterator methods.
        /// </remarks>
429
        private void WriteForwardIteratorCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
430
        {
431
            Debug.Assert(record.Kind == CustomDebugInfoKind.ForwardIterator);
P
Pilchie 已提交
432 433 434

            writer.WriteStartElement("forwardIterator");

435
            string name = CDI.DecodeForwardIteratorRecord(record.Data);
P
Pilchie 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448

            writer.WriteAttributeString("name", name);

            writer.WriteEndElement(); //forwardIterator
        }

        /// <summary>
        /// Contains a list of buckets, each of which contains a number of flags, a slot ID, and a name.
        /// TODO: comment when the structure is understood.
        /// </summary>
        /// <remarks>
        /// Appears when there are dynamic locals.
        /// </remarks>
449
        private void WriteDynamicLocalsCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
450
        {
451
            Debug.Assert(record.Kind == CustomDebugInfoKind.DynamicLocals);
P
Pilchie 已提交
452 453 454

            writer.WriteStartElement("dynamicLocals");

455
            var buckets = CDI.DecodeDynamicLocalsRecord(record.Data);
P
Pilchie 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

            foreach (DynamicLocalBucket bucket in buckets)
            {
                ulong flags = bucket.Flags;
                int flagCount = bucket.FlagCount;

                PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
                StringBuilder flagsBuilder = pooled.Builder;
                for (int f = 0; f < flagCount; f++)
                {
                    flagsBuilder.Append((flags >> f) & 1UL);
                }

                writer.WriteStartElement("bucket");
                writer.WriteAttributeString("flagCount", flagCount.ToString());
                writer.WriteAttributeString("flags", pooled.ToStringAndFree());
                writer.WriteAttributeString("slotId", bucket.SlotId.ToString());
                writer.WriteAttributeString("localName", bucket.Name);
                writer.WriteEndElement(); //bucket
            }

            writer.WriteEndElement(); //dynamicLocals
        }

480
        private unsafe void WriteEditAndContinueLocalSlotMap(CustomDebugInfoRecord record)
481
        {
482
            Debug.Assert(record.Kind == CustomDebugInfoKind.EditAndContinueLocalSlotMap);
483 484 485

            writer.WriteStartElement("encLocalSlotMap");

486
            int syntaxOffsetBaseline = -1;
487

488
            fixed (byte* compressedSlotMapPtr = &record.Data.ToArray()[0])
489
            {
490
                var blobReader = new BlobReader(compressedSlotMapPtr, record.Data.Length);
491 492 493 494 495 496 497 498 499 500

                while (blobReader.RemainingBytes > 0)
                {
                    byte b = blobReader.ReadByte();

                    if (b == 0xff)
                    {
                        break;
                    }

501 502 503 504 505 506 507
                    if (b == 0xfe)
                    {
                        syntaxOffsetBaseline = -blobReader.ReadCompressedInteger();
                        writer.WriteElementString("baseline", syntaxOffsetBaseline.ToString());
                        continue;
                    }

508 509 510 511 512 513 514 515 516 517
                    writer.WriteStartElement("slot");

                    if (b == 0)
                    {
                        // short-lived temp, no info
                        writer.WriteAttributeString("kind", "temp");
                    }
                    else
                    {
                        int synthesizedKind = (b & 0x3f) - 1;
518 519
                        bool hasOrdinal = (b & (1 << 7)) != 0;

A
angocke 已提交
520 521
                        int syntaxOffset;
                        bool badSyntaxOffset = !blobReader.TryReadCompressedInteger(out syntaxOffset);
522
                        syntaxOffset += syntaxOffsetBaseline;
523

A
angocke 已提交
524
                        int ordinal = 0;
525
                        bool badOrdinal = hasOrdinal && !blobReader.TryReadCompressedInteger(out ordinal);
526 527 528 529

                        writer.WriteAttributeString("kind", synthesizedKind.ToString());
                        writer.WriteAttributeString("offset", badSyntaxOffset ? "?" : syntaxOffset.ToString());

530
                        if (badOrdinal || hasOrdinal)
531 532 533 534 535 536 537 538 539 540 541 542
                        {
                            writer.WriteAttributeString("ordinal", badOrdinal ? "?" : ordinal.ToString());
                        }
                    }

                    writer.WriteEndElement();
                }
            }

            writer.WriteEndElement(); //encLocalSlotMap
        }

P
Pilchie 已提交
543 544 545 546
        private void WriteScopes(ISymUnmanagedScope scope)
        {
            writer.WriteStartElement("scope");
            {
547 548
                writer.WriteAttributeString("startOffset", AsILOffset(scope.GetStartOffset()));
                writer.WriteAttributeString("endOffset", AsILOffset(scope.GetEndOffset()));
P
Pilchie 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
                {
                    foreach (ISymUnmanagedNamespace @namespace in scope.GetNamespaces())
                    {
                        WriteNamespace(@namespace);
                    }

                    WriteLocalsHelper(scope, slotNames: null, includeChildScopes: false);
                }
                foreach (ISymUnmanagedScope child in scope.GetScopes())
                {
                    WriteScopes(child);
                }
            }
            writer.WriteEndElement(); // </scope>
        }

        private void WriteNamespace(ISymUnmanagedNamespace @namespace)
        {
            string rawName = @namespace.GetName();

            string alias;
            string externAlias;
            string target;
            ImportTargetKind kind;
            ImportScope scope;

            try
            {
                if (rawName.Length == 0)
                {
                    externAlias = null;
580 581
                    var parsingSucceeded = CDI.TryParseVisualBasicImportString(rawName, out alias, out target, out kind, out scope);
                    Debug.Assert(parsingSucceeded);
P
Pilchie 已提交
582 583 584 585 586 587 588 589 590 591
                }
                else
                {
                    switch (rawName[0])
                    {
                        case 'U':
                        case 'A':
                        case 'X':
                        case 'Z':
                        case 'E':
592
                        case 'T':
P
Pilchie 已提交
593
                            scope = ImportScope.Unspecified;
594 595 596 597
                            if (!CDI.TryParseCSharpImportString(rawName, out alias, out externAlias, out target, out kind))
                            {
                                throw new InvalidOperationException(string.Format("Invalid import '{0}'", rawName));
                            }
P
Pilchie 已提交
598 599 600 601
                            break;

                        default:
                            externAlias = null;
602 603 604 605
                            if (!CDI.TryParseVisualBasicImportString(rawName, out alias, out target, out kind, out scope))
                            {
                                throw new InvalidOperationException(string.Format("Invalid import '{0}'", rawName));
                            }
P
Pilchie 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
                            break;
                    }
                }
            }
            catch (ArgumentException) // TODO: filter
            {
                if ((options & PdbToXmlOptions.ThrowOnError) != 0)
                {
                    throw;
                }

                writer.WriteStartElement("invalid-custom-data");
                writer.WriteAttributeString("raw", rawName);
                writer.WriteEndElement();
                return;
            }

            switch (kind)
            {
                case ImportTargetKind.CurrentNamespace:
                    Debug.Assert(alias == null);
                    Debug.Assert(externAlias == null);
                    Debug.Assert(scope == ImportScope.Unspecified);
                    writer.WriteStartElement("currentnamespace");
                    writer.WriteAttributeString("name", target);
                    writer.WriteEndElement(); // </currentnamespace>
                    break;
                case ImportTargetKind.DefaultNamespace:
                    Debug.Assert(alias == null);
                    Debug.Assert(externAlias == null);
                    Debug.Assert(scope == ImportScope.Unspecified);
                    writer.WriteStartElement("defaultnamespace");
                    writer.WriteAttributeString("name", target);
                    writer.WriteEndElement(); // </defaultnamespace>
                    break;
                case ImportTargetKind.MethodToken:
                    Debug.Assert(alias == null);
                    Debug.Assert(externAlias == null);
                    Debug.Assert(scope == ImportScope.Unspecified);
                    int token = Convert.ToInt32(target);
                    writer.WriteStartElement("importsforward");
                    WriteMethodAttributes(token, isReference: true);
                    writer.WriteEndElement(); // </importsforward>
                    break;
                case ImportTargetKind.XmlNamespace:
                    Debug.Assert(externAlias == null);
                    writer.WriteStartElement("xmlnamespace");
                    writer.WriteAttributeString("prefix", alias);
                    writer.WriteAttributeString("name", target);
                    WriteScopeAttribute(scope);
                    writer.WriteEndElement(); // </xmlnamespace>
                    break;
                case ImportTargetKind.NamespaceOrType:
                    Debug.Assert(externAlias == null);
                    writer.WriteStartElement("alias");
                    writer.WriteAttributeString("name", alias);
                    writer.WriteAttributeString("target", target);
                    writer.WriteAttributeString("kind", "namespace"); // Strange, but retaining to avoid breaking tests.
                    WriteScopeAttribute(scope);
                    writer.WriteEndElement(); // </alias>
                    break;
                case ImportTargetKind.Namespace:
                    if (alias != null)
                    {
                        writer.WriteStartElement("alias");
                        writer.WriteAttributeString("name", alias);
                        if (externAlias != null) writer.WriteAttributeString("qualifier", externAlias);
                        writer.WriteAttributeString("target", target);
                        writer.WriteAttributeString("kind", "namespace");
                        Debug.Assert(scope == ImportScope.Unspecified); // Only C# hits this case.
                        writer.WriteEndElement(); // </alias>
                    }
                    else
                    {
                        writer.WriteStartElement("namespace");
                        if (externAlias != null) writer.WriteAttributeString("qualifier", externAlias);
                        writer.WriteAttributeString("name", target);
                        WriteScopeAttribute(scope);
                        writer.WriteEndElement(); // </namespace>
                    }
                    break;
                case ImportTargetKind.Type:
                    Debug.Assert(externAlias == null);
                    if (alias != null)
                    {
                        writer.WriteStartElement("alias");
                        writer.WriteAttributeString("name", alias);
                        writer.WriteAttributeString("target", target);
                        writer.WriteAttributeString("kind", "type");
                        Debug.Assert(scope == ImportScope.Unspecified); // Only C# hits this case.
                        writer.WriteEndElement(); // </alias>
                    }
                    else
                    {
                        writer.WriteStartElement("type");
                        writer.WriteAttributeString("name", target);
                        WriteScopeAttribute(scope);
                        writer.WriteEndElement(); // </type>
                    }
                    break;
                case ImportTargetKind.Assembly:
                    Debug.Assert(alias == null);
                    Debug.Assert(scope == ImportScope.Unspecified);
                    if (target == null)
                    {
                        writer.WriteStartElement("extern");
                        writer.WriteAttributeString("alias", externAlias);
                        writer.WriteEndElement(); // </extern>
                    }
                    else
                    {
                        writer.WriteStartElement("externinfo");
                        writer.WriteAttributeString("alias", externAlias);
                        writer.WriteAttributeString("assembly", target);
                        writer.WriteEndElement(); // </externinfo>
                    }
                    break;
A
acasey 已提交
723 724 725 726 727 728 729
                case ImportTargetKind.Defunct:
                    Debug.Assert(alias == null);
                    Debug.Assert(scope == ImportScope.Unspecified);
                    writer.WriteStartElement("defunct");
                    writer.WriteAttributeString("name", rawName);
                    writer.WriteEndElement(); // </defunct>
                    break;
P
Pilchie 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                default:
                    Debug.Assert(false, "Unexpected import kind '" + kind + "'");
                    writer.WriteStartElement("unknown");
                    writer.WriteAttributeString("name", rawName);
                    writer.WriteEndElement(); // </unknown>
                    break;
            }
        }

        private void WriteScopeAttribute(ImportScope scope)
        {
            if (scope == ImportScope.File)
            {
                writer.WriteAttributeString("importlevel", "file");
            }
            else if (scope == ImportScope.Project)
            {
                writer.WriteAttributeString("importlevel", "project");
            }
            else
            {
                Debug.Assert(scope == ImportScope.Unspecified, "Unexpected scope '" + scope + "'");
            }
        }

755
        private void WriteAsyncInfo(ISymUnmanagedMethod method)
P
Pilchie 已提交
756
        {
757 758
            var asyncMethod = method.AsAsync();
            if (asyncMethod == null)
P
Pilchie 已提交
759
            {
760 761
                return;
            }
762

T
TomasMatousek 已提交
763
            writer.WriteStartElement("asyncInfo");
P
Pilchie 已提交
764

765 766 767
            var catchOffset = asyncMethod.GetCatchHandlerILOffset();
            if (catchOffset >= 0)
            {
T
TomasMatousek 已提交
768 769 770
                writer.WriteStartElement("catchHandler");
                writer.WriteAttributeString("offset", AsILOffset(catchOffset));
                writer.WriteEndElement();
P
Pilchie 已提交
771 772
            }

T
TomasMatousek 已提交
773
            writer.WriteStartElement("kickoffMethod");
774 775 776 777
            WriteMethodAttributes(asyncMethod.GetKickoffMethod(), isReference: true);
            writer.WriteEndElement();

            foreach (var info in asyncMethod.GetAsyncStepInfos())
P
Pilchie 已提交
778
            {
779 780 781 782 783
                writer.WriteStartElement("await");
                writer.WriteAttributeString("yield", AsILOffset(info.YieldOffset));
                writer.WriteAttributeString("resume", AsILOffset(info.ResumeOffset));
                WriteMethodAttributes(info.ResumeMethod, isReference: true);
                writer.WriteEndElement();
P
Pilchie 已提交
784 785
            }

786
            writer.WriteEndElement();
P
Pilchie 已提交
787 788 789 790 791 792 793 794 795 796 797
        }

        // Write all the locals in the given method out to an XML file.
        // Since the symbol store represents the locals in a recursive scope structure, we need to walk a tree.
        // Although the locals are technically a hierarchy (based off nested scopes), it's easiest for clients
        // if we present them as a linear list. We will provide the range for each local's scope so that somebody
        // could reconstruct an approximation of the scope tree. The reconstruction may not be exact.
        // (Note this would still break down if you had an empty scope nested in another scope.
        private void WriteLocals(ISymUnmanagedMethod method, Dictionary<int, ImmutableArray<string>> slotNames)
        {
            writer.WriteStartElement("locals");
798 799
            // If there are no locals, then this element will just be empty.
            WriteLocalsHelper(method.GetRootScope(), slotNames, includeChildScopes: true);
P
Pilchie 已提交
800 801 802
            writer.WriteEndElement();
        }

803
        private void WriteLocalsHelper(ISymUnmanagedScope scope, Dictionary<int, ImmutableArray<string>> slotNames, bool includeChildScopes)
P
Pilchie 已提交
804
        {
805
            foreach (ISymUnmanagedVariable l in scope.GetLocals())
P
Pilchie 已提交
806 807 808
            {
                writer.WriteStartElement("local");
                {
809
                    writer.WriteAttributeString("name", l.GetName());
P
Pilchie 已提交
810 811 812 813 814 815 816 817 818

                    // Each local maps to a "IL Index" or "slot" number. 
                    // The index is not necessarily unique. Several locals may refer to the same slot. 
                    // It just means that the same local is known under different names inside the same or different scopes.
                    // This index is what you pass to ICorDebugILFrame::GetLocalVariable() to get
                    // a specific local variable. 
                    // NOTE: VB emits "fake" locals for resumable locals which are actually backed by fields.
                    //       These locals always map to the slot #0 which is just a valid number that is 
                    //       not used. Only scoping information is used by EE in this case.
819
                    int slot = l.GetSlot();
P
Pilchie 已提交
820 821 822 823 824 825 826 827 828 829
                    writer.WriteAttributeString("il_index", CultureInvariantToString(slot));

                    bool reusingSlot = false;

                    // collect slot names so that we can verify ISymUnmanagedReader APIs
                    if (slotNames != null)
                    {
                        ImmutableArray<string> existingNames;
                        if (slotNames.TryGetValue(slot, out existingNames))
                        {
830
                            slotNames[slot] = existingNames.Add(l.GetName());
P
Pilchie 已提交
831 832 833 834
                            reusingSlot = true;
                        }
                        else
                        {
835
                            slotNames.Add(slot, ImmutableArray.Create(l.GetName()));
P
Pilchie 已提交
836 837 838 839
                        }
                    }

                    // Provide scope range
840 841 842
                    writer.WriteAttributeString("il_start", AsILOffset(scope.GetStartOffset()));
                    writer.WriteAttributeString("il_end", AsILOffset(scope.GetEndOffset()));
                    writer.WriteAttributeString("attributes", l.GetAttributes().ToString());
P
Pilchie 已提交
843 844 845 846 847 848 849 850

                    if (reusingSlot)
                    {
                        writer.WriteAttributeString("reusingslot", reusingSlot.ToString(CultureInfo.InvariantCulture));
                    }
                }
                writer.WriteEndElement(); // </local>
            }
851

852
            foreach (ISymUnmanagedConstant c in scope.GetConstants())
P
Pilchie 已提交
853 854 855 856 857 858 859 860 861 862 863
            {
                // Note: We can retrieve constant tokens by saving it into signature blob
                // in our implementation of IMetadataImport.GetSigFromToken.
                writer.WriteStartElement("constant");
                {
                    writer.WriteAttributeString("name", c.GetName());
                    
                    object value = c.GetValue();
                    string typeName = value.GetType().Name;

                    // certain Unicode characters will give Xml writers fits...in order to avoid this, we'll replace
864
                    // problematic characters/sequences with their hexadecimal equivalents, like U+0000, etc...
P
Pilchie 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
                    var chars = value as string;
                    if (chars != null)
                    {
                        PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
                        var valueWithPlaceholders = pooled.Builder;
                        foreach (var ch in chars)
                        {
                            // if we end up with more, we can add them here
                            if (0 == (int)ch)
                            {
                                valueWithPlaceholders.AppendFormat("U+{0:X4}", (int)ch);
                            }
                            else
                            {
                                valueWithPlaceholders.Append(ch);
                            }
                        }
                        if (valueWithPlaceholders.Length > chars.Length)
                        {
                            value = valueWithPlaceholders.ToString();
                        }
                        pooled.Free();
                    }

                    writer.WriteAttributeString("value", value.ToString());
                    writer.WriteAttributeString("type", typeName);
                }
                writer.WriteEndElement(); // </constant>
            }
894

P
Pilchie 已提交
895 896
            if (includeChildScopes)
            {
897
                foreach (ISymUnmanagedScope childScope in scope.GetScopes())
P
Pilchie 已提交
898 899 900 901 902 903 904 905 906
                {
                    WriteLocalsHelper(childScope, slotNames, includeChildScopes);
                }
            }
        }

        // Write the sequence points for the given method
        // Sequence points are the map between IL offsets and source lines.
        // A single method could span multiple files (use C#'s #line directive to see for yourself).        
907
        private void WriteSequencePoints(ISymUnmanagedMethod method)
P
Pilchie 已提交
908
        {
T
TomasMatousek 已提交
909
            writer.WriteStartElement("sequencePoints");
P
Pilchie 已提交
910

911 912
            var sequencePoints = method.GetSequencePoints();
            
P
Pilchie 已提交
913
            // Write out sequence points
914
            foreach (var sequencePoint in sequencePoints)
P
Pilchie 已提交
915 916
            {
                writer.WriteStartElement("entry");
T
TomasMatousek 已提交
917
                writer.WriteAttributeString("offset", AsILOffset(sequencePoint.Offset));
P
Pilchie 已提交
918 919 920 921

                // If it's a special 0xFeeFee sequence point (eg, "hidden"), 
                // place an attribute on it to make it very easy for tools to recognize.
                // See http://blogs.msdn.com/jmstall/archive/2005/06/19/FeeFee_SequencePoints.aspx
922
                if (sequencePoint.IsHidden)
P
Pilchie 已提交
923
                {
T
TomasMatousek 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
                    if (sequencePoint.StartLine != sequencePoint.EndLine || sequencePoint.StartColumn != 0 || sequencePoint.EndColumn != 0)
                    {
                        writer.WriteAttributeString("hidden", "invalid");
                    }
                    else
                    {
                        writer.WriteAttributeString("hidden", XmlConvert.ToString(true));
                    }
                }
                else
                {
                    writer.WriteAttributeString("startLine", CultureInvariantToString(sequencePoint.StartLine));
                    writer.WriteAttributeString("startColumn", CultureInvariantToString(sequencePoint.StartColumn));
                    writer.WriteAttributeString("endLine", CultureInvariantToString(sequencePoint.EndLine));
                    writer.WriteAttributeString("endColumn", CultureInvariantToString(sequencePoint.EndColumn));
P
Pilchie 已提交
939 940 941 942
                }

                //EDMAURER allow there to be PDBs generated for sources that don't have a name (document).
                int fileRefVal = -1;
943
                this.m_fileMapping.TryGetValue(sequencePoint.Document.GetName(), out fileRefVal);
T
TomasMatousek 已提交
944
                writer.WriteAttributeString("document", CultureInvariantToString(fileRefVal));
P
Pilchie 已提交
945 946 947 948 949 950 951 952 953 954 955

                writer.WriteEndElement();
            }

            writer.WriteEndElement(); // sequencepoints
        }

        // Write all docs, and add to the m_fileMapping list.
        // Other references to docs will then just refer to this list.
        private void WriteDocList()
        {
956 957
            var documents = pdbReader.SymbolReader.GetDocuments();
            if (documents.Length == 0)
P
Pilchie 已提交
958 959 960 961 962 963
            {
                return;
            }

            int id = 0;
            writer.WriteStartElement("files");
964
            foreach (ISymUnmanagedDocument doc in documents)
P
Pilchie 已提交
965
            {
966
                string name = doc.GetName();
P
Pilchie 已提交
967 968

                // Symbol store may give out duplicate documents. We'll fold them here
969
                if (m_fileMapping.ContainsKey(name))
P
Pilchie 已提交
970
                {
971
                    writer.WriteComment("There is a duplicate entry for: " + name);
P
Pilchie 已提交
972 973 974 975
                    continue;
                }

                id++;
976
                m_fileMapping.Add(name, id);
P
Pilchie 已提交
977 978 979

                writer.WriteStartElement("file");

980 981 982 983 984
                writer.WriteAttributeString("id", CultureInvariantToString(id));
                writer.WriteAttributeString("name", name);
                writer.WriteAttributeString("language", doc.GetLanguage().ToString());
                writer.WriteAttributeString("languageVendor", doc.GetLanguageVendor().ToString());
                writer.WriteAttributeString("documentType", doc.GetDocumentType().ToString());
P
Pilchie 已提交
985

986 987 988 989 990 991
                var checkSum = string.Concat(doc.GetCheckSum().Select(b => string.Format("{0,2:X}", b) + ", ")) ;

                if (!string.IsNullOrEmpty(checkSum))
                {
                    writer.WriteAttributeString("checkSumAlgorithmId", doc.GetHashAlgorithm().ToString());
                    writer.WriteAttributeString("checkSum", checkSum);
P
Pilchie 已提交
992 993 994 995 996 997 998 999 1000 1001 1002
                }

                writer.WriteEndElement(); // file
            }
            writer.WriteEndElement(); // files
        }

        private void WriteAllMethodSpans()
        {
            writer.WriteStartElement("method-spans");

1003
            foreach (ISymUnmanagedDocument doc in pdbReader.SymbolReader.GetDocuments())
P
Pilchie 已提交
1004
            {
1005
                foreach (ISymUnmanagedMethod method in pdbReader.SymbolReader.GetMethodsInDocument(doc))
P
Pilchie 已提交
1006 1007 1008
                {
                    writer.WriteStartElement("method");

1009
                    WriteMethodAttributes(method.GetToken(), isReference: true);
P
Pilchie 已提交
1010

1011
                    foreach (var methodDocument in method.GetDocumentsForMethod())
P
Pilchie 已提交
1012 1013 1014 1015
                    {
                        writer.WriteStartElement("document");
                        
                        int startLine, endLine;
1016
                        method.GetSourceExtentInDocument(methodDocument, out startLine, out endLine);
P
Pilchie 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

                        writer.WriteAttributeString("startLine", startLine.ToString());
                        writer.WriteAttributeString("endLine", endLine.ToString());

                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }
            }

            writer.WriteEndElement();
        }

        // Write out a reference to the entry point method (if one exists)
        private void WriteEntryPoint()
        {
1034 1035
            int token = pdbReader.SymbolReader.GetUserEntryPoint();
            if (token != 0)
P
Pilchie 已提交
1036
            {
1037 1038 1039
                writer.WriteStartElement("entryPoint");
                WriteMethodAttributes(token, isReference: true);
                writer.WriteEndElement();
P
Pilchie 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
            }
        }

        // Write out XML snippet to refer to the given method.
        private void WriteMethodAttributes(int token, bool isReference)
        {
            if ((options & PdbToXmlOptions.ResolveTokens) != 0)
            {
                var handle = MetadataTokens.Handle(token);

                try
                {
A
angocke 已提交
1052
                    switch (handle.Kind)
P
Pilchie 已提交
1053
                    {
A
angocke 已提交
1054 1055
                        case HandleKind.MethodDefinition:
                            WriteResolvedToken((MethodDefinitionHandle)handle, isReference);
P
Pilchie 已提交
1056 1057
                            break;

A
angocke 已提交
1058
                        case HandleKind.MemberReference:
P
Pilchie 已提交
1059 1060 1061 1062 1063
                            WriteResolvedToken((MemberReferenceHandle)handle);
                            break;

                        default:
                            WriteToken(token);
A
angocke 已提交
1064
                            writer.WriteAttributeString("error", string.Format("Unexpected token type: {0}", handle.Kind));
P
Pilchie 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
                            break;
                    }
                }
                catch (BadImageFormatException e) // TODO: filter
                {
                    if ((options & PdbToXmlOptions.ThrowOnError) != 0)
                    {
                        throw;
                    }

                    WriteToken(token);
                    writer.WriteAttributeString("metadata-error", e.Message);
                }
            }

            if ((options & PdbToXmlOptions.IncludeTokens) != 0)
            {
                WriteToken(token);
            }
        }

A
angocke 已提交
1086
        private static string GetQualifiedMethodName(MetadataReader metadataReader, MethodDefinitionHandle methodHandle)
P
Pilchie 已提交
1087
        {
A
angocke 已提交
1088 1089
            var method = metadataReader.GetMethodDefinition(methodHandle);
            var containingTypeHandle = method.GetDeclaringType();
P
Pilchie 已提交
1090 1091 1092 1093 1094 1095 1096

            string fullTypeName = GetFullTypeName(metadataReader, containingTypeHandle);
            string methodName = metadataReader.GetString(method.Name);

            return fullTypeName != null ? fullTypeName + "." + methodName : methodName;
        }

A
angocke 已提交
1097
        private void WriteResolvedToken(MethodDefinitionHandle methodHandle, bool isReference)
P
Pilchie 已提交
1098
        {
A
angocke 已提交
1099
            var method = metadataReader.GetMethodDefinition(methodHandle);
P
Pilchie 已提交
1100 1101

            // type name
A
angocke 已提交
1102
            var containingTypeHandle = method.GetDeclaringType();
P
Pilchie 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
            var fullName = GetFullTypeName(metadataReader, containingTypeHandle);
            if (fullName != null)
            {
                writer.WriteAttributeString(isReference ? "declaringType" :  "containingType", fullName);
            }

            // method name
            writer.WriteAttributeString(isReference ? "methodName" : "name", metadataReader.GetString(method.Name));

            // parameters:
T
TomasMatousek 已提交
1113 1114 1115 1116
            var parameterNames = (from paramHandle in method.GetParameters()
                                  let parameter = metadataReader.GetParameter(paramHandle)
                                  where parameter.SequenceNumber > 0 // exclude return parameter
                                  select parameter.Name.IsNil ? "?" : metadataReader.GetString(parameter.Name)).ToArray();
P
Pilchie 已提交
1117

T
TomasMatousek 已提交
1118 1119 1120 1121
            if (parameterNames.Length > 0)
            {
                writer.WriteAttributeString("parameterNames", string.Join(", ", parameterNames));
            }
P
Pilchie 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
        }

        private void WriteResolvedToken(MemberReferenceHandle memberRefHandle)
        {
            var memberRef = metadataReader.GetMemberReference(memberRefHandle);

            // type name
            string fullName = GetFullTypeName(metadataReader, memberRef.Parent);
            if (fullName != null)
            {
                writer.WriteAttributeString("declaringType", fullName);
            }

            // method name
            writer.WriteAttributeString("methodName", metadataReader.GetString(memberRef.Name));
        }

        private static bool IsNested(TypeAttributes flags)
        {
            return (flags & ((TypeAttributes)0x00000006)) != 0;
        }

        private static string GetFullTypeName(MetadataReader metadataReader, Handle handle)
        {
            if (handle.IsNil)
            {
                return null;
            }

A
angocke 已提交
1151
            if (handle.Kind == HandleKind.TypeDefinition)
P
Pilchie 已提交
1152
            {
A
angocke 已提交
1153
                var type = metadataReader.GetTypeDefinition((TypeDefinitionHandle)handle);
P
Pilchie 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
                string name = metadataReader.GetString(type.Name);

                while (IsNested(type.Attributes))
                {
                    var enclosingType = metadataReader.GetTypeDefinition(type.GetDeclaringType());
                    name = metadataReader.GetString(enclosingType.Name) + "+" + name;
                    type = enclosingType;
                }

                if (type.Namespace.IsNil)
                {
                    return name;
                }

                return metadataReader.GetString(type.Namespace) + "." + name;
            }

A
angocke 已提交
1171
            if (handle.Kind == HandleKind.TypeReference)
P
Pilchie 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
            {
                var typeRef = metadataReader.GetTypeReference((TypeReferenceHandle)handle);
                string name = metadataReader.GetString(typeRef.Name);
                if (typeRef.Namespace.IsNil)
                {
                    return name;
                }

                return metadataReader.GetString(typeRef.Namespace) + "." + name;
            }

            return string.Format("<unexpected token kind: {0}>", AsToken(metadataReader.GetToken(handle)));
        }

        #region Utils

        private void WriteToken(int token)
        {
            writer.WriteAttributeString("token", AsToken(token));
        }

        internal static string AsToken(int i)
        {
1195
            return string.Format(CultureInfo.InvariantCulture, "0x{0:x}", i);
P
Pilchie 已提交
1196 1197
        }

1198
        internal static string AsILOffset(int i)
P
Pilchie 已提交
1199
        {
1200
            return string.Format(CultureInfo.InvariantCulture, "0x{0:x}", i);
P
Pilchie 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
        }

        internal static int ToInt32(string input)
        {
            return ToInt32(input, 10);
        }

        internal static int ToInt32(string input, int numberBase)
        {
            return Convert.ToInt32(input, numberBase);
        }

        internal static string ToHexString(byte[] input)
        {
            PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
            StringBuilder sb = pooled.Builder;
            foreach (byte b in input)
            {
                sb.AppendFormat("{0:X2}", b);
            }
            return pooled.ToStringAndFree();
        }

        internal static byte[] ToByteArray(string input)
        {
            byte[] retval = new byte[input.Length];
            for (int i = 0; i < input.Length; i++)
            {
                retval[i] = Convert.ToByte(input[i]);
            }
            return retval;
        }

        internal static string CultureInvariantToString(int input)
        {
            return input.ToString(CultureInfo.InvariantCulture);
        }

        internal static void Error(string message)
        {
            Console.WriteLine("Error: {0}", message);
            Debug.Assert(false, message);
        }

        #endregion
    }
}