CSComponentInspector.cs 32 KB

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