CodeWriter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. //
  2. // Author:
  3. // Jb Evain (jbevain@gmail.com)
  4. //
  5. // Copyright (c) 2008 - 2015 Jb Evain
  6. // Copyright (c) 2008 - 2011 Novell, Inc.
  7. //
  8. // Licensed under the MIT/X11 license.
  9. //
  10. using System;
  11. using System.Collections.Generic;
  12. using ILRuntime.Mono.Collections.Generic;
  13. using ILRuntime.Mono.Cecil.Metadata;
  14. using ILRuntime.Mono.Cecil.PE;
  15. using RVA = System.UInt32;
  16. namespace ILRuntime.Mono.Cecil.Cil {
  17. sealed class CodeWriter : ByteBuffer {
  18. readonly RVA code_base;
  19. internal readonly MetadataBuilder metadata;
  20. readonly Dictionary<uint, MetadataToken> standalone_signatures;
  21. readonly Dictionary<ByteBuffer, RVA> tiny_method_bodies;
  22. MethodBody body;
  23. public CodeWriter (MetadataBuilder metadata)
  24. : base (0)
  25. {
  26. this.code_base = metadata.text_map.GetNextRVA (TextSegment.CLIHeader);
  27. this.metadata = metadata;
  28. this.standalone_signatures = new Dictionary<uint, MetadataToken> ();
  29. this.tiny_method_bodies = new Dictionary<ByteBuffer, RVA> (new ByteBufferEqualityComparer ());
  30. }
  31. public RVA WriteMethodBody (MethodDefinition method)
  32. {
  33. RVA rva;
  34. if (IsUnresolved (method)) {
  35. if (method.rva == 0)
  36. return 0;
  37. rva = WriteUnresolvedMethodBody (method);
  38. } else {
  39. if (IsEmptyMethodBody (method.Body))
  40. return 0;
  41. rva = WriteResolvedMethodBody (method);
  42. }
  43. return rva;
  44. }
  45. static bool IsEmptyMethodBody (MethodBody body)
  46. {
  47. return body.instructions.IsNullOrEmpty ()
  48. && body.variables.IsNullOrEmpty ();
  49. }
  50. static bool IsUnresolved (MethodDefinition method)
  51. {
  52. return method.HasBody && method.HasImage && method.body == null;
  53. }
  54. RVA WriteUnresolvedMethodBody (MethodDefinition method)
  55. {
  56. var code_reader = metadata.module.reader.code;
  57. int code_size;
  58. MetadataToken local_var_token;
  59. var raw_body = code_reader.PatchRawMethodBody (method, this, out code_size, out local_var_token);
  60. var fat_header = (raw_body.buffer [0] & 0x3) == 0x3;
  61. if (fat_header)
  62. Align (4);
  63. var rva = BeginMethod ();
  64. if (fat_header || !GetOrMapTinyMethodBody (raw_body, ref rva)) {
  65. WriteBytes (raw_body);
  66. }
  67. if (method.debug_info == null)
  68. return rva;
  69. var symbol_writer = metadata.symbol_writer;
  70. if (symbol_writer != null) {
  71. method.debug_info.code_size = code_size;
  72. method.debug_info.local_var_token = local_var_token;
  73. symbol_writer.Write (method.debug_info);
  74. }
  75. return rva;
  76. }
  77. RVA WriteResolvedMethodBody(MethodDefinition method)
  78. {
  79. RVA rva;
  80. body = method.Body;
  81. ComputeHeader ();
  82. if (RequiresFatHeader ()) {
  83. Align (4);
  84. rva = BeginMethod ();
  85. WriteFatHeader ();
  86. WriteInstructions ();
  87. if (body.HasExceptionHandlers)
  88. WriteExceptionHandlers ();
  89. } else {
  90. rva = BeginMethod ();
  91. WriteByte ((byte) (0x2 | (body.CodeSize << 2))); // tiny
  92. WriteInstructions ();
  93. var start_position = (int) (rva - code_base);
  94. var body_size = position - start_position;
  95. var body_bytes = new byte [body_size];
  96. Array.Copy (buffer, start_position, body_bytes, 0, body_size);
  97. if (GetOrMapTinyMethodBody (new ByteBuffer (body_bytes), ref rva))
  98. position = start_position;
  99. }
  100. var symbol_writer = metadata.symbol_writer;
  101. if (symbol_writer != null && method.debug_info != null) {
  102. method.debug_info.code_size = body.CodeSize;
  103. method.debug_info.local_var_token = body.local_var_token;
  104. symbol_writer.Write (method.debug_info);
  105. }
  106. return rva;
  107. }
  108. bool GetOrMapTinyMethodBody (ByteBuffer body, ref RVA rva)
  109. {
  110. RVA existing_rva;
  111. if (tiny_method_bodies.TryGetValue (body, out existing_rva)) {
  112. rva = existing_rva;
  113. return true;
  114. }
  115. tiny_method_bodies.Add (body, rva);
  116. return false;
  117. }
  118. void WriteFatHeader ()
  119. {
  120. var body = this.body;
  121. byte flags = 0x3; // fat
  122. if (body.InitLocals)
  123. flags |= 0x10; // init locals
  124. if (body.HasExceptionHandlers)
  125. flags |= 0x8; // more sections
  126. WriteByte (flags);
  127. WriteByte (0x30);
  128. WriteInt16 ((short) body.max_stack_size);
  129. WriteInt32 (body.code_size);
  130. body.local_var_token = body.HasVariables
  131. ? GetStandAloneSignature (body.Variables)
  132. : MetadataToken.Zero;
  133. WriteMetadataToken (body.local_var_token);
  134. }
  135. void WriteInstructions ()
  136. {
  137. var instructions = body.Instructions;
  138. var items = instructions.items;
  139. var size = instructions.size;
  140. for (int i = 0; i < size; i++) {
  141. var instruction = items [i];
  142. WriteOpCode (instruction.opcode);
  143. WriteOperand (instruction);
  144. }
  145. }
  146. void WriteOpCode (OpCode opcode)
  147. {
  148. if (opcode.Size == 1) {
  149. WriteByte (opcode.Op2);
  150. } else {
  151. WriteByte (opcode.Op1);
  152. WriteByte (opcode.Op2);
  153. }
  154. }
  155. void WriteOperand (Instruction instruction)
  156. {
  157. var opcode = instruction.opcode;
  158. var operand_type = opcode.OperandType;
  159. if (operand_type == OperandType.InlineNone)
  160. return;
  161. var operand = instruction.operand;
  162. if (operand == null && !(operand_type == OperandType.InlineBrTarget || operand_type == OperandType.ShortInlineBrTarget)) {
  163. throw new ArgumentException ();
  164. }
  165. switch (operand_type) {
  166. case OperandType.InlineSwitch: {
  167. var targets = (Instruction []) operand;
  168. WriteInt32 (targets.Length);
  169. var diff = instruction.Offset + opcode.Size + (4 * (targets.Length + 1));
  170. for (int i = 0; i < targets.Length; i++)
  171. WriteInt32 (GetTargetOffset (targets [i]) - diff);
  172. break;
  173. }
  174. case OperandType.ShortInlineBrTarget: {
  175. var target = (Instruction) operand;
  176. var offset = target != null ? GetTargetOffset (target) : body.code_size;
  177. WriteSByte ((sbyte) (offset - (instruction.Offset + opcode.Size + 1)));
  178. break;
  179. }
  180. case OperandType.InlineBrTarget: {
  181. var target = (Instruction) operand;
  182. var offset = target != null ? GetTargetOffset (target) : body.code_size;
  183. WriteInt32 (offset - (instruction.Offset + opcode.Size + 4));
  184. break;
  185. }
  186. case OperandType.ShortInlineVar:
  187. WriteByte ((byte) GetVariableIndex ((VariableDefinition) operand));
  188. break;
  189. case OperandType.ShortInlineArg:
  190. WriteByte ((byte) GetParameterIndex ((ParameterDefinition) operand));
  191. break;
  192. case OperandType.InlineVar:
  193. WriteInt16 ((short) GetVariableIndex ((VariableDefinition) operand));
  194. break;
  195. case OperandType.InlineArg:
  196. WriteInt16 ((short) GetParameterIndex ((ParameterDefinition) operand));
  197. break;
  198. case OperandType.InlineSig:
  199. WriteMetadataToken (GetStandAloneSignature ((CallSite) operand));
  200. break;
  201. case OperandType.ShortInlineI:
  202. if (opcode == OpCodes.Ldc_I4_S)
  203. WriteSByte ((sbyte) operand);
  204. else
  205. WriteByte ((byte) operand);
  206. break;
  207. case OperandType.InlineI:
  208. WriteInt32 ((int) operand);
  209. break;
  210. case OperandType.InlineI8:
  211. WriteInt64 ((long) operand);
  212. break;
  213. case OperandType.ShortInlineR:
  214. WriteSingle ((float) operand);
  215. break;
  216. case OperandType.InlineR:
  217. WriteDouble ((double) operand);
  218. break;
  219. case OperandType.InlineString:
  220. WriteMetadataToken (
  221. new MetadataToken (
  222. TokenType.String,
  223. GetUserStringIndex ((string) operand)));
  224. break;
  225. case OperandType.InlineType:
  226. case OperandType.InlineField:
  227. case OperandType.InlineMethod:
  228. case OperandType.InlineTok:
  229. WriteMetadataToken (metadata.LookupToken ((IMetadataTokenProvider) operand));
  230. break;
  231. default:
  232. throw new ArgumentException ();
  233. }
  234. }
  235. int GetTargetOffset (Instruction instruction)
  236. {
  237. if (instruction == null) {
  238. var last = body.instructions [body.instructions.size - 1];
  239. return last.offset + last.GetSize ();
  240. }
  241. return instruction.offset;
  242. }
  243. uint GetUserStringIndex (string @string)
  244. {
  245. if (@string == null)
  246. return 0;
  247. return metadata.user_string_heap.GetStringIndex (@string);
  248. }
  249. static int GetVariableIndex (VariableDefinition variable)
  250. {
  251. return variable.Index;
  252. }
  253. int GetParameterIndex (ParameterDefinition parameter)
  254. {
  255. if (body.method.HasThis) {
  256. if (parameter == body.this_parameter)
  257. return 0;
  258. return parameter.Index + 1;
  259. }
  260. return parameter.Index;
  261. }
  262. bool RequiresFatHeader ()
  263. {
  264. var body = this.body;
  265. return body.CodeSize >= 64
  266. || body.InitLocals
  267. || body.HasVariables
  268. || body.HasExceptionHandlers
  269. || body.MaxStackSize > 8;
  270. }
  271. void ComputeHeader ()
  272. {
  273. int offset = 0;
  274. var instructions = body.instructions;
  275. var items = instructions.items;
  276. var count = instructions.size;
  277. var stack_size = 0;
  278. var max_stack = 0;
  279. Dictionary<Instruction, int> stack_sizes = null;
  280. if (body.HasExceptionHandlers)
  281. ComputeExceptionHandlerStackSize (ref stack_sizes);
  282. for (int i = 0; i < count; i++) {
  283. var instruction = items [i];
  284. instruction.offset = offset;
  285. offset += instruction.GetSize ();
  286. ComputeStackSize (instruction, ref stack_sizes, ref stack_size, ref max_stack);
  287. }
  288. body.code_size = offset;
  289. body.max_stack_size = max_stack;
  290. }
  291. void ComputeExceptionHandlerStackSize (ref Dictionary<Instruction, int> stack_sizes)
  292. {
  293. var exception_handlers = body.ExceptionHandlers;
  294. for (int i = 0; i < exception_handlers.Count; i++) {
  295. var exception_handler = exception_handlers [i];
  296. switch (exception_handler.HandlerType) {
  297. case ExceptionHandlerType.Catch:
  298. AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
  299. break;
  300. case ExceptionHandlerType.Filter:
  301. AddExceptionStackSize (exception_handler.FilterStart, ref stack_sizes);
  302. AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
  303. break;
  304. }
  305. }
  306. }
  307. static void AddExceptionStackSize (Instruction handler_start, ref Dictionary<Instruction, int> stack_sizes)
  308. {
  309. if (handler_start == null)
  310. return;
  311. if (stack_sizes == null)
  312. stack_sizes = new Dictionary<Instruction, int> ();
  313. stack_sizes [handler_start] = 1;
  314. }
  315. static void ComputeStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, ref int stack_size, ref int max_stack)
  316. {
  317. int computed_size;
  318. if (stack_sizes != null && stack_sizes.TryGetValue (instruction, out computed_size))
  319. stack_size = computed_size;
  320. max_stack = System.Math.Max (max_stack, stack_size);
  321. ComputeStackDelta (instruction, ref stack_size);
  322. max_stack = System.Math.Max (max_stack, stack_size);
  323. CopyBranchStackSize (instruction, ref stack_sizes, stack_size);
  324. ComputeStackSize (instruction, ref stack_size);
  325. }
  326. static void CopyBranchStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, int stack_size)
  327. {
  328. if (stack_size == 0)
  329. return;
  330. switch (instruction.opcode.OperandType) {
  331. case OperandType.ShortInlineBrTarget:
  332. case OperandType.InlineBrTarget:
  333. CopyBranchStackSize (ref stack_sizes, (Instruction) instruction.operand, stack_size);
  334. break;
  335. case OperandType.InlineSwitch:
  336. var targets = (Instruction []) instruction.operand;
  337. for (int i = 0; i < targets.Length; i++)
  338. CopyBranchStackSize (ref stack_sizes, targets [i], stack_size);
  339. break;
  340. }
  341. }
  342. static void CopyBranchStackSize (ref Dictionary<Instruction, int> stack_sizes, Instruction target, int stack_size)
  343. {
  344. if (stack_sizes == null)
  345. stack_sizes = new Dictionary<Instruction, int> ();
  346. int branch_stack_size = stack_size;
  347. int computed_size;
  348. if (stack_sizes.TryGetValue (target, out computed_size))
  349. branch_stack_size = System.Math.Max (branch_stack_size, computed_size);
  350. stack_sizes [target] = branch_stack_size;
  351. }
  352. static void ComputeStackSize (Instruction instruction, ref int stack_size)
  353. {
  354. switch (instruction.opcode.FlowControl) {
  355. case FlowControl.Branch:
  356. case FlowControl.Break:
  357. case FlowControl.Throw:
  358. case FlowControl.Return:
  359. stack_size = 0;
  360. break;
  361. }
  362. }
  363. static void ComputeStackDelta (Instruction instruction, ref int stack_size)
  364. {
  365. switch (instruction.opcode.FlowControl) {
  366. case FlowControl.Call: {
  367. var method = (IMethodSignature) instruction.operand;
  368. // pop 'this' argument
  369. if (method.HasImplicitThis() && instruction.opcode.Code != Code.Newobj)
  370. stack_size--;
  371. // pop normal arguments
  372. if (method.HasParameters)
  373. stack_size -= method.Parameters.Count;
  374. // pop function pointer
  375. if (instruction.opcode.Code == Code.Calli)
  376. stack_size--;
  377. // push return value
  378. if (method.ReturnType.etype != ElementType.Void || instruction.opcode.Code == Code.Newobj)
  379. stack_size++;
  380. break;
  381. }
  382. default:
  383. ComputePopDelta (instruction.opcode.StackBehaviourPop, ref stack_size);
  384. ComputePushDelta (instruction.opcode.StackBehaviourPush, ref stack_size);
  385. break;
  386. }
  387. }
  388. static void ComputePopDelta (StackBehaviour pop_behavior, ref int stack_size)
  389. {
  390. switch (pop_behavior) {
  391. case StackBehaviour.Popi:
  392. case StackBehaviour.Popref:
  393. case StackBehaviour.Pop1:
  394. stack_size--;
  395. break;
  396. case StackBehaviour.Pop1_pop1:
  397. case StackBehaviour.Popi_pop1:
  398. case StackBehaviour.Popi_popi:
  399. case StackBehaviour.Popi_popi8:
  400. case StackBehaviour.Popi_popr4:
  401. case StackBehaviour.Popi_popr8:
  402. case StackBehaviour.Popref_pop1:
  403. case StackBehaviour.Popref_popi:
  404. stack_size -= 2;
  405. break;
  406. case StackBehaviour.Popi_popi_popi:
  407. case StackBehaviour.Popref_popi_popi:
  408. case StackBehaviour.Popref_popi_popi8:
  409. case StackBehaviour.Popref_popi_popr4:
  410. case StackBehaviour.Popref_popi_popr8:
  411. case StackBehaviour.Popref_popi_popref:
  412. stack_size -= 3;
  413. break;
  414. case StackBehaviour.PopAll:
  415. stack_size = 0;
  416. break;
  417. }
  418. }
  419. static void ComputePushDelta (StackBehaviour push_behaviour, ref int stack_size)
  420. {
  421. switch (push_behaviour) {
  422. case StackBehaviour.Push1:
  423. case StackBehaviour.Pushi:
  424. case StackBehaviour.Pushi8:
  425. case StackBehaviour.Pushr4:
  426. case StackBehaviour.Pushr8:
  427. case StackBehaviour.Pushref:
  428. stack_size++;
  429. break;
  430. case StackBehaviour.Push1_push1:
  431. stack_size += 2;
  432. break;
  433. }
  434. }
  435. void WriteExceptionHandlers ()
  436. {
  437. Align (4);
  438. var handlers = body.ExceptionHandlers;
  439. if (handlers.Count < 0x15 && !RequiresFatSection (handlers))
  440. WriteSmallSection (handlers);
  441. else
  442. WriteFatSection (handlers);
  443. }
  444. static bool RequiresFatSection (Collection<ExceptionHandler> handlers)
  445. {
  446. for (int i = 0; i < handlers.Count; i++) {
  447. var handler = handlers [i];
  448. if (IsFatRange (handler.TryStart, handler.TryEnd))
  449. return true;
  450. if (IsFatRange (handler.HandlerStart, handler.HandlerEnd))
  451. return true;
  452. if (handler.HandlerType == ExceptionHandlerType.Filter
  453. && IsFatRange (handler.FilterStart, handler.HandlerStart))
  454. return true;
  455. }
  456. return false;
  457. }
  458. static bool IsFatRange (Instruction start, Instruction end)
  459. {
  460. if (start == null)
  461. throw new ArgumentException ();
  462. if (end == null)
  463. return true;
  464. return end.Offset - start.Offset > 255 || start.Offset > 65535;
  465. }
  466. void WriteSmallSection (Collection<ExceptionHandler> handlers)
  467. {
  468. const byte eh_table = 0x1;
  469. WriteByte (eh_table);
  470. WriteByte ((byte) (handlers.Count * 12 + 4));
  471. WriteBytes (2);
  472. WriteExceptionHandlers (
  473. handlers,
  474. i => WriteUInt16 ((ushort) i),
  475. i => WriteByte ((byte) i));
  476. }
  477. void WriteFatSection (Collection<ExceptionHandler> handlers)
  478. {
  479. const byte eh_table = 0x1;
  480. const byte fat_format = 0x40;
  481. WriteByte (eh_table | fat_format);
  482. int size = handlers.Count * 24 + 4;
  483. WriteByte ((byte) (size & 0xff));
  484. WriteByte ((byte) ((size >> 8) & 0xff));
  485. WriteByte ((byte) ((size >> 16) & 0xff));
  486. WriteExceptionHandlers (handlers, WriteInt32, WriteInt32);
  487. }
  488. void WriteExceptionHandlers (Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
  489. {
  490. for (int i = 0; i < handlers.Count; i++) {
  491. var handler = handlers [i];
  492. write_entry ((int) handler.HandlerType);
  493. write_entry (handler.TryStart.Offset);
  494. write_length (GetTargetOffset (handler.TryEnd) - handler.TryStart.Offset);
  495. write_entry (handler.HandlerStart.Offset);
  496. write_length (GetTargetOffset (handler.HandlerEnd) - handler.HandlerStart.Offset);
  497. WriteExceptionHandlerSpecific (handler);
  498. }
  499. }
  500. void WriteExceptionHandlerSpecific (ExceptionHandler handler)
  501. {
  502. switch (handler.HandlerType) {
  503. case ExceptionHandlerType.Catch:
  504. WriteMetadataToken (metadata.LookupToken (handler.CatchType));
  505. break;
  506. case ExceptionHandlerType.Filter:
  507. WriteInt32 (handler.FilterStart.Offset);
  508. break;
  509. default:
  510. WriteInt32 (0);
  511. break;
  512. }
  513. }
  514. public MetadataToken GetStandAloneSignature (Collection<VariableDefinition> variables)
  515. {
  516. var signature = metadata.GetLocalVariableBlobIndex (variables);
  517. return GetStandAloneSignatureToken (signature);
  518. }
  519. public MetadataToken GetStandAloneSignature (CallSite call_site)
  520. {
  521. var signature = metadata.GetCallSiteBlobIndex (call_site);
  522. var token = GetStandAloneSignatureToken (signature);
  523. call_site.MetadataToken = token;
  524. return token;
  525. }
  526. MetadataToken GetStandAloneSignatureToken (uint signature)
  527. {
  528. MetadataToken token;
  529. if (standalone_signatures.TryGetValue (signature, out token))
  530. return token;
  531. token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature));
  532. standalone_signatures.Add (signature, token);
  533. return token;
  534. }
  535. RVA BeginMethod ()
  536. {
  537. return (RVA)(code_base + position);
  538. }
  539. void WriteMetadataToken (MetadataToken token)
  540. {
  541. WriteUInt32 (token.ToUInt32 ());
  542. }
  543. void Align (int align)
  544. {
  545. align--;
  546. WriteBytes (((position + align) & ~align) - position);
  547. }
  548. }
  549. }