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

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
        {
            var writer = new StringWriter();
            ToXml(
51 52
                writer,
                deltaPdb,
P
Pilchie 已提交
53
                metadataReaderOpt: null,
54
                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
                }

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

                converter.WriteRoot(methodHandles ?? metadataReaderOpt.MethodDefinitions);
            }
146

P
Pilchie 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
            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
            byte[] cdi = pdbReader.SymbolReader.GetCustomDebugInfoBytes(token, methodVersion: 0);
202 203
            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
            var records = CustomDebugInfoReader.GetCustomDebugInfoRecords(bytes).ToArray();
264

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;
298 299 300
                        case CustomDebugInfoKind.EditAndContinueLambdaMap:
                            WriteEditAndContinueLambdaMap(record);
                            break;
P
Pilchie 已提交
301
                        default:
302
                            WriteUnknownCustomDebugInfo(record);
P
Pilchie 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315
                            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>
316
        private void WriteUnknownCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
317 318
        {
            writer.WriteStartElement("unknown");
T
TomasMatousek 已提交
319 320
            writer.WriteAttributeString("kind", record.Kind.ToString());
            writer.WriteAttributeString("version", record.Version.ToString());
P
Pilchie 已提交
321 322 323

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

P
Pilchie 已提交
329 330 331 332 333 334 335 336 337 338 339 340
            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>
341
        private void WriteUsingCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
342
        {
343
            Debug.Assert(record.Kind == CustomDebugInfoKind.UsingInfo);
P
Pilchie 已提交
344 345 346

            writer.WriteStartElement("using");

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

            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>
366
        private void WriteForwardCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
367
        {
368
            Debug.Assert(record.Kind == CustomDebugInfoKind.ForwardInfo);
P
Pilchie 已提交
369 370 371

            writer.WriteStartElement("forward");

372
            int token = CDI.DecodeForwardRecord(record.Data);
P
Pilchie 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385
            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>
386
        private void WriteForwardToModuleCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
387
        {
388
            Debug.Assert(record.Kind == CustomDebugInfoKind.ForwardToModuleInfo);
P
Pilchie 已提交
389 390 391

            writer.WriteStartElement("forwardToModule");

392
            int token = CDI.DecodeForwardRecord(record.Data);
P
Pilchie 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405
            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>
406
        private void WriteStatemachineHoistedLocalScopesCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
407
        {
408
            Debug.Assert(record.Kind == CustomDebugInfoKind.StateMachineHoistedLocalScopes);
P
Pilchie 已提交
409

410
            writer.WriteStartElement("hoistedLocalScopes");
P
Pilchie 已提交
411

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

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

422
            writer.WriteEndElement();
P
Pilchie 已提交
423 424 425 426 427 428 429 430 431
        }

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

            writer.WriteStartElement("forwardIterator");

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

            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>
452
        private void WriteDynamicLocalsCustomDebugInfo(CustomDebugInfoRecord record)
P
Pilchie 已提交
453
        {
454
            Debug.Assert(record.Kind == CustomDebugInfoKind.DynamicLocals);
P
Pilchie 已提交
455 456 457

            writer.WriteStartElement("dynamicLocals");

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

            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
        }

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

            writer.WriteStartElement("encLocalSlotMap");
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
            try
            {
                int syntaxOffsetBaseline = -1;

                fixed (byte* compressedSlotMapPtr = &record.Data.ToArray()[0])
                {
                    var blobReader = new BlobReader(compressedSlotMapPtr, record.Data.Length);

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

                        if (b == 0xff)
                        {
                            if (!blobReader.TryReadCompressedInteger(out syntaxOffsetBaseline))
                            {
                                writer.WriteElementString("baseline", "?");
                                return;
                            }

                            syntaxOffsetBaseline = -syntaxOffsetBaseline;
                            continue;
                        }
511

512 513 514 515 516 517 518 519 520 521 522
                        writer.WriteStartElement("slot");

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

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
                            int syntaxOffset;
                            bool badSyntaxOffset = !blobReader.TryReadCompressedInteger(out syntaxOffset);
                            syntaxOffset += syntaxOffsetBaseline;

                            int ordinal = 0;
                            bool badOrdinal = hasOrdinal && !blobReader.TryReadCompressedInteger(out ordinal);

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

                            if (badOrdinal || hasOrdinal)
                            {
                                writer.WriteAttributeString("ordinal", badOrdinal ? "?" : ordinal.ToString());
                            }
                        }

                        writer.WriteEndElement();
                    }
                }
            }
            finally
545
            {
546 547 548 549 550 551 552
                writer.WriteEndElement(); //encLocalSlotMap
            }
        }

        private unsafe void WriteEditAndContinueLambdaMap(CustomDebugInfoRecord record)
        {
            Debug.Assert(record.Kind == CustomDebugInfoKind.EditAndContinueLambdaMap);
553

554 555 556 557
            writer.WriteStartElement("encLambdaMap");
            try
            {
                if (record.Data.Length == 0)
558
                {
559 560
                    return;
                }
561

562 563 564 565 566 567 568 569 570
                int methodOrdinal = -1;
                int syntaxOffsetBaseline = -1;
                int closureCount;

                fixed (byte* blobPtr = &record.Data.ToArray()[0])
                {
                    var blobReader = new BlobReader(blobPtr, record.Data.Length);

                    if (!blobReader.TryReadCompressedInteger(out methodOrdinal))
571
                    {
572 573 574
                        writer.WriteElementString("methodOrdinal", "?");
                        writer.WriteEndElement();
                        return;
575 576
                    }

577 578 579 580 581
                    // [-1, inf)
                    methodOrdinal--;
                    writer.WriteElementString("methodOrdinal", methodOrdinal.ToString());

                    if (!blobReader.TryReadCompressedInteger(out syntaxOffsetBaseline))
582
                    {
583 584 585
                        writer.WriteElementString("baseline", "?");
                        writer.WriteEndElement();
                        return;
586 587
                    }

588 589
                    syntaxOffsetBaseline = -syntaxOffsetBaseline;
                    if (!blobReader.TryReadCompressedInteger(out closureCount))
590
                    {
591 592 593
                        writer.WriteElementString("closureCount", "?");
                        writer.WriteEndElement();
                        return;
594
                    }
595 596

                    for (int i = 0; i < closureCount; i++)
597
                    {
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
                        writer.WriteStartElement("closure");
                        try
                        {
                            int syntaxOffset;
                            if (!blobReader.TryReadCompressedInteger(out syntaxOffset))
                            {
                                writer.WriteElementString("offset", "?");
                                break;
                            }

                            writer.WriteAttributeString("offset", (syntaxOffset + syntaxOffsetBaseline).ToString());
                        }
                        finally
                        {
                            writer.WriteEndElement();
                        }
                    }
615

616 617 618 619 620 621 622 623 624 625 626
                    while (blobReader.RemainingBytes > 0)
                    {
                        writer.WriteStartElement("lambda");
                        try
                        {
                            int syntaxOffset;
                            if (!blobReader.TryReadCompressedInteger(out syntaxOffset))
                            {
                                writer.WriteElementString("offset", "?");
                                return;
                            }
627

628
                            writer.WriteAttributeString("offset", (syntaxOffset + syntaxOffsetBaseline).ToString());
629

630 631 632 633 634 635
                            int closureOrdinal;
                            if (!blobReader.TryReadCompressedInteger(out closureOrdinal))
                            {
                                writer.WriteElementString("closure", "?");
                                return;
                            }
636

637 638 639 640 641 642 643 644
                            closureOrdinal--;
                            if (closureOrdinal != -1)
                            {
                                writer.WriteAttributeString("closure",
                                    closureOrdinal.ToString() + (closureOrdinal < -1 || closureOrdinal >= closureCount ? " (invalid)" : ""));
                            }
                        }
                        finally
645
                        {
646
                            writer.WriteEndElement();
647 648 649 650
                        }
                    }
                }
            }
651 652 653 654
            finally
            {
                writer.WriteEndElement(); //encLocalSlotMap
            }
655 656
        }

P
Pilchie 已提交
657 658 659 660
        private void WriteScopes(ISymUnmanagedScope scope)
        {
            writer.WriteStartElement("scope");
            {
661 662
                writer.WriteAttributeString("startOffset", AsILOffset(scope.GetStartOffset()));
                writer.WriteAttributeString("endOffset", AsILOffset(scope.GetEndOffset()));
P
Pilchie 已提交
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
                {
                    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;
694 695
                    var parsingSucceeded = CDI.TryParseVisualBasicImportString(rawName, out alias, out target, out kind, out scope);
                    Debug.Assert(parsingSucceeded);
P
Pilchie 已提交
696 697 698 699 700 701 702 703 704 705
                }
                else
                {
                    switch (rawName[0])
                    {
                        case 'U':
                        case 'A':
                        case 'X':
                        case 'Z':
                        case 'E':
706
                        case 'T':
P
Pilchie 已提交
707
                            scope = ImportScope.Unspecified;
708 709 710 711
                            if (!CDI.TryParseCSharpImportString(rawName, out alias, out externAlias, out target, out kind))
                            {
                                throw new InvalidOperationException(string.Format("Invalid import '{0}'", rawName));
                            }
P
Pilchie 已提交
712 713 714 715
                            break;

                        default:
                            externAlias = null;
716 717 718 719
                            if (!CDI.TryParseVisualBasicImportString(rawName, out alias, out target, out kind, out scope))
                            {
                                throw new InvalidOperationException(string.Format("Invalid import '{0}'", rawName));
                            }
P
Pilchie 已提交
720 721 722 723 724 725 726 727 728 729 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 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
                            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:
821 822
                    Debug.Assert(alias != null);
                    Debug.Assert(externAlias == null);
P
Pilchie 已提交
823 824 825 826
                    Debug.Assert(scope == ImportScope.Unspecified);
                    if (target == null)
                    {
                        writer.WriteStartElement("extern");
827
                        writer.WriteAttributeString("alias", alias);
P
Pilchie 已提交
828 829 830 831 832
                        writer.WriteEndElement(); // </extern>
                    }
                    else
                    {
                        writer.WriteStartElement("externinfo");
833
                        writer.WriteAttributeString("alias", alias);
P
Pilchie 已提交
834 835 836 837
                        writer.WriteAttributeString("assembly", target);
                        writer.WriteEndElement(); // </externinfo>
                    }
                    break;
A
acasey 已提交
838 839 840 841 842 843 844
                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 已提交
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
                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 + "'");
            }
        }

870
        private void WriteAsyncInfo(ISymUnmanagedMethod method)
P
Pilchie 已提交
871
        {
872 873
            var asyncMethod = method.AsAsync();
            if (asyncMethod == null)
P
Pilchie 已提交
874
            {
875 876
                return;
            }
877

T
TomasMatousek 已提交
878
            writer.WriteStartElement("asyncInfo");
P
Pilchie 已提交
879

880 881 882
            var catchOffset = asyncMethod.GetCatchHandlerILOffset();
            if (catchOffset >= 0)
            {
T
TomasMatousek 已提交
883 884 885
                writer.WriteStartElement("catchHandler");
                writer.WriteAttributeString("offset", AsILOffset(catchOffset));
                writer.WriteEndElement();
P
Pilchie 已提交
886 887
            }

T
TomasMatousek 已提交
888
            writer.WriteStartElement("kickoffMethod");
889 890 891 892
            WriteMethodAttributes(asyncMethod.GetKickoffMethod(), isReference: true);
            writer.WriteEndElement();

            foreach (var info in asyncMethod.GetAsyncStepInfos())
P
Pilchie 已提交
893
            {
894 895 896 897 898
                writer.WriteStartElement("await");
                writer.WriteAttributeString("yield", AsILOffset(info.YieldOffset));
                writer.WriteAttributeString("resume", AsILOffset(info.ResumeOffset));
                WriteMethodAttributes(info.ResumeMethod, isReference: true);
                writer.WriteEndElement();
P
Pilchie 已提交
899 900
            }

901
            writer.WriteEndElement();
P
Pilchie 已提交
902 903 904 905 906 907 908 909 910 911 912
        }

        // 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");
913 914
            // If there are no locals, then this element will just be empty.
            WriteLocalsHelper(method.GetRootScope(), slotNames, includeChildScopes: true);
P
Pilchie 已提交
915 916 917
            writer.WriteEndElement();
        }

918
        private void WriteLocalsHelper(ISymUnmanagedScope scope, Dictionary<int, ImmutableArray<string>> slotNames, bool includeChildScopes)
P
Pilchie 已提交
919
        {
920
            foreach (ISymUnmanagedVariable l in scope.GetLocals())
P
Pilchie 已提交
921 922 923
            {
                writer.WriteStartElement("local");
                {
924
                    writer.WriteAttributeString("name", l.GetName());
P
Pilchie 已提交
925 926 927 928 929 930 931 932 933

                    // 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.
934
                    int slot = l.GetSlot();
P
Pilchie 已提交
935 936 937 938 939 940 941 942 943 944
                    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))
                        {
945
                            slotNames[slot] = existingNames.Add(l.GetName());
P
Pilchie 已提交
946 947 948 949
                            reusingSlot = true;
                        }
                        else
                        {
950
                            slotNames.Add(slot, ImmutableArray.Create(l.GetName()));
P
Pilchie 已提交
951 952 953 954
                        }
                    }

                    // Provide scope range
955 956 957
                    writer.WriteAttributeString("il_start", AsILOffset(scope.GetStartOffset()));
                    writer.WriteAttributeString("il_end", AsILOffset(scope.GetEndOffset()));
                    writer.WriteAttributeString("attributes", l.GetAttributes().ToString());
P
Pilchie 已提交
958 959 960 961 962 963 964 965

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

967
            foreach (ISymUnmanagedConstant c in scope.GetConstants())
P
Pilchie 已提交
968 969 970 971 972 973
            {
                // 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());
974

P
Pilchie 已提交
975 976 977 978
                    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
979
                    // problematic characters/sequences with their hexadecimal equivalents, like U+0000, etc...
P
Pilchie 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
                    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>
            }
1009

P
Pilchie 已提交
1010 1011
            if (includeChildScopes)
            {
1012
                foreach (ISymUnmanagedScope childScope in scope.GetScopes())
P
Pilchie 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021
                {
                    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).        
1022
        private void WriteSequencePoints(ISymUnmanagedMethod method)
P
Pilchie 已提交
1023
        {
T
TomasMatousek 已提交
1024
            writer.WriteStartElement("sequencePoints");
P
Pilchie 已提交
1025

1026
            var sequencePoints = method.GetSequencePoints();
1027

P
Pilchie 已提交
1028
            // Write out sequence points
1029
            foreach (var sequencePoint in sequencePoints)
P
Pilchie 已提交
1030 1031
            {
                writer.WriteStartElement("entry");
T
TomasMatousek 已提交
1032
                writer.WriteAttributeString("offset", AsILOffset(sequencePoint.Offset));
P
Pilchie 已提交
1033

1034
                if (sequencePoint.IsHidden)
P
Pilchie 已提交
1035
                {
T
TomasMatousek 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
                    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 已提交
1051 1052
                }

1053 1054 1055
                int documentId;
                this.m_fileMapping.TryGetValue(sequencePoint.Document.GetName(), out documentId);
                writer.WriteAttributeString("document", CultureInvariantToString(documentId));
P
Pilchie 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

                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()
        {
1067 1068
            var documents = pdbReader.SymbolReader.GetDocuments();
            if (documents.Length == 0)
P
Pilchie 已提交
1069 1070 1071 1072 1073 1074
            {
                return;
            }

            int id = 0;
            writer.WriteStartElement("files");
1075
            foreach (ISymUnmanagedDocument doc in documents)
P
Pilchie 已提交
1076
            {
1077
                string name = doc.GetName();
P
Pilchie 已提交
1078 1079

                // Symbol store may give out duplicate documents. We'll fold them here
1080
                if (m_fileMapping.ContainsKey(name))
P
Pilchie 已提交
1081
                {
1082
                    writer.WriteComment("There is a duplicate entry for: " + name);
P
Pilchie 已提交
1083 1084 1085 1086
                    continue;
                }

                id++;
1087
                m_fileMapping.Add(name, id);
P
Pilchie 已提交
1088 1089 1090

                writer.WriteStartElement("file");

1091 1092 1093 1094 1095
                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 已提交
1096

1097
                var checkSum = string.Concat(doc.GetCheckSum().Select(b => string.Format("{0,2:X}", b) + ", "));
1098 1099 1100 1101 1102

                if (!string.IsNullOrEmpty(checkSum))
                {
                    writer.WriteAttributeString("checkSumAlgorithmId", doc.GetHashAlgorithm().ToString());
                    writer.WriteAttributeString("checkSum", checkSum);
P
Pilchie 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
                }

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

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

1114
            foreach (ISymUnmanagedDocument doc in pdbReader.SymbolReader.GetDocuments())
P
Pilchie 已提交
1115
            {
1116
                foreach (ISymUnmanagedMethod method in pdbReader.SymbolReader.GetMethodsInDocument(doc))
P
Pilchie 已提交
1117 1118 1119
                {
                    writer.WriteStartElement("method");

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

1122
                    foreach (var methodDocument in method.GetDocumentsForMethod())
P
Pilchie 已提交
1123 1124
                    {
                        writer.WriteStartElement("document");
1125

P
Pilchie 已提交
1126
                        int startLine, endLine;
1127
                        method.GetSourceExtentInDocument(methodDocument, out startLine, out endLine);
P
Pilchie 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

                        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()
        {
1145 1146
            int token = pdbReader.SymbolReader.GetUserEntryPoint();
            if (token != 0)
P
Pilchie 已提交
1147
            {
1148 1149 1150
                writer.WriteStartElement("entryPoint");
                WriteMethodAttributes(token, isReference: true);
                writer.WriteEndElement();
P
Pilchie 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
            }
        }

        // 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 已提交
1163
                    switch (handle.Kind)
P
Pilchie 已提交
1164
                    {
A
angocke 已提交
1165 1166
                        case HandleKind.MethodDefinition:
                            WriteResolvedToken((MethodDefinitionHandle)handle, isReference);
P
Pilchie 已提交
1167 1168
                            break;

A
angocke 已提交
1169
                        case HandleKind.MemberReference:
P
Pilchie 已提交
1170 1171 1172 1173 1174
                            WriteResolvedToken((MemberReferenceHandle)handle);
                            break;

                        default:
                            WriteToken(token);
A
angocke 已提交
1175
                            writer.WriteAttributeString("error", string.Format("Unexpected token type: {0}", handle.Kind));
P
Pilchie 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
                            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 已提交
1197
        private static string GetQualifiedMethodName(MetadataReader metadataReader, MethodDefinitionHandle methodHandle)
P
Pilchie 已提交
1198
        {
A
angocke 已提交
1199 1200
            var method = metadataReader.GetMethodDefinition(methodHandle);
            var containingTypeHandle = method.GetDeclaringType();
P
Pilchie 已提交
1201 1202 1203 1204 1205 1206 1207

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

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

A
angocke 已提交
1208
        private void WriteResolvedToken(MethodDefinitionHandle methodHandle, bool isReference)
P
Pilchie 已提交
1209
        {
A
angocke 已提交
1210
            var method = metadataReader.GetMethodDefinition(methodHandle);
P
Pilchie 已提交
1211 1212

            // type name
A
angocke 已提交
1213
            var containingTypeHandle = method.GetDeclaringType();
P
Pilchie 已提交
1214 1215 1216
            var fullName = GetFullTypeName(metadataReader, containingTypeHandle);
            if (fullName != null)
            {
1217
                writer.WriteAttributeString(isReference ? "declaringType" : "containingType", fullName);
P
Pilchie 已提交
1218 1219 1220 1221 1222 1223
            }

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

            // parameters:
T
TomasMatousek 已提交
1224 1225 1226 1227
            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 已提交
1228

T
TomasMatousek 已提交
1229 1230 1231 1232
            if (parameterNames.Length > 0)
            {
                writer.WriteAttributeString("parameterNames", string.Join(", ", parameterNames));
            }
P
Pilchie 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        }

        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 已提交
1262
            if (handle.Kind == HandleKind.TypeDefinition)
P
Pilchie 已提交
1263
            {
A
angocke 已提交
1264
                var type = metadataReader.GetTypeDefinition((TypeDefinitionHandle)handle);
P
Pilchie 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
                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 已提交
1282
            if (handle.Kind == HandleKind.TypeReference)
P
Pilchie 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
            {
                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)
        {
1306
            return string.Format(CultureInfo.InvariantCulture, "0x{0:x}", i);
P
Pilchie 已提交
1307 1308
        }

1309
        internal static string AsILOffset(int i)
P
Pilchie 已提交
1310
        {
1311
            return string.Format(CultureInfo.InvariantCulture, "0x{0:x}", i);
P
Pilchie 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
        }

        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
    }
}