ILGenerator.cs 32 KB

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