CSComponentInspector.cs 23 KB

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