CodeWriter.cs 17 KB

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