MethodILExtensions.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.
  2. using System;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using System.Reflection.Metadata;
  6. using System.Text;
  7. namespace AtomicEditor
  8. {
  9. public static class MethodILExtensions
  10. {
  11. public static unsafe string GetMethodIL(this ImmutableArray<byte> ilArray)
  12. {
  13. var result = new StringBuilder();
  14. fixed (byte* ilPtr = ilArray.ToArray())
  15. {
  16. int offset = 0;
  17. while (true)
  18. {
  19. // skip padding:
  20. while (offset < ilArray.Length && ilArray[offset] == 0)
  21. {
  22. offset++;
  23. }
  24. if (offset == ilArray.Length)
  25. {
  26. break;
  27. }
  28. var reader = new BlobReader(ilPtr + offset, ilArray.Length - offset);
  29. var methodIL = MethodBodyBlock.Create(reader);
  30. if (methodIL == null)
  31. {
  32. result.AppendFormat("<invalid byte 0x{0:X2} at offset {1}>", ilArray[offset], offset);
  33. offset++;
  34. }
  35. else
  36. {
  37. ILVisualizerAsTokens.Instance.DumpMethod(
  38. result,
  39. methodIL.MaxStack,
  40. methodIL.GetILContent(),
  41. ImmutableArray.Create<ILVisualizer.LocalInfo>(),
  42. ImmutableArray.Create<ILVisualizer.HandlerSpan>());
  43. offset += methodIL.Size;
  44. }
  45. }
  46. }
  47. return result.ToString();
  48. }
  49. }
  50. }