ILGenerator.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  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. if (method.DeclaringType.Module == module)
  627. add_token_fixup (method);
  628. emit_int (token);
  629. if (method.ReturnType != void_type)
  630. cur_stack ++;
  631. if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
  632. cur_stack -= method.GetParameterCount ();
  633. }
  634. private void Emit (OpCode opcode, MethodInfo method, int token)
  635. {
  636. make_room (6);
  637. ll_emit (opcode);
  638. if (method.DeclaringType.Module == module)
  639. add_token_fixup (method);
  640. emit_int (token);
  641. if (method.ReturnType != void_type)
  642. cur_stack ++;
  643. if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
  644. cur_stack -= method.GetParameterCount ();
  645. }
  646. [CLSCompliant(false)]
  647. public void Emit (OpCode opcode, sbyte val)
  648. {
  649. make_room (3);
  650. ll_emit (opcode);
  651. code [code_len++] = (byte)val;
  652. }
  653. public virtual void Emit (OpCode opcode, SignatureHelper shelper)
  654. {
  655. int token = token_gen.GetToken (shelper);
  656. make_room (6);
  657. ll_emit (opcode);
  658. emit_int (token);
  659. }
  660. public virtual void Emit (OpCode opcode, float val)
  661. {
  662. byte[] s = System.BitConverter.GetBytes (val);
  663. make_room (6);
  664. ll_emit (opcode);
  665. if (BitConverter.IsLittleEndian){
  666. System.Array.Copy (s, 0, code, code_len, 4);
  667. code_len += 4;
  668. } else {
  669. code [code_len++] = s [3];
  670. code [code_len++] = s [2];
  671. code [code_len++] = s [1];
  672. code [code_len++] = s [0];
  673. }
  674. }
  675. public virtual void Emit (OpCode opcode, string val)
  676. {
  677. int token = token_gen.GetToken (val);
  678. make_room (6);
  679. ll_emit (opcode);
  680. emit_int (token);
  681. }
  682. public virtual void Emit (OpCode opcode, Type type)
  683. {
  684. make_room (6);
  685. ll_emit (opcode);
  686. emit_int (token_gen.GetToken (type));
  687. }
  688. [MonoTODO ("Do something about varargs method")]
  689. public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes)
  690. {
  691. if (methodinfo == null)
  692. throw new ArgumentNullException ("methodinfo can not be null");
  693. short value = opcode.Value;
  694. if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value))
  695. throw new NotSupportedException ("Only Call and CallVirt are allowed");
  696. if (optionalParamTypes != null){
  697. if ((methodinfo.CallingConvention & CallingConventions.VarArgs) == 0){
  698. throw new InvalidOperationException ("Method is not VarArgs method and optional types were passed");
  699. }
  700. int token = token_gen.GetToken (methodinfo, optionalParamTypes);
  701. Emit (opcode, methodinfo, token);
  702. return;
  703. }
  704. Emit (opcode, methodinfo);
  705. }
  706. public void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] paramTypes)
  707. {
  708. SignatureHelper helper
  709. = SignatureHelper.GetMethodSigHelper (module, 0, unmanagedCallConv, returnType, paramTypes);
  710. Emit (opcode, helper);
  711. }
  712. public void EmitCalli (OpCode opcode, CallingConventions callConv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes)
  713. {
  714. if (optionalParamTypes != null)
  715. throw new NotImplementedException ();
  716. SignatureHelper helper
  717. = SignatureHelper.GetMethodSigHelper (module, callConv, 0, returnType, paramTypes);
  718. Emit (opcode, helper);
  719. }
  720. public virtual void EmitWriteLine (FieldInfo field)
  721. {
  722. if (field == null)
  723. throw new ArgumentNullException ("field");
  724. // The MS implementation does not check for valuetypes here but it
  725. // should. Also, it should check that if the field is not static,
  726. // then it is a member of this type.
  727. if (field.IsStatic)
  728. Emit (OpCodes.Ldsfld, field);
  729. else {
  730. Emit (OpCodes.Ldarg_0);
  731. Emit (OpCodes.Ldfld, field);
  732. }
  733. Emit (OpCodes.Call,
  734. typeof (Console).GetMethod ("WriteLine",
  735. new Type[1] { field.FieldType }));
  736. }
  737. public virtual void EmitWriteLine (LocalBuilder lbuilder)
  738. {
  739. if (lbuilder == null)
  740. throw new ArgumentNullException ("lbuilder");
  741. if (lbuilder.LocalType is TypeBuilder)
  742. throw new ArgumentException ("Output streams do not support TypeBuilders.");
  743. // The MS implementation does not check for valuetypes here but it
  744. // should.
  745. Emit (OpCodes.Ldloc, lbuilder);
  746. Emit (OpCodes.Call,
  747. typeof (Console).GetMethod ("WriteLine",
  748. new Type[1] { lbuilder.LocalType }));
  749. }
  750. public virtual void EmitWriteLine (string val)
  751. {
  752. Emit (OpCodes.Ldstr, val);
  753. Emit (OpCodes.Call,
  754. typeof (Console).GetMethod ("WriteLine",
  755. new Type[1] { typeof(string)}));
  756. }
  757. public virtual void EndExceptionBlock ()
  758. {
  759. if (open_blocks == null)
  760. open_blocks = new Stack (defaultExceptionStackSize);
  761. if (open_blocks.Count <= 0)
  762. throw new NotSupportedException ("Not in an exception block");
  763. InternalEndClause ();
  764. MarkLabel (ex_handlers [cur_block].end);
  765. ex_handlers [cur_block].End (code_len);
  766. ex_handlers [cur_block].Debug (cur_block);
  767. //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
  768. open_blocks.Pop ();
  769. if (open_blocks.Count > 0)
  770. cur_block = (int)open_blocks.Peek ();
  771. //Console.WriteLine ("curblock restored to {0}", cur_block);
  772. //throw new NotImplementedException ();
  773. }
  774. public virtual void EndScope ()
  775. { }
  776. public virtual void MarkLabel (Label loc)
  777. {
  778. if (loc.label < 0 || loc.label >= num_labels)
  779. throw new System.ArgumentException ("The label is not valid");
  780. if (labels [loc.label].addr >= 0)
  781. throw new System.ArgumentException ("The label was already defined");
  782. labels [loc.label].addr = code_len;
  783. if (labels [loc.label].maxStack > cur_stack)
  784. cur_stack = labels [loc.label].maxStack;
  785. }
  786. public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
  787. int startColumn, int endLine, int endColumn)
  788. {
  789. if (currentSequence == null || currentSequence.Document != document) {
  790. if (sequencePointLists == null)
  791. sequencePointLists = new ArrayList ();
  792. currentSequence = new SequencePointList (document);
  793. sequencePointLists.Add (currentSequence);
  794. }
  795. currentSequence.AddSequencePoint (code_len, startLine, startColumn, endLine, endColumn);
  796. }
  797. internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
  798. {
  799. if (sequencePointLists != null) {
  800. SequencePointList first = (SequencePointList) sequencePointLists [0];
  801. SequencePointList last = (SequencePointList) sequencePointLists [sequencePointLists.Count - 1];
  802. symbolWriter.SetMethodSourceRange (first.Document, first.StartLine, first.StartColumn, last.Document, last.EndLine, last.EndColumn);
  803. foreach (SequencePointList list in sequencePointLists)
  804. symbolWriter.DefineSequencePoints (list.Document, list.GetOffsets(), list.GetLines(), list.GetColumns(), list.GetEndLines(), list.GetEndColumns());
  805. if (locals != null) {
  806. foreach (LocalBuilder local in locals) {
  807. if (local.Name != null && local.Name.Length > 0) {
  808. SignatureHelper sighelper = SignatureHelper.GetLocalVarSigHelper (module);
  809. sighelper.AddArgument (local.LocalType);
  810. byte[] signature = sighelper.GetSignature ();
  811. symbolWriter.DefineLocalVariable (local.Name, FieldAttributes.Public, signature, SymAddressKind.ILOffset, local.position, 0, 0, local.StartOffset, local.EndOffset);
  812. }
  813. }
  814. }
  815. sequencePointLists = null;
  816. }
  817. }
  818. internal bool HasDebugInfo
  819. {
  820. get { return sequencePointLists != null; }
  821. }
  822. public virtual void ThrowException (Type exceptionType)
  823. {
  824. if (exceptionType == null)
  825. throw new ArgumentNullException ("exceptionType");
  826. if (! ((exceptionType == typeof (Exception)) ||
  827. exceptionType.IsSubclassOf (typeof (Exception))))
  828. throw new ArgumentException ("Type should be an exception type", "exceptionType");
  829. ConstructorInfo ctor = exceptionType.GetConstructor (new Type[0]);
  830. if (ctor == null)
  831. throw new ArgumentException ("Type should have a default constructor", "exceptionType");
  832. Emit (OpCodes.Newobj, ctor);
  833. Emit (OpCodes.Throw);
  834. }
  835. [MonoTODO]
  836. public void UsingNamespace (String usingNamespace)
  837. {
  838. throw new NotImplementedException ();
  839. }
  840. internal void label_fixup ()
  841. {
  842. for (int i = 0; i < num_fixups; ++i) {
  843. // Diff is the offset from the end of the jump instruction to the address of the label
  844. int diff = labels [fixups [i].label_idx].addr - (fixups [i].pos + fixups [i].offset);
  845. if (fixups [i].offset == 1) {
  846. code [fixups [i].pos] = (byte)((sbyte) diff);
  847. } else {
  848. int old_cl = code_len;
  849. code_len = fixups [i].pos;
  850. emit_int (diff);
  851. code_len = old_cl;
  852. }
  853. }
  854. }
  855. internal static int Mono_GetCurrentOffset (ILGenerator ig)
  856. {
  857. return ig.code_len;
  858. }
  859. void _ILGenerator.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  860. {
  861. throw new NotImplementedException ();
  862. }
  863. void _ILGenerator.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  864. {
  865. throw new NotImplementedException ();
  866. }
  867. void _ILGenerator.GetTypeInfoCount (out uint pcTInfo)
  868. {
  869. throw new NotImplementedException ();
  870. }
  871. void _ILGenerator.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  872. {
  873. throw new NotImplementedException ();
  874. }
  875. }
  876. internal class SequencePointList
  877. {
  878. ISymbolDocumentWriter doc;
  879. SequencePoint[] points;
  880. int count;
  881. const int arrayGrow = 10;
  882. public SequencePointList (ISymbolDocumentWriter doc)
  883. {
  884. this.doc = doc;
  885. }
  886. public ISymbolDocumentWriter Document {
  887. get { return doc; }
  888. }
  889. public int[] GetOffsets()
  890. {
  891. int[] data = new int [count];
  892. for (int n=0; n<count; n++) data [n] = points[n].Offset;
  893. return data;
  894. }
  895. public int[] GetLines()
  896. {
  897. int[] data = new int [count];
  898. for (int n=0; n<count; n++) data [n] = points[n].Line;
  899. return data;
  900. }
  901. public int[] GetColumns()
  902. {
  903. int[] data = new int [count];
  904. for (int n=0; n<count; n++) data [n] = points[n].Col;
  905. return data;
  906. }
  907. public int[] GetEndLines()
  908. {
  909. int[] data = new int [count];
  910. for (int n=0; n<count; n++) data [n] = points[n].EndLine;
  911. return data;
  912. }
  913. public int[] GetEndColumns()
  914. {
  915. int[] data = new int [count];
  916. for (int n=0; n<count; n++) data [n] = points[n].EndCol;
  917. return data;
  918. }
  919. public int StartLine {
  920. get { return points[0].Line; }
  921. }
  922. public int EndLine {
  923. get { return points[count - 1].Line; }
  924. }
  925. public int StartColumn {
  926. get { return points[0].Col; }
  927. }
  928. public int EndColumn {
  929. get { return points[count - 1].Col; }
  930. }
  931. public void AddSequencePoint (int offset, int line, int col, int endLine, int endCol)
  932. {
  933. SequencePoint s = new SequencePoint ();
  934. s.Offset = offset;
  935. s.Line = line;
  936. s.Col = col;
  937. s.EndLine = endLine;
  938. s.EndCol = endCol;
  939. if (points == null) {
  940. points = new SequencePoint [arrayGrow];
  941. } else if (count >= points.Length) {
  942. SequencePoint[] temp = new SequencePoint [count + arrayGrow];
  943. Array.Copy (points, temp, points.Length);
  944. points = temp;
  945. }
  946. points [count] = s;
  947. count++;
  948. }
  949. }
  950. struct SequencePoint {
  951. public int Offset;
  952. public int Line;
  953. public int Col;
  954. public int EndLine;
  955. public int EndCol;
  956. }
  957. }