ILGenerator.cs 30 KB

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