CSComponentInspector.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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.Collections.Immutable;
  3. //using Roslyn.Utilities;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.Text;
  9. using System.Reflection.Emit;
  10. using System.Reflection;
  11. using System.Reflection.Metadata;
  12. using System.Reflection.Metadata.Ecma335;
  13. using System.Reflection.PortableExecutable;
  14. // References
  15. //https://github.com/Microsoft/dotnetsamples/tree/master/System.Reflection.Metadata
  16. //https://github.com/dotnet/corefx/tree/master/src/System.Reflection.Metadata/tests
  17. //http://www.cnetion.com/getting-field-values-using-mono-cecil-qq-AUvBjRFgivICeoL1jxJy.php
  18. // https://github.com/Reactive-Extensions/IL2JS/blob/master/CCI2/PeReader/ILReader.cs
  19. // https://github.com/Reactive-Extensions/IL2JS
  20. // custom attr loading: https://github.com/Reactive-Extensions/IL2JS/blob/a4570f9c69b6c40d001e7539b952266d67609ca9/CST/PELoader.cs#L2352
  21. // custom attr: https://www.simple-talk.com/blogs/2011/06/03/anatomy-of-a-net-assembly-custom-attribute-encoding/
  22. // custom attr: https://github.com/jbevain/cecil/blob/67a2569688a13a6cb487f9af5c3418f7a8f43e3c/Mono.Cecil/AssemblyReader.cs
  23. // https://github.com/dotnet/roslyn/tree/master/src/Compilers/Core/Portable/MetadataReader
  24. namespace AtomicTools
  25. {
  26. public class CSComponentInspector
  27. {
  28. InspectorComponent _inspectorComponent;
  29. public CSComponentInspector (TypeDefinition typeDef, PEReader peFile, MetadataReader metaReader)
  30. {
  31. this.typeDef = typeDef;
  32. this.peFile = peFile;
  33. this.metaReader = metaReader;
  34. this._inspectorComponent = new InspectorComponent ();
  35. this._inspectorComponent.Name = metaReader.GetString (typeDef.Name);
  36. this._inspectorComponent.Namespace = metaReader.GetString (typeDef.Namespace);
  37. }
  38. // Inspect a CSComponent derived class
  39. internal InspectorComponent Inspect ()
  40. {
  41. var fields = typeDef.GetFields ();
  42. foreach (var fieldHandle in fields) {
  43. var inspectorField = new InspectorField ();
  44. var fieldDef = metaReader.GetFieldDefinition (fieldHandle);
  45. var customAttr = fieldDef.GetCustomAttributes ();
  46. foreach (var caHandle in customAttr) {
  47. // Look for InspectorAttribute
  48. if (DecodeCustomAttribute (caHandle, inspectorField)) {
  49. BlobReader sigReader = metaReader.GetBlobReader (fieldDef.Signature);
  50. SignatureHeader header = sigReader.ReadSignatureHeader ();
  51. if (header.Kind != SignatureKind.Field)
  52. continue;
  53. var typeCode = sigReader.ReadSignatureTypeCode ();
  54. string typeName = typeCode.ToString ();
  55. if (typeCode == SignatureTypeCode.TypeHandle) {
  56. EntityHandle token = sigReader.ReadTypeHandle ();
  57. HandleKind tokenType = token.Kind;
  58. if (tokenType == HandleKind.TypeDefinition) {
  59. // can store local enum typedefs
  60. // enum initializers are stored as constant value in the IL
  61. var typeDef = metaReader.GetTypeDefinition ((TypeDefinitionHandle)token);
  62. var baseTypeToken = typeDef.BaseType;
  63. if (baseTypeToken.Kind != HandleKind.TypeReference)
  64. continue;
  65. var baseTypeRef = metaReader.GetTypeReference ((TypeReferenceHandle)baseTypeToken);
  66. if (metaReader.GetString (baseTypeRef.Name) != "Enum")
  67. continue;
  68. inspectorField.IsEnum = true;
  69. typeName = metaReader.GetString (typeDef.Name);
  70. } else if (tokenType == HandleKind.TypeReference) {
  71. // TypeReference, ok
  72. var typeRef = metaReader.GetTypeReference ((TypeReferenceHandle)token);
  73. typeName = metaReader.GetString (typeRef.Name);
  74. } else {
  75. // ???
  76. continue;
  77. }
  78. }
  79. inspectorField.TypeName = typeName;
  80. inspectorField.Name = metaReader.GetString (fieldDef.Name);
  81. _inspectorComponent.Fields [inspectorField.Name] = inspectorField;
  82. break;
  83. }
  84. }
  85. }
  86. // There is no way to get the initializer value of a field
  87. // other than to inspect the IL code of the constructor
  88. var methods = typeDef.GetMethods ();
  89. foreach (var methodHandle in methods) {
  90. var methodDef = metaReader.GetMethodDefinition (methodHandle);
  91. if (metaReader.GetString (methodDef.Name) == ".ctor") {
  92. var body = peFile.GetMethodBody (methodDef.RelativeVirtualAddress);
  93. var ilBytes = body.GetILContent ();
  94. InspectILBlock (ilBytes, ilBytes.Length);
  95. }
  96. }
  97. //Dump ();
  98. return _inspectorComponent;
  99. }
  100. private bool DecodeCustomAttribute (CustomAttributeHandle caHandle, InspectorField inspectorField)
  101. {
  102. // GetCustomAttribute: https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/MetadataReader/MetadataDecoder.cs#L1370
  103. // Custom Attribute
  104. var ca = metaReader.GetCustomAttribute (caHandle);
  105. // MethodDefinitionHandle or MemberReferenceHandle
  106. if (ca.Constructor.Kind != HandleKind.MemberReference) {
  107. Console.WriteLine ("ca.Constructor.Kind != HandleKind.MemberReference");
  108. return false;
  109. }
  110. // constructor of the custom attr which contains the signature
  111. var memberRef = metaReader.GetMemberReference ((MemberReferenceHandle)ca.Constructor);
  112. // parent of the constructor is the TypeReference
  113. var parent = memberRef.Parent;
  114. if (parent.Kind != HandleKind.TypeReference) {
  115. Console.WriteLine ("parent.Kind != HandleKind.TypeReference");
  116. return false;
  117. }
  118. var parentTypeRef = metaReader.GetTypeReference ((TypeReferenceHandle)parent);
  119. // check whether we have an InspectorAttribute
  120. if (metaReader.GetString (parentTypeRef.Name) != "InspectorAttribute") {
  121. Console.WriteLine ("parentTypeRef != InspectorAttribute");
  122. return false;
  123. }
  124. // args
  125. var argsReader = metaReader.GetBlobReader ((BlobHandle)ca.Value);
  126. uint prolog = argsReader.ReadUInt16 ();
  127. if (prolog != 1) {
  128. Console.WriteLine ("prolog != 1");
  129. return false;
  130. }
  131. // sig reader is on constructor
  132. BlobReader sigReader = metaReader.GetBlobReader (memberRef.Signature);
  133. SignatureHeader header = sigReader.ReadSignatureHeader ();
  134. // Get the type parameter count.
  135. if (header.IsGeneric && sigReader.ReadCompressedInteger () != 0) {
  136. Console.WriteLine ("header.IsGeneric && sigReader.ReadCompressedInteger() != 0");
  137. return false;
  138. }
  139. // Get the parameter count
  140. int paramCount = sigReader.ReadCompressedInteger ();
  141. // Get the type return type.
  142. var returnTypeCode = sigReader.ReadSignatureTypeCode ();
  143. if (returnTypeCode != SignatureTypeCode.Void) {
  144. Console.WriteLine ("returnTypeCode != SignatureTypeCode.Void");
  145. return false;
  146. }
  147. List<SignatureTypeCode> sigTypeCodes = new List<SignatureTypeCode> ();
  148. // position args
  149. for (int i = 0; i < paramCount; i++) {
  150. SignatureTypeCode paramTypeCode = sigReader.ReadSignatureTypeCode ();
  151. // support string custom attr for now to simplify things
  152. if (paramTypeCode != SignatureTypeCode.String)
  153. return false;
  154. string value;
  155. if (CrackStringInAttributeValue (out value, ref argsReader)) {
  156. inspectorField.CustomAttrPositionalArgs.Add (value);
  157. }
  158. sigTypeCodes.Add (paramTypeCode);
  159. }
  160. // named args
  161. short namedParamCount = argsReader.ReadInt16 ();
  162. for (short i = 0; i < namedParamCount; i++) {
  163. // Ecma-335 23.3 - A NamedArg is simply a FixedArg preceded by information to identify which field or
  164. // property it represents. [Note: Recall that the CLI allows fields and properties to have the same name; so
  165. // we require a means to disambiguate such situations. end note] FIELD is the single byte 0x53. PROPERTY is
  166. // the single byte 0x54.
  167. // https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/MetadataReader/MetadataDecoder.cs#L1305
  168. var kind = (CustomAttributeNamedArgumentKind)argsReader.ReadCompressedInteger ();
  169. if (kind != CustomAttributeNamedArgumentKind.Field && kind != CustomAttributeNamedArgumentKind.Property) {
  170. return false;
  171. }
  172. var typeCode = argsReader.ReadSerializationTypeCode ();
  173. // support string custom attr for now to simplify things
  174. if (typeCode != SerializationTypeCode.String)
  175. return false;
  176. string name;
  177. if (!CrackStringInAttributeValue (out name, ref argsReader))
  178. return false;
  179. string value;
  180. if (!CrackStringInAttributeValue (out value, ref argsReader))
  181. return false;
  182. inspectorField.CustomAttrNamedArgs [name] = value;
  183. }
  184. return true;
  185. }
  186. internal static bool CrackStringInAttributeValue (out string value, ref BlobReader sig)
  187. {
  188. try {
  189. int strLen;
  190. if (sig.TryReadCompressedInteger (out strLen) && sig.RemainingBytes >= strLen) {
  191. value = sig.ReadUTF8 (strLen);
  192. // Trim null characters at the end to mimic native compiler behavior.
  193. // There are libraries that have them and leaving them in breaks tests.
  194. value = value.TrimEnd ('\0');
  195. return true;
  196. }
  197. value = null;
  198. // Strings are stored as UTF8, but 0xFF means NULL string.
  199. return sig.RemainingBytes >= 1 && sig.ReadByte () == 0xFF;
  200. } catch (BadImageFormatException) {
  201. value = null;
  202. return false;
  203. }
  204. }
  205. public void InspectILBlock (
  206. ImmutableArray<byte> ilBytes,
  207. int length,
  208. IReadOnlyList<HandlerSpan> spans = null,
  209. int blockOffset = 0,
  210. IReadOnlyDictionary<int, string> markers = null)
  211. {
  212. if (ilBytes == null) {
  213. return;
  214. }
  215. int spanIndex = 0;
  216. int curIndex = InspectILBlock (ilBytes, length, spans, blockOffset, 0, spanIndex, markers, out spanIndex);
  217. }
  218. private int InspectILBlock (
  219. ImmutableArray<byte> ilBytes,
  220. int length,
  221. IReadOnlyList<HandlerSpan> spans,
  222. int blockOffset,
  223. int curIndex,
  224. int spanIndex,
  225. IReadOnlyDictionary<int, string> markers,
  226. out int nextSpanIndex)
  227. {
  228. int lastSpanIndex = spanIndex - 1;
  229. List<string> loadedValues = new List<string> ();
  230. while (curIndex < length) {
  231. if (lastSpanIndex > 0 && StartsFilterHandler (spans, lastSpanIndex, curIndex + blockOffset)) {
  232. }
  233. if (StartsSpan (spans, spanIndex, curIndex + blockOffset)) {
  234. curIndex = InspectILBlock (ilBytes, length, spans, blockOffset, curIndex, spanIndex + 1, markers, out spanIndex);
  235. } else {
  236. int ilOffset = curIndex + blockOffset;
  237. string marker;
  238. if (markers != null && markers.TryGetValue (ilOffset, out marker)) {
  239. } else {
  240. }
  241. OpCode opCode;
  242. int expectedSize;
  243. byte op1 = ilBytes [curIndex++];
  244. if (op1 == 0xfe && curIndex < length) {
  245. byte op2 = ilBytes [curIndex++];
  246. opCode = s_twoByteOpCodes [op2];
  247. expectedSize = 2;
  248. } else {
  249. opCode = s_oneByteOpCodes [op1];
  250. expectedSize = 1;
  251. }
  252. if (opCode.Size != expectedSize) {
  253. //sb.AppendLine(string.Format(" <unknown 0x{0}{1:X2}>", expectedSize == 2 ? "fe" : "", op1));
  254. continue;
  255. }
  256. //sb.Append(" ");
  257. // Console.WriteLine (opCode.OperandType == OperandType.InlineNone ? "{0} {1}" : "{0,-10} {1}", opCode, opCode.OperandType);
  258. switch (opCode.OperandType) {
  259. case OperandType.InlineField:
  260. // read token
  261. uint fieldToken = ReadUInt32 (ilBytes, ref curIndex);
  262. // get the kind
  263. uint tokenKind = fieldToken & TokenTypeIds.TokenTypeMask;
  264. // and the rowId
  265. uint rowId = fieldToken & TokenTypeIds.RIDMask;
  266. var fieldHandle = MetadataTokens.FieldDefinitionHandle ((int)rowId);
  267. var fieldDef = metaReader.GetFieldDefinition (fieldHandle);
  268. var fieldName = metaReader.GetString (fieldDef.Name);
  269. if (opCode.ToString () == "stfld") {
  270. InspectorField inspectorField;
  271. if (_inspectorComponent.Fields.TryGetValue (fieldName, out inspectorField)) {
  272. inspectorField.DefaultValue = String.Join (" ", loadedValues.ToArray ());
  273. }
  274. }
  275. loadedValues.Clear ();
  276. break;
  277. case OperandType.InlineMethod:
  278. // new Vector3, etc
  279. if (opCode.ToString () == "newobj") {
  280. } else
  281. loadedValues.Clear ();
  282. break;
  283. case OperandType.InlineTok:
  284. case OperandType.InlineType:
  285. ReadUInt32 (ilBytes, ref curIndex);
  286. loadedValues.Clear ();
  287. break;
  288. case OperandType.InlineSig: // signature (calli), not emitted by C#/VB
  289. ReadUInt32 (ilBytes, ref curIndex);
  290. loadedValues.Clear ();
  291. break;
  292. case OperandType.InlineString:
  293. //sb.Append(" 391 ");
  294. //sb.Append(VisualizeUserString());
  295. uint stringToken = ReadUInt32 (ilBytes, ref curIndex);
  296. // get the kind
  297. //uint tokenKind = stringToken & TokenTypeIds.TokenTypeMask;
  298. // and the rowId
  299. //uint rowId = stringToken & TokenTypeIds.RIDMask;
  300. UserStringHandle handle = MetadataTokens.UserStringHandle ((int)stringToken);
  301. loadedValues.Add (metaReader.GetUserString (handle));
  302. break;
  303. case OperandType.InlineNone:
  304. if (opCode == OpCodes.Ldc_I4_0)
  305. loadedValues.Add ("0");
  306. else if (opCode == OpCodes.Ldc_I4_1)
  307. loadedValues.Add ("1");
  308. else if (opCode == OpCodes.Ldc_I4_2)
  309. loadedValues.Add ("2");
  310. else if (opCode == OpCodes.Ldc_I4_3)
  311. loadedValues.Add ("3");
  312. else if (opCode == OpCodes.Ldc_I4_4)
  313. loadedValues.Add ("4");
  314. else if (opCode == OpCodes.Ldc_I4_5)
  315. loadedValues.Add ("5");
  316. else if (opCode == OpCodes.Ldc_I4_6)
  317. loadedValues.Add ("6");
  318. else if (opCode == OpCodes.Ldc_I4_7)
  319. loadedValues.Add ("7");
  320. else if (opCode == OpCodes.Ldc_I4_8)
  321. loadedValues.Add ("8");
  322. else if (opCode == OpCodes.Ldc_I4_M1)
  323. loadedValues.Add ("-1");
  324. break;
  325. case OperandType.ShortInlineI:
  326. loadedValues.Add (ReadSByte (ilBytes, ref curIndex).ToString ());
  327. break;
  328. case OperandType.ShortInlineVar:
  329. loadedValues.Add (ReadByte (ilBytes, ref curIndex).ToString ());
  330. break;
  331. case OperandType.InlineVar:
  332. loadedValues.Add (ReadUInt16 (ilBytes, ref curIndex).ToString ());
  333. break;
  334. case OperandType.InlineI:
  335. loadedValues.Add (ReadUInt32 (ilBytes, ref curIndex).ToString ());
  336. break;
  337. case OperandType.InlineI8:
  338. loadedValues.Add (ReadUInt64 (ilBytes, ref curIndex).ToString ());
  339. break;
  340. case OperandType.ShortInlineR:
  341. {
  342. loadedValues.Add (ReadSingle (ilBytes, ref curIndex).ToString ());
  343. }
  344. break;
  345. case OperandType.InlineR:
  346. {
  347. loadedValues.Add (ReadDouble (ilBytes, ref curIndex).ToString ());
  348. }
  349. break;
  350. case OperandType.ShortInlineBrTarget:
  351. loadedValues.Clear ();
  352. var sbyteValue = ReadSByte (ilBytes, ref curIndex) + curIndex + blockOffset;
  353. break;
  354. case OperandType.InlineBrTarget:
  355. loadedValues.Clear ();
  356. var int32value = ReadInt32 (ilBytes, ref curIndex) + curIndex + blockOffset;
  357. break;
  358. case OperandType.InlineSwitch:
  359. loadedValues.Clear ();
  360. int labelCount = ReadInt32 (ilBytes, ref curIndex);
  361. int instrEnd = curIndex + labelCount * 4;
  362. for (int i = 0; i < labelCount; i++) {
  363. var int32LabelValue = ReadInt32 (ilBytes, ref curIndex) + instrEnd + blockOffset;
  364. //sb.AppendLine((i == labelCount - 1) ? ")" : ",");
  365. }
  366. break;
  367. default:
  368. throw new InvalidOperationException ();
  369. //throw ExceptionUtilities.UnexpectedValue(opCode.OperandType);
  370. }
  371. //sb.AppendLine();
  372. }
  373. if (EndsSpan (spans, lastSpanIndex, curIndex + blockOffset)) {
  374. break;
  375. }
  376. }
  377. nextSpanIndex = spanIndex;
  378. return curIndex;
  379. }
  380. TypeDefinition typeDef;
  381. PEReader peFile;
  382. MetadataReader metaReader;
  383. private static readonly OpCode[] s_oneByteOpCodes;
  384. private static readonly OpCode[] s_twoByteOpCodes;
  385. static CSComponentInspector ()
  386. {
  387. s_oneByteOpCodes = new OpCode[0x100];
  388. s_twoByteOpCodes = new OpCode[0x100];
  389. var typeOfOpCode = typeof(OpCode);
  390. foreach (FieldInfo fi in typeof(OpCodes).GetTypeInfo().DeclaredFields) {
  391. if (fi.FieldType != typeOfOpCode) {
  392. continue;
  393. }
  394. OpCode opCode = (OpCode)fi.GetValue (null);
  395. var value = unchecked((ushort)opCode.Value);
  396. if (value < 0x100) {
  397. s_oneByteOpCodes [value] = opCode;
  398. } else if ((value & 0xff00) == 0xfe00) {
  399. s_twoByteOpCodes [value & 0xff] = opCode;
  400. }
  401. }
  402. }
  403. private static ulong ReadUInt64 (ImmutableArray<byte> buffer, ref int pos)
  404. {
  405. ulong result =
  406. buffer [pos] |
  407. (ulong)buffer [pos + 1] << 8 |
  408. (ulong)buffer [pos + 2] << 16 |
  409. (ulong)buffer [pos + 3] << 24 |
  410. (ulong)buffer [pos + 4] << 32 |
  411. (ulong)buffer [pos + 5] << 40 |
  412. (ulong)buffer [pos + 6] << 48 |
  413. (ulong)buffer [pos + 7] << 56;
  414. pos += sizeof(ulong);
  415. return result;
  416. }
  417. private static uint ReadUInt32 (ImmutableArray<byte> buffer, ref int pos)
  418. {
  419. uint result = buffer [pos] | (uint)buffer [pos + 1] << 8 | (uint)buffer [pos + 2] << 16 | (uint)buffer [pos + 3] << 24;
  420. pos += sizeof(uint);
  421. return result;
  422. }
  423. private static int ReadInt32 (ImmutableArray<byte> buffer, ref int pos)
  424. {
  425. return unchecked((int)ReadUInt32 (buffer, ref pos));
  426. }
  427. private static ushort ReadUInt16 (ImmutableArray<byte> buffer, ref int pos)
  428. {
  429. ushort result = (ushort)(buffer [pos] | buffer [pos + 1] << 8);
  430. pos += sizeof(ushort);
  431. return result;
  432. }
  433. private static byte ReadByte (ImmutableArray<byte> buffer, ref int pos)
  434. {
  435. byte result = buffer [pos];
  436. pos += sizeof(byte);
  437. return result;
  438. }
  439. private static sbyte ReadSByte (ImmutableArray<byte> buffer, ref int pos)
  440. {
  441. sbyte result = unchecked((sbyte)buffer [pos]);
  442. pos += 1;
  443. return result;
  444. }
  445. private unsafe static float ReadSingle (ImmutableArray<byte> buffer, ref int pos)
  446. {
  447. uint value = ReadUInt32 (buffer, ref pos);
  448. return *(float*)&value;
  449. }
  450. private unsafe static double ReadDouble (ImmutableArray<byte> buffer, ref int pos)
  451. {
  452. ulong value = ReadUInt64 (buffer, ref pos);
  453. return *(double*)&value;
  454. }
  455. public enum HandlerKind
  456. {
  457. Try,
  458. Catch,
  459. Filter,
  460. Finally,
  461. Fault
  462. }
  463. public struct HandlerSpan : IComparable<HandlerSpan>
  464. {
  465. public readonly HandlerKind Kind;
  466. public readonly object ExceptionType;
  467. public readonly int StartOffset;
  468. public readonly int FilterHandlerStart;
  469. public readonly int EndOffset;
  470. public HandlerSpan (HandlerKind kind, object exceptionType, int startOffset, int endOffset, int filterHandlerStart = 0)
  471. {
  472. this.Kind = kind;
  473. this.ExceptionType = exceptionType;
  474. this.StartOffset = startOffset;
  475. this.EndOffset = endOffset;
  476. this.FilterHandlerStart = filterHandlerStart;
  477. }
  478. public int CompareTo (HandlerSpan other)
  479. {
  480. int result = this.StartOffset - other.StartOffset;
  481. if (result == 0) {
  482. // Both blocks have same start. Order larger (outer) before smaller (inner).
  483. result = other.EndOffset - this.EndOffset;
  484. }
  485. return result;
  486. }
  487. public string ToString (CSComponentInspector visualizer)
  488. {
  489. switch (this.Kind) {
  490. default:
  491. return ".try";
  492. case HandlerKind.Catch:
  493. return "catch **exceptiontype**";// + visualizer.VisualizeLocalType(this.ExceptionType);
  494. case HandlerKind.Filter:
  495. return "filter";
  496. case HandlerKind.Finally:
  497. return "finally";
  498. case HandlerKind.Fault:
  499. return "fault";
  500. }
  501. }
  502. public override string ToString ()
  503. {
  504. throw new NotSupportedException ("Use ToString(CSComponentInspector)");
  505. }
  506. }
  507. private static bool StartsSpan (IReadOnlyList<HandlerSpan> spans, int spanIndex, int curIndex)
  508. {
  509. return spans != null && spanIndex < spans.Count && spans [spanIndex].StartOffset == (uint)curIndex;
  510. }
  511. private static bool EndsSpan (IReadOnlyList<HandlerSpan> spans, int spanIndex, int curIndex)
  512. {
  513. return spans != null && spanIndex >= 0 && spans [spanIndex].EndOffset == (uint)curIndex;
  514. }
  515. private static bool StartsFilterHandler (IReadOnlyList<HandlerSpan> spans, int spanIndex, int curIndex)
  516. {
  517. return spans != null &&
  518. spanIndex < spans.Count &&
  519. spans [spanIndex].Kind == HandlerKind.Filter &&
  520. spans [spanIndex].FilterHandlerStart == (uint)curIndex;
  521. }
  522. public static IReadOnlyList<HandlerSpan> GetHandlerSpans (ImmutableArray<ExceptionRegion> entries)
  523. {
  524. if (entries.Length == 0) {
  525. return new HandlerSpan[0];
  526. }
  527. var result = new List<HandlerSpan> ();
  528. foreach (ExceptionRegion entry in entries) {
  529. int tryStartOffset = entry.TryOffset;
  530. int tryEndOffset = entry.TryOffset + entry.TryLength;
  531. var span = new HandlerSpan (HandlerKind.Try, null, tryStartOffset, tryEndOffset);
  532. if (result.Count == 0 || span.CompareTo (result [result.Count - 1]) != 0) {
  533. result.Add (span);
  534. }
  535. }
  536. foreach (ExceptionRegion entry in entries) {
  537. int handlerStartOffset = entry.HandlerOffset;
  538. int handlerEndOffset = entry.HandlerOffset + entry.HandlerLength;
  539. HandlerSpan span;
  540. switch (entry.Kind) {
  541. case ExceptionRegionKind.Catch:
  542. span = new HandlerSpan (HandlerKind.Catch, MetadataTokens.GetToken (entry.CatchType), handlerStartOffset, handlerEndOffset);
  543. break;
  544. case ExceptionRegionKind.Fault:
  545. span = new HandlerSpan (HandlerKind.Fault, null, handlerStartOffset, handlerEndOffset);
  546. break;
  547. case ExceptionRegionKind.Filter:
  548. span = new HandlerSpan (HandlerKind.Filter, null, handlerStartOffset, handlerEndOffset, entry.FilterOffset);
  549. break;
  550. case ExceptionRegionKind.Finally:
  551. span = new HandlerSpan (HandlerKind.Finally, null, handlerStartOffset, handlerEndOffset);
  552. break;
  553. default:
  554. throw new InvalidOperationException ();
  555. }
  556. result.Add (span);
  557. }
  558. return result;
  559. }
  560. public void Dump ()
  561. {
  562. /*
  563. foreach (var entry in InspectorFields) {
  564. var field = entry.Value;
  565. Console.WriteLine ("Inspector Field: {0}", field.Name);
  566. Console.WriteLine (" Type Name: {0}", field.TypeName);
  567. Console.WriteLine (" Default Value: {0}", field.DefaultValue);
  568. Console.WriteLine (" Positional Custom Attr:");
  569. foreach (var p in field.CustomAttrPositionalArgs)
  570. if (p.Length != 0)
  571. Console.WriteLine (" {0}", p);
  572. Console.WriteLine (" Named Custom Attr:");
  573. foreach (var nentry in field.CustomAttrNamedArgs)
  574. Console.WriteLine (" {0}:{1}", nentry.Key, nentry.Value);
  575. }
  576. */
  577. }
  578. }
  579. internal static class TokenTypeIds
  580. {
  581. internal const uint Module = 0x00000000;
  582. internal const uint TypeRef = 0x01000000;
  583. internal const uint TypeDef = 0x02000000;
  584. internal const uint FieldDef = 0x04000000;
  585. internal const uint MethodDef = 0x06000000;
  586. internal const uint ParamDef = 0x08000000;
  587. internal const uint InterfaceImpl = 0x09000000;
  588. internal const uint MemberRef = 0x0a000000;
  589. internal const uint CustomAttribute = 0x0c000000;
  590. internal const uint Permission = 0x0e000000;
  591. internal const uint Signature = 0x11000000;
  592. internal const uint Event = 0x14000000;
  593. internal const uint Property = 0x17000000;
  594. internal const uint ModuleRef = 0x1a000000;
  595. internal const uint TypeSpec = 0x1b000000;
  596. internal const uint Assembly = 0x20000000;
  597. internal const uint AssemblyRef = 0x23000000;
  598. internal const uint File = 0x26000000;
  599. internal const uint ExportedType = 0x27000000;
  600. internal const uint ManifestResource = 0x28000000;
  601. internal const uint GenericParam = 0x2a000000;
  602. internal const uint MethodSpec = 0x2b000000;
  603. internal const uint GenericParamConstraint = 0x2c000000;
  604. internal const uint String = 0x70000000;
  605. internal const uint Name = 0x71000000;
  606. internal const uint BaseType = 0x72000000;
  607. // Leave this on the high end value. This does not correspond to metadata table???
  608. internal const uint RIDMask = 0x00FFFFFF;
  609. internal const uint TokenTypeMask = 0xFF000000;
  610. }
  611. }