ILGenerator.cs 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. //
  2. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining
  5. // a copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to
  9. // permit persons to whom the Software is furnished to do so, subject to
  10. // the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be
  13. // included in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. //
  24. // System.Reflection.Emit/ILGenerator.cs
  25. //
  26. // Author:
  27. // Paolo Molaro ([email protected])
  28. //
  29. // (C) 2001 Ximian, Inc. http://www.ximian.com
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.Diagnostics.SymbolStore;
  34. using System.Runtime.InteropServices;
  35. namespace System.Reflection.Emit {
  36. internal struct ILExceptionBlock {
  37. public const int CATCH = 0;
  38. public const int FILTER = 1;
  39. public const int FINALLY = 2;
  40. public const int FAULT = 4;
  41. internal Type extype;
  42. internal int type;
  43. internal int start;
  44. internal int len;
  45. internal int filter_offset;
  46. internal void Debug () {
  47. #if NO
  48. System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
  49. if (extype != null)
  50. System.Console.WriteLine (" extype="+extype.ToString());
  51. else
  52. System.Console.WriteLine ("");
  53. #endif
  54. }
  55. }
  56. internal struct ILExceptionInfo {
  57. ILExceptionBlock[] handlers;
  58. internal int start;
  59. int len;
  60. internal Label end;
  61. internal int NumHandlers ()
  62. {
  63. return handlers.Length;
  64. }
  65. internal void AddCatch (Type extype, int offset)
  66. {
  67. int i;
  68. End (offset);
  69. add_block (offset);
  70. i = handlers.Length - 1;
  71. handlers [i].type = ILExceptionBlock.CATCH;
  72. handlers [i].start = offset;
  73. handlers [i].extype = extype;
  74. }
  75. internal void AddFinally (int offset)
  76. {
  77. int i;
  78. End (offset);
  79. add_block (offset);
  80. i = handlers.Length - 1;
  81. handlers [i].type = ILExceptionBlock.FINALLY;
  82. handlers [i].start = offset;
  83. handlers [i].extype = null;
  84. }
  85. internal void AddFault (int offset)
  86. {
  87. int i;
  88. End (offset);
  89. add_block (offset);
  90. i = handlers.Length - 1;
  91. handlers [i].type = ILExceptionBlock.FAULT;
  92. handlers [i].start = offset;
  93. handlers [i].extype = null;
  94. }
  95. internal void End (int offset)
  96. {
  97. if (handlers == null)
  98. return;
  99. int i = handlers.Length - 1;
  100. if (i >= 0)
  101. handlers [i].len = offset - handlers [i].start;
  102. }
  103. internal int LastClauseType ()
  104. {
  105. if (handlers != null)
  106. return handlers [handlers.Length-1].type;
  107. else
  108. return ILExceptionBlock.CATCH;
  109. }
  110. internal void Debug (int b)
  111. {
  112. #if NO
  113. System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len);
  114. for (int i = 0; i < handlers.Length; ++i)
  115. handlers [i].Debug ();
  116. #endif
  117. }
  118. void add_block (int offset)
  119. {
  120. if (handlers != null) {
  121. int i = handlers.Length;
  122. ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
  123. System.Array.Copy (handlers, new_b, i);
  124. handlers = new_b;
  125. handlers [i].len = offset - handlers [i].start;
  126. } else {
  127. handlers = new ILExceptionBlock [1];
  128. len = offset - start;
  129. }
  130. }
  131. }
  132. internal struct ILTokenInfo {
  133. public MemberInfo member;
  134. public int code_pos;
  135. }
  136. internal interface TokenGenerator {
  137. int GetToken (string str);
  138. int GetToken (MemberInfo member);
  139. int GetToken (MethodInfo method, Type[] opt_param_types);
  140. int GetToken (SignatureHelper helper);
  141. }
  142. #if NET_2_0
  143. [ComVisible (true)]
  144. [ClassInterfaceAttribute (ClassInterfaceType.None)]
  145. [ComDefaultInterfaceAttribute (typeof (_ILGenerator))]
  146. #endif
  147. public class ILGenerator: Object {
  148. private struct LabelFixup {
  149. public int offset; // The number of bytes between pos and the
  150. // offset of the jump
  151. public int pos; // Where offset of the label is placed
  152. public int label_idx; // The label to jump to
  153. };
  154. struct LabelData {
  155. public LabelData (int addr, int maxStack)
  156. {
  157. this.addr = addr;
  158. this.maxStack = maxStack;
  159. }
  160. public int addr;
  161. public int maxStack;
  162. }
  163. static readonly Type void_type = typeof (void);
  164. #region Sync with reflection.h
  165. private byte[] code;
  166. private int code_len;
  167. private int max_stack;
  168. private int cur_stack;
  169. private LocalBuilder[] locals;
  170. private ILExceptionInfo[] ex_handlers;
  171. private int num_token_fixups;
  172. private ILTokenInfo[] token_fixups;
  173. #endregion
  174. private LabelData [] labels;
  175. private int num_labels;
  176. private LabelFixup[] fixups;
  177. private int num_fixups;
  178. internal Module module;
  179. private Stack scopes;
  180. private int cur_block;
  181. private Stack open_blocks;
  182. private TokenGenerator token_gen;
  183. const int defaultFixupSize = 8;
  184. const int defaultLabelsSize = 8;
  185. ArrayList sequencePointLists;
  186. SequencePointList currentSequence;
  187. internal ILGenerator (Module m, TokenGenerator token_gen, int size)
  188. {
  189. if (size < 0)
  190. size = 128;
  191. code_len = 0;
  192. code = new byte [size];
  193. cur_stack = max_stack = 0;
  194. num_fixups = num_labels = 0;
  195. token_fixups = new ILTokenInfo [8];
  196. num_token_fixups = 0;
  197. module = m;
  198. open_blocks = new Stack ();
  199. this.token_gen = token_gen;
  200. }
  201. private void add_token_fixup (MemberInfo mi)
  202. {
  203. if (num_token_fixups == token_fixups.Length) {
  204. ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
  205. token_fixups.CopyTo (ntf, 0);
  206. token_fixups = ntf;
  207. }
  208. token_fixups [num_token_fixups].member = mi;
  209. token_fixups [num_token_fixups++].code_pos = code_len;
  210. }
  211. private void make_room (int nbytes)
  212. {
  213. if (code_len + nbytes < code.Length)
  214. return;
  215. byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
  216. System.Array.Copy (code, 0, new_code, 0, code.Length);
  217. code = new_code;
  218. }
  219. private void emit_int (int val)
  220. {
  221. code [code_len++] = (byte) (val & 0xFF);
  222. code [code_len++] = (byte) ((val >> 8) & 0xFF);
  223. code [code_len++] = (byte) ((val >> 16) & 0xFF);
  224. code [code_len++] = (byte) ((val >> 24) & 0xFF);
  225. }
  226. /* change to pass by ref to avoid copy */
  227. private void ll_emit (OpCode opcode)
  228. {
  229. /*
  230. * there is already enough room allocated in code.
  231. */
  232. // access op1 and op2 directly since the Value property is useless
  233. if (opcode.Size == 2)
  234. code [code_len++] = opcode.op1;
  235. code [code_len++] = opcode.op2;
  236. /*
  237. * We should probably keep track of stack needs here.
  238. * Or we may want to run the verifier on the code before saving it
  239. * (this may be needed anyway when the ILGenerator is not used...).
  240. */
  241. switch (opcode.StackBehaviourPush) {
  242. case StackBehaviour.Push1:
  243. case StackBehaviour.Pushi:
  244. case StackBehaviour.Pushi8:
  245. case StackBehaviour.Pushr4:
  246. case StackBehaviour.Pushr8:
  247. case StackBehaviour.Pushref:
  248. case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
  249. cur_stack ++;
  250. break;
  251. case StackBehaviour.Push1_push1:
  252. cur_stack += 2;
  253. break;
  254. }
  255. if (max_stack < cur_stack)
  256. max_stack = cur_stack;
  257. /*
  258. * Note that we adjust for the pop behaviour _after_ setting max_stack.
  259. */
  260. switch (opcode.StackBehaviourPop) {
  261. case StackBehaviour.Varpop:
  262. break; /* we are conservative and assume it doesn't decrease the stack needs */
  263. case StackBehaviour.Pop1:
  264. case StackBehaviour.Popi:
  265. case StackBehaviour.Popref:
  266. cur_stack --;
  267. break;
  268. case StackBehaviour.Pop1_pop1:
  269. case StackBehaviour.Popi_pop1:
  270. case StackBehaviour.Popi_popi:
  271. case StackBehaviour.Popi_popi8:
  272. case StackBehaviour.Popi_popr4:
  273. case StackBehaviour.Popi_popr8:
  274. case StackBehaviour.Popref_pop1:
  275. case StackBehaviour.Popref_popi:
  276. cur_stack -= 2;
  277. break;
  278. case StackBehaviour.Popi_popi_popi:
  279. case StackBehaviour.Popref_popi_popi:
  280. case StackBehaviour.Popref_popi_popi8:
  281. case StackBehaviour.Popref_popi_popr4:
  282. case StackBehaviour.Popref_popi_popr8:
  283. case StackBehaviour.Popref_popi_popref:
  284. cur_stack -= 3;
  285. break;
  286. }
  287. }
  288. private static int target_len (OpCode opcode)
  289. {
  290. if (opcode.OperandType == OperandType.InlineBrTarget)
  291. return 4;
  292. return 1;
  293. }
  294. private void InternalEndClause ()
  295. {
  296. switch (ex_handlers [cur_block].LastClauseType ()) {
  297. case ILExceptionBlock.CATCH:
  298. // how could we optimize code size here?
  299. Emit (OpCodes.Leave, ex_handlers [cur_block].end);
  300. break;
  301. case ILExceptionBlock.FAULT:
  302. case ILExceptionBlock.FINALLY:
  303. Emit (OpCodes.Endfinally);
  304. break;
  305. case ILExceptionBlock.FILTER:
  306. Emit (OpCodes.Endfilter);
  307. break;
  308. }
  309. }
  310. public virtual void BeginCatchBlock (Type exceptionType)
  311. {
  312. if (open_blocks.Count <= 0)
  313. throw new NotSupportedException ("Not in an exception block");
  314. InternalEndClause ();
  315. ex_handlers [cur_block].AddCatch (exceptionType, code_len);
  316. cur_stack = 1; // the exception object is on the stack by default
  317. if (max_stack < cur_stack)
  318. max_stack = cur_stack;
  319. //System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack);
  320. //throw new NotImplementedException ();
  321. }
  322. [MonoTODO]
  323. public virtual void BeginExceptFilterBlock ()
  324. {
  325. throw new NotImplementedException ();
  326. }
  327. public virtual Label BeginExceptionBlock ()
  328. {
  329. //System.Console.WriteLine ("Begin Block");
  330. if (ex_handlers != null) {
  331. cur_block = ex_handlers.Length;
  332. ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
  333. System.Array.Copy (ex_handlers, new_ex, cur_block);
  334. ex_handlers = new_ex;
  335. } else {
  336. ex_handlers = new ILExceptionInfo [1];
  337. cur_block = 0;
  338. }
  339. open_blocks.Push (cur_block);
  340. ex_handlers [cur_block].start = code_len;
  341. return ex_handlers [cur_block].end = DefineLabel ();
  342. }
  343. public virtual void BeginFaultBlock()
  344. {
  345. if (open_blocks.Count <= 0)
  346. throw new NotSupportedException ("Not in an exception block");
  347. //System.Console.WriteLine ("Begin fault Block");
  348. ex_handlers [cur_block].AddFault (code_len);
  349. }
  350. public virtual void BeginFinallyBlock()
  351. {
  352. if (open_blocks.Count <= 0)
  353. throw new NotSupportedException ("Not in an exception block");
  354. InternalEndClause ();
  355. //System.Console.WriteLine ("Begin finally Block");
  356. ex_handlers [cur_block].AddFinally (code_len);
  357. }
  358. public virtual void BeginScope ()
  359. { }
  360. public LocalBuilder DeclareLocal (Type localType)
  361. {
  362. return DeclareLocal (localType, false);
  363. }
  364. #if NET_2_0
  365. public
  366. #else
  367. internal
  368. #endif
  369. LocalBuilder DeclareLocal (Type localType, bool pinned)
  370. {
  371. if (localType == null)
  372. throw new ArgumentNullException ("localType");
  373. LocalBuilder res = new LocalBuilder (localType, this);
  374. res.is_pinned = pinned;
  375. if (locals != null) {
  376. LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
  377. System.Array.Copy (locals, new_l, locals.Length);
  378. new_l [locals.Length] = res;
  379. locals = new_l;
  380. } else {
  381. locals = new LocalBuilder [1];
  382. locals [0] = res;
  383. }
  384. res.position = (ushort)(locals.Length - 1);
  385. return res;
  386. }
  387. public virtual Label DefineLabel ()
  388. {
  389. if (labels == null)
  390. labels = new LabelData [defaultLabelsSize];
  391. else if (num_labels >= labels.Length) {
  392. LabelData [] t = new LabelData [labels.Length * 2];
  393. Array.Copy (labels, t, labels.Length);
  394. labels = t;
  395. }
  396. labels [num_labels] = new LabelData (-1, 0);
  397. return new Label (num_labels++);
  398. }
  399. public virtual void Emit (OpCode opcode)
  400. {
  401. make_room (2);
  402. ll_emit (opcode);
  403. }
  404. public virtual void Emit (OpCode opcode, Byte val)
  405. {
  406. make_room (3);
  407. ll_emit (opcode);
  408. code [code_len++] = val;
  409. }
  410. [ComVisible (true)]
  411. public virtual void Emit (OpCode opcode, ConstructorInfo constructor)
  412. {
  413. int token = token_gen.GetToken (constructor);
  414. make_room (6);
  415. ll_emit (opcode);
  416. if (constructor.DeclaringType.Module == module)
  417. add_token_fixup (constructor);
  418. emit_int (token);
  419. if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
  420. cur_stack -= constructor.GetParameterCount ();
  421. }
  422. public virtual void Emit (OpCode opcode, double val)
  423. {
  424. Double.AssertEndianity (out val);
  425. byte[] s = System.BitConverter.GetBytes (val);
  426. make_room (10);
  427. ll_emit (opcode);
  428. if (BitConverter.IsLittleEndian){
  429. System.Array.Copy (s, 0, code, code_len, 8);
  430. code_len += 8;
  431. } else {
  432. code [code_len++] = s [7];
  433. code [code_len++] = s [6];
  434. code [code_len++] = s [5];
  435. code [code_len++] = s [4];
  436. code [code_len++] = s [3];
  437. code [code_len++] = s [2];
  438. code [code_len++] = s [1];
  439. code [code_len++] = s [0];
  440. }
  441. }
  442. public virtual void Emit (OpCode opcode, FieldInfo field)
  443. {
  444. int token = token_gen.GetToken (field);
  445. make_room (6);
  446. ll_emit (opcode);
  447. if (field.DeclaringType.Module == module)
  448. add_token_fixup (field);
  449. emit_int (token);
  450. }
  451. public virtual void Emit (OpCode opcode, Int16 val)
  452. {
  453. make_room (4);
  454. ll_emit (opcode);
  455. code [code_len++] = (byte) (val & 0xFF);
  456. code [code_len++] = (byte) ((val >> 8) & 0xFF);
  457. }
  458. public virtual void Emit (OpCode opcode, int val)
  459. {
  460. make_room (6);
  461. ll_emit (opcode);
  462. emit_int (val);
  463. }
  464. public virtual void Emit (OpCode opcode, long val)
  465. {
  466. make_room (10);
  467. ll_emit (opcode);
  468. code [code_len++] = (byte) (val & 0xFF);
  469. code [code_len++] = (byte) ((val >> 8) & 0xFF);
  470. code [code_len++] = (byte) ((val >> 16) & 0xFF);
  471. code [code_len++] = (byte) ((val >> 24) & 0xFF);
  472. code [code_len++] = (byte) ((val >> 32) & 0xFF);
  473. code [code_len++] = (byte) ((val >> 40) & 0xFF);
  474. code [code_len++] = (byte) ((val >> 48) & 0xFF);
  475. code [code_len++] = (byte) ((val >> 56) & 0xFF);
  476. }
  477. public virtual void Emit (OpCode opcode, Label label)
  478. {
  479. int tlen = target_len (opcode);
  480. make_room (6);
  481. ll_emit (opcode);
  482. if (cur_stack > labels [label.label].maxStack)
  483. labels [label.label].maxStack = cur_stack;
  484. if (fixups == null)
  485. fixups = new LabelFixup [defaultFixupSize];
  486. else if (num_fixups >= fixups.Length) {
  487. LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
  488. System.Array.Copy (fixups, newf, fixups.Length);
  489. fixups = newf;
  490. }
  491. fixups [num_fixups].offset = tlen;
  492. fixups [num_fixups].pos = code_len;
  493. fixups [num_fixups].label_idx = label.label;
  494. num_fixups++;
  495. code_len += tlen;
  496. }
  497. public virtual void Emit (OpCode opcode, Label[] labels)
  498. {
  499. /* opcode needs to be switch. */
  500. int count = labels.Length;
  501. make_room (6 + count * 4);
  502. ll_emit (opcode);
  503. for (int i = 0; i < count; ++i)
  504. if (cur_stack > this.labels [labels [i].label].maxStack)
  505. this.labels [labels [i].label].maxStack = cur_stack;
  506. emit_int (count);
  507. if (fixups == null)
  508. fixups = new LabelFixup [defaultFixupSize + count];
  509. else if (num_fixups + count >= fixups.Length) {
  510. LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
  511. System.Array.Copy (fixups, newf, fixups.Length);
  512. fixups = newf;
  513. }
  514. // ECMA 335, Partition III, p94 (7-10)
  515. //
  516. // The switch instruction implements a jump table. The format of
  517. // the instruction is an unsigned int32 representing the number of targets N,
  518. // followed by N int32 values specifying jump targets: these targets are
  519. // represented as offsets (positive or negative) from the beginning of the
  520. // instruction following this switch instruction.
  521. //
  522. // We must make sure it gets an offset from the *end* of the last label
  523. // (eg, the beginning of the instruction following this).
  524. //
  525. // remaining is the number of bytes from the current instruction to the
  526. // instruction that will be emitted.
  527. for (int i = 0, remaining = count * 4; i < count; ++i, remaining -= 4) {
  528. fixups [num_fixups].offset = remaining;
  529. fixups [num_fixups].pos = code_len;
  530. fixups [num_fixups].label_idx = labels [i].label;
  531. num_fixups++;
  532. code_len += 4;
  533. }
  534. }
  535. public virtual void Emit (OpCode opcode, LocalBuilder lbuilder)
  536. {
  537. uint pos = lbuilder.position;
  538. bool load_addr = false;
  539. bool is_store = false;
  540. make_room (6);
  541. if (lbuilder.ilgen != this)
  542. throw new Exception ("Trying to emit a local from a different ILGenerator.");
  543. /* inline the code from ll_emit () to optimize il code size */
  544. if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
  545. cur_stack --;
  546. is_store = true;
  547. } else {
  548. cur_stack++;
  549. if (cur_stack > max_stack)
  550. max_stack = cur_stack;
  551. load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
  552. }
  553. if (load_addr) {
  554. if (pos < 256) {
  555. code [code_len++] = (byte)0x12;
  556. code [code_len++] = (byte)pos;
  557. } else {
  558. code [code_len++] = (byte)0xfe;
  559. code [code_len++] = (byte)0x0d;
  560. code [code_len++] = (byte)(pos & 0xff);
  561. code [code_len++] = (byte)((pos >> 8) & 0xff);
  562. }
  563. } else {
  564. if (is_store) {
  565. if (pos < 4) {
  566. code [code_len++] = (byte)(0x0a + pos);
  567. } else if (pos < 256) {
  568. code [code_len++] = (byte)0x13;
  569. code [code_len++] = (byte)pos;
  570. } else {
  571. code [code_len++] = (byte)0xfe;
  572. code [code_len++] = (byte)0x0e;
  573. code [code_len++] = (byte)(pos & 0xff);
  574. code [code_len++] = (byte)((pos >> 8) & 0xff);
  575. }
  576. } else {
  577. if (pos < 4) {
  578. code [code_len++] = (byte)(0x06 + pos);
  579. } else if (pos < 256) {
  580. code [code_len++] = (byte)0x11;
  581. code [code_len++] = (byte)pos;
  582. } else {
  583. code [code_len++] = (byte)0xfe;
  584. code [code_len++] = (byte)0x0c;
  585. code [code_len++] = (byte)(pos & 0xff);
  586. code [code_len++] = (byte)((pos >> 8) & 0xff);
  587. }
  588. }
  589. }
  590. }
  591. public virtual void Emit (OpCode opcode, MethodInfo method)
  592. {
  593. if (method == null)
  594. throw new ArgumentNullException ("method");
  595. int token = token_gen.GetToken (method);
  596. make_room (6);
  597. ll_emit (opcode);
  598. if (method.DeclaringType.Module == module)
  599. add_token_fixup (method);
  600. emit_int (token);
  601. if (method.ReturnType != void_type)
  602. cur_stack ++;
  603. if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
  604. cur_stack -= method.GetParameterCount ();
  605. }
  606. private void Emit (OpCode opcode, MethodInfo method, int token)
  607. {
  608. make_room (6);
  609. ll_emit (opcode);
  610. if (method.DeclaringType.Module == module)
  611. add_token_fixup (method);
  612. emit_int (token);
  613. if (method.ReturnType != void_type)
  614. cur_stack ++;
  615. if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
  616. cur_stack -= method.GetParameterCount ();
  617. }
  618. [CLSCompliant(false)]
  619. public void Emit (OpCode opcode, sbyte val)
  620. {
  621. make_room (3);
  622. ll_emit (opcode);
  623. code [code_len++] = (byte)val;
  624. }
  625. public virtual void Emit (OpCode opcode, SignatureHelper shelper)
  626. {
  627. int token = token_gen.GetToken (shelper);
  628. make_room (6);
  629. ll_emit (opcode);
  630. emit_int (token);
  631. }
  632. public virtual void Emit (OpCode opcode, float val)
  633. {
  634. byte[] s = System.BitConverter.GetBytes (val);
  635. make_room (6);
  636. ll_emit (opcode);
  637. if (BitConverter.IsLittleEndian){
  638. System.Array.Copy (s, 0, code, code_len, 4);
  639. code_len += 4;
  640. } else {
  641. code [code_len++] = s [3];
  642. code [code_len++] = s [2];
  643. code [code_len++] = s [1];
  644. code [code_len++] = s [0];
  645. }
  646. }
  647. public virtual void Emit (OpCode opcode, string val)
  648. {
  649. int token = token_gen.GetToken (val);
  650. make_room (6);
  651. ll_emit (opcode);
  652. emit_int (token);
  653. }
  654. public virtual void Emit (OpCode opcode, Type type)
  655. {
  656. make_room (6);
  657. ll_emit (opcode);
  658. emit_int (token_gen.GetToken (type));
  659. }
  660. [MonoTODO ("Do something about varargs method")]
  661. public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes)
  662. {
  663. if (methodinfo == null)
  664. throw new ArgumentNullException ("methodinfo can not be null");
  665. short value = opcode.Value;
  666. if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value))
  667. throw new NotSupportedException ("Only Call and CallVirt are allowed");
  668. if (optionalParamTypes != null){
  669. if ((methodinfo.CallingConvention & CallingConventions.VarArgs) == 0){
  670. throw new InvalidOperationException ("Method is not VarArgs method and optional types were passed");
  671. }
  672. int token = token_gen.GetToken (methodinfo, optionalParamTypes);
  673. Emit (opcode, methodinfo, token);
  674. return;
  675. }
  676. Emit (opcode, methodinfo);
  677. }
  678. public void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] paramTypes)
  679. {
  680. SignatureHelper helper
  681. = SignatureHelper.GetMethodSigHelper (module, 0, unmanagedCallConv, returnType, paramTypes);
  682. Emit (opcode, helper);
  683. }
  684. public void EmitCalli (OpCode opcode, CallingConventions callConv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes)
  685. {
  686. if (optionalParamTypes != null)
  687. throw new NotImplementedException ();
  688. SignatureHelper helper
  689. = SignatureHelper.GetMethodSigHelper (module, callConv, 0, returnType, paramTypes);
  690. Emit (opcode, helper);
  691. }
  692. public virtual void EmitWriteLine (FieldInfo field)
  693. {
  694. if (field == null)
  695. throw new ArgumentNullException ("field");
  696. // The MS implementation does not check for valuetypes here but it
  697. // should. Also, it should check that if the field is not static,
  698. // then it is a member of this type.
  699. if (field.IsStatic)
  700. Emit (OpCodes.Ldsfld, field);
  701. else {
  702. Emit (OpCodes.Ldarg_0);
  703. Emit (OpCodes.Ldfld, field);
  704. }
  705. Emit (OpCodes.Call,
  706. typeof (Console).GetMethod ("WriteLine",
  707. new Type[1] { field.FieldType }));
  708. }
  709. public virtual void EmitWriteLine (LocalBuilder lbuilder)
  710. {
  711. if (lbuilder == null)
  712. throw new ArgumentNullException ("lbuilder");
  713. if (lbuilder.LocalType is TypeBuilder)
  714. throw new ArgumentException ("Output streams do not support TypeBuilders.");
  715. // The MS implementation does not check for valuetypes here but it
  716. // should.
  717. Emit (OpCodes.Ldloc, lbuilder);
  718. Emit (OpCodes.Call,
  719. typeof (Console).GetMethod ("WriteLine",
  720. new Type[1] { lbuilder.LocalType }));
  721. }
  722. public virtual void EmitWriteLine (string val)
  723. {
  724. Emit (OpCodes.Ldstr, val);
  725. Emit (OpCodes.Call,
  726. typeof (Console).GetMethod ("WriteLine",
  727. new Type[1] { typeof(string)}));
  728. }
  729. public virtual void EndExceptionBlock ()
  730. {
  731. if (open_blocks.Count <= 0)
  732. throw new NotSupportedException ("Not in an exception block");
  733. InternalEndClause ();
  734. MarkLabel (ex_handlers [cur_block].end);
  735. ex_handlers [cur_block].End (code_len);
  736. ex_handlers [cur_block].Debug (cur_block);
  737. //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
  738. open_blocks.Pop ();
  739. if (open_blocks.Count > 0)
  740. cur_block = (int)open_blocks.Peek ();
  741. //Console.WriteLine ("curblock restored to {0}", cur_block);
  742. //throw new NotImplementedException ();
  743. }
  744. public virtual void EndScope ()
  745. { }
  746. public virtual void MarkLabel (Label loc)
  747. {
  748. if (loc.label < 0 || loc.label >= num_labels)
  749. throw new System.ArgumentException ("The label is not valid");
  750. if (labels [loc.label].addr >= 0)
  751. throw new System.ArgumentException ("The label was already defined");
  752. labels [loc.label].addr = code_len;
  753. if (labels [loc.label].maxStack > cur_stack)
  754. cur_stack = labels [loc.label].maxStack;
  755. }
  756. public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
  757. int startColumn, int endLine, int endColumn)
  758. {
  759. if (currentSequence == null || currentSequence.Document != document) {
  760. if (sequencePointLists == null)
  761. sequencePointLists = new ArrayList ();
  762. currentSequence = new SequencePointList (document);
  763. sequencePointLists.Add (currentSequence);
  764. }
  765. currentSequence.AddSequencePoint (code_len, startLine, startColumn, endLine, endColumn);
  766. }
  767. internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
  768. {
  769. if (sequencePointLists != null) {
  770. SequencePointList first = (SequencePointList) sequencePointLists [0];
  771. SequencePointList last = (SequencePointList) sequencePointLists [sequencePointLists.Count - 1];
  772. symbolWriter.SetMethodSourceRange (first.Document, first.StartLine, first.StartColumn, last.Document, last.EndLine, last.EndColumn);
  773. foreach (SequencePointList list in sequencePointLists)
  774. symbolWriter.DefineSequencePoints (list.Document, list.GetOffsets(), list.GetLines(), list.GetColumns(), list.GetEndLines(), list.GetEndColumns());
  775. if (locals != null) {
  776. foreach (LocalBuilder local in locals) {
  777. if (local.Name != null && local.Name.Length > 0) {
  778. SignatureHelper sighelper = SignatureHelper.GetLocalVarSigHelper (module);
  779. sighelper.AddArgument (local.LocalType);
  780. byte[] signature = sighelper.GetSignature ();
  781. symbolWriter.DefineLocalVariable (local.Name, FieldAttributes.Public, signature, SymAddressKind.ILOffset, local.position, 0, 0, local.StartOffset, local.EndOffset);
  782. }
  783. }
  784. }
  785. sequencePointLists = null;
  786. }
  787. }
  788. internal bool HasDebugInfo
  789. {
  790. get { return sequencePointLists != null; }
  791. }
  792. public virtual void ThrowException (Type exceptionType)
  793. {
  794. if (exceptionType == null)
  795. throw new ArgumentNullException ("exceptionType");
  796. if (! ((exceptionType == typeof (Exception)) ||
  797. exceptionType.IsSubclassOf (typeof (Exception))))
  798. throw new ArgumentException ("Type should be an exception type", "exceptionType");
  799. ConstructorInfo ctor = exceptionType.GetConstructor (new Type[0]);
  800. if (ctor == null)
  801. throw new ArgumentException ("Type should have a default constructor", "exceptionType");
  802. Emit (OpCodes.Newobj, ctor);
  803. Emit (OpCodes.Throw);
  804. }
  805. [MonoTODO]
  806. public void UsingNamespace (String usingNamespace)
  807. {
  808. throw new NotImplementedException ();
  809. }
  810. internal void label_fixup ()
  811. {
  812. for (int i = 0; i < num_fixups; ++i) {
  813. // Diff is the offset from the end of the jump instruction to the address of the label
  814. int diff = labels [fixups [i].label_idx].addr - (fixups [i].pos + fixups [i].offset);
  815. if (fixups [i].offset == 1) {
  816. code [fixups [i].pos] = (byte)((sbyte) diff);
  817. } else {
  818. int old_cl = code_len;
  819. code_len = fixups [i].pos;
  820. emit_int (diff);
  821. code_len = old_cl;
  822. }
  823. }
  824. }
  825. internal static int Mono_GetCurrentOffset (ILGenerator ig)
  826. {
  827. return ig.code_len;
  828. }
  829. }
  830. internal class SequencePointList
  831. {
  832. ISymbolDocumentWriter doc;
  833. SequencePoint[] points;
  834. int count;
  835. const int arrayGrow = 10;
  836. public SequencePointList (ISymbolDocumentWriter doc)
  837. {
  838. this.doc = doc;
  839. }
  840. public ISymbolDocumentWriter Document {
  841. get { return doc; }
  842. }
  843. public int[] GetOffsets()
  844. {
  845. int[] data = new int [count];
  846. for (int n=0; n<count; n++) data [n] = points[n].Offset;
  847. return data;
  848. }
  849. public int[] GetLines()
  850. {
  851. int[] data = new int [count];
  852. for (int n=0; n<count; n++) data [n] = points[n].Line;
  853. return data;
  854. }
  855. public int[] GetColumns()
  856. {
  857. int[] data = new int [count];
  858. for (int n=0; n<count; n++) data [n] = points[n].Col;
  859. return data;
  860. }
  861. public int[] GetEndLines()
  862. {
  863. int[] data = new int [count];
  864. for (int n=0; n<count; n++) data [n] = points[n].EndLine;
  865. return data;
  866. }
  867. public int[] GetEndColumns()
  868. {
  869. int[] data = new int [count];
  870. for (int n=0; n<count; n++) data [n] = points[n].EndCol;
  871. return data;
  872. }
  873. public int StartLine {
  874. get { return points[0].Line; }
  875. }
  876. public int EndLine {
  877. get { return points[count - 1].Line; }
  878. }
  879. public int StartColumn {
  880. get { return points[0].Col; }
  881. }
  882. public int EndColumn {
  883. get { return points[count - 1].Col; }
  884. }
  885. public void AddSequencePoint (int offset, int line, int col, int endLine, int endCol)
  886. {
  887. SequencePoint s = new SequencePoint ();
  888. s.Offset = offset;
  889. s.Line = line;
  890. s.Col = col;
  891. s.EndLine = endLine;
  892. s.EndCol = endCol;
  893. if (points == null) {
  894. points = new SequencePoint [arrayGrow];
  895. } else if (count >= points.Length) {
  896. SequencePoint[] temp = new SequencePoint [count + arrayGrow];
  897. Array.Copy (points, temp, points.Length);
  898. points = temp;
  899. }
  900. points [count] = s;
  901. count++;
  902. }
  903. }
  904. struct SequencePoint {
  905. public int Offset;
  906. public int Line;
  907. public int Col;
  908. public int EndLine;
  909. public int EndCol;
  910. }
  911. }