ILGenerator.cs 32 KB

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