MethodBuilderTest.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. //
  2. // MethodBuilderTest.cs - NUnit Test Cases for the MethodBuilder class
  3. //
  4. // Zoltan Varga ([email protected])
  5. //
  6. // (C) Ximian, Inc. http://www.ximian.com
  7. // TODO:
  8. // - implement 'Signature' (what the hell it does???) and test it
  9. // - implement Equals and test it
  10. using System;
  11. using System.Threading;
  12. using System.Reflection;
  13. using System.Reflection.Emit;
  14. using System.Runtime.CompilerServices;
  15. using System.Security;
  16. using System.Security.Permissions;
  17. using System.Runtime.InteropServices;
  18. using NUnit.Framework;
  19. namespace MonoTests.System.Reflection.Emit
  20. {
  21. [TestFixture]
  22. public class MethodBuilderTest
  23. {
  24. private TypeBuilder genClass;
  25. private ModuleBuilder module;
  26. [SetUp]
  27. protected void SetUp ()
  28. {
  29. AssemblyName assemblyName = new AssemblyName ();
  30. assemblyName.Name = "MonoTests.System.Reflection.Emit.MethodBuilderTest";
  31. AssemblyBuilder assembly = Thread.GetDomain ().DefineDynamicAssembly (
  32. assemblyName, AssemblyBuilderAccess.Run);
  33. module = assembly.DefineDynamicModule ("module1");
  34. genClass = module.DefineType (genTypeName (), TypeAttributes.Public);
  35. }
  36. static int methodIndexer = 0;
  37. static int typeIndexer = 0;
  38. // Return a unique method name
  39. private string genMethodName ()
  40. {
  41. return "m" + (methodIndexer++);
  42. }
  43. // Return a unique type name
  44. private string genTypeName ()
  45. {
  46. return "class" + (typeIndexer++);
  47. }
  48. [Test]
  49. public void TestAttributes ()
  50. {
  51. MethodBuilder mb = genClass.DefineMethod (
  52. genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]);
  53. Assert.AreEqual (MethodAttributes.Public, mb.Attributes);
  54. }
  55. [Test]
  56. public void TestCallingConvention ()
  57. {
  58. MethodBuilder mb = genClass.DefineMethod (
  59. genMethodName (), 0, typeof (void), new Type [0]);
  60. Assert.AreEqual (CallingConventions.Standard | CallingConventions.HasThis,
  61. mb.CallingConvention, "CallingConvetion defaults to Standard+HasThis");
  62. MethodBuilder mb3 = genClass.DefineMethod (
  63. genMethodName (), 0, CallingConventions.VarArgs, typeof (void), new Type [0]);
  64. Assert.AreEqual (CallingConventions.VarArgs | CallingConventions.HasThis,
  65. mb3.CallingConvention, "CallingConvetion works");
  66. MethodBuilder mb4 = genClass.DefineMethod (
  67. genMethodName (), MethodAttributes.Static, CallingConventions.Standard,
  68. typeof (void), new Type [0]);
  69. Assert.AreEqual (CallingConventions.Standard, mb4.CallingConvention,
  70. "Static implies !HasThis");
  71. }
  72. [Test]
  73. public void TestDeclaringType ()
  74. {
  75. MethodBuilder mb = genClass.DefineMethod (
  76. genMethodName (), 0, typeof (void), new Type [0]);
  77. Assert.AreEqual (genClass, mb.DeclaringType, "DeclaringType works");
  78. }
  79. [Test]
  80. public void TestInitLocals ()
  81. {
  82. MethodBuilder mb = genClass.DefineMethod (
  83. genMethodName (), 0, typeof (void), new Type [0]);
  84. Assert.IsTrue (mb.InitLocals, "#1");
  85. mb.InitLocals = false;
  86. Assert.IsFalse (mb.InitLocals, "#2");
  87. }
  88. [Test]
  89. [ExpectedException (typeof (NotSupportedException))]
  90. public void TestMethodHandleIncomplete ()
  91. {
  92. MethodBuilder mb = genClass.DefineMethod (
  93. genMethodName (), 0, typeof (void), new Type [0]);
  94. RuntimeMethodHandle handle = mb.MethodHandle;
  95. }
  96. [Test]
  97. [ExpectedException (typeof (NotSupportedException))]
  98. public void TestMethodHandleComplete ()
  99. {
  100. MethodBuilder mb = genClass.DefineMethod (
  101. genMethodName (), 0, typeof (void), new Type [0]);
  102. mb.CreateMethodBody (new byte [2], 1);
  103. genClass.CreateType ();
  104. RuntimeMethodHandle handle = mb.MethodHandle;
  105. }
  106. [Test]
  107. public void TestName ()
  108. {
  109. string name = genMethodName ();
  110. MethodBuilder mb = genClass.DefineMethod (
  111. name, 0, typeof (void), new Type [0]);
  112. Assert.AreEqual (name, mb.Name);
  113. }
  114. [Test]
  115. public void TestReflectedType ()
  116. {
  117. MethodBuilder mb = genClass.DefineMethod (
  118. genMethodName (), 0, typeof (void), new Type [0]);
  119. Assert.AreEqual (genClass, mb.ReflectedType);
  120. }
  121. [Test]
  122. public void TestReturnType ()
  123. {
  124. MethodBuilder mb = genClass.DefineMethod (
  125. genMethodName (), 0, typeof (Console), new Type [0]);
  126. Assert.AreEqual (typeof (Console), mb.ReturnType, "#1");
  127. MethodBuilder mb2 = genClass.DefineMethod (
  128. genMethodName (), 0, null, new Type [0]);
  129. Assert.IsTrue (mb2.ReturnType == null || mb2.ReturnType == typeof (void), "#2");
  130. }
  131. [Test]
  132. public void TestReturnTypeCustomAttributes ()
  133. {
  134. MethodBuilder mb = genClass.DefineMethod (
  135. genMethodName (), 0, typeof (Console), new Type [0]);
  136. Assert.IsNull (mb.ReturnTypeCustomAttributes);
  137. }
  138. /*
  139. public void TestSignature () {
  140. MethodBuilder mb = genClass.DefineMethod (
  141. "m91", 0, typeof (Console), new Type [1] { typeof (Console) });
  142. Console.WriteLine (mb.Signature);
  143. }
  144. */
  145. [Test]
  146. public void TestCreateMethodBody ()
  147. {
  148. MethodBuilder mb = genClass.DefineMethod (
  149. genMethodName (), 0, typeof (void), new Type [0]);
  150. // Clear body
  151. mb.CreateMethodBody (null, 999);
  152. // Check arguments 1.
  153. try {
  154. mb.CreateMethodBody (new byte [1], -1);
  155. Assert.Fail ("#1");
  156. } catch (ArgumentOutOfRangeException) {
  157. }
  158. // Check arguments 2.
  159. try {
  160. mb.CreateMethodBody (new byte [1], 2);
  161. Assert.Fail ("#2");
  162. } catch (ArgumentOutOfRangeException) {
  163. }
  164. mb.CreateMethodBody (new byte [2], 1);
  165. // Could only be called once
  166. try {
  167. mb.CreateMethodBody (new byte [2], 1);
  168. Assert.Fail ("#3");
  169. } catch (InvalidOperationException) {
  170. }
  171. // Can not be called on a created type
  172. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  173. MethodBuilder mb2 = tb.DefineMethod (
  174. genMethodName (), 0, typeof (void), new Type [0]);
  175. ILGenerator ilgen = mb2.GetILGenerator ();
  176. ilgen.Emit (OpCodes.Ret);
  177. tb.CreateType ();
  178. try {
  179. mb2.CreateMethodBody (new byte [2], 1);
  180. Assert.Fail ("#4");
  181. } catch (InvalidOperationException) {
  182. }
  183. }
  184. [Test]
  185. [ExpectedException (typeof (InvalidOperationException))]
  186. public void TestDefineParameterInvalidIndexComplete ()
  187. {
  188. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  189. MethodBuilder mb = tb.DefineMethod (genMethodName (), 0, typeof (void),
  190. new Type [2] { typeof(int), typeof(int) });
  191. mb.CreateMethodBody (new byte [2], 1);
  192. tb.CreateType ();
  193. mb.DefineParameter (-5, ParameterAttributes.None, "param1");
  194. }
  195. [Test]
  196. [ExpectedException (typeof (InvalidOperationException))]
  197. public void TestDefineParameterValidIndexComplete ()
  198. {
  199. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  200. MethodBuilder mb = tb.DefineMethod (genMethodName (), 0, typeof (void),
  201. new Type [2] { typeof(int), typeof(int) });
  202. mb.CreateMethodBody (new byte [2], 1);
  203. tb.CreateType ();
  204. mb.DefineParameter (1, ParameterAttributes.None, "param1");
  205. }
  206. [Test]
  207. public void TestDefineParameter ()
  208. {
  209. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  210. MethodBuilder mb = tb.DefineMethod (
  211. genMethodName (), 0, typeof (void),
  212. new Type [2] { typeof (int), typeof (int) });
  213. // index out of range
  214. // This fails on mono because the mono version accepts a 0 index
  215. /*
  216. try {
  217. mb.DefineParameter (0, 0, "param1");
  218. Fail ();
  219. } catch (ArgumentOutOfRangeException) {
  220. }
  221. */
  222. try {
  223. mb.DefineParameter (3, 0, "param1");
  224. Assert.Fail ("#1");
  225. } catch (ArgumentOutOfRangeException) {
  226. }
  227. // Normal usage
  228. mb.DefineParameter (1, 0, "param1");
  229. mb.DefineParameter (1, 0, "param1");
  230. mb.DefineParameter (2, 0, null);
  231. mb.CreateMethodBody (new byte [2], 1);
  232. tb.CreateType ();
  233. try {
  234. mb.DefineParameter (1, 0, "param1");
  235. Assert.Fail ("#2");
  236. } catch (InvalidOperationException) {
  237. }
  238. }
  239. [Test]
  240. #if NET_2_0
  241. // MS.NET 2.x no longer allows a zero length method body
  242. // to be emitted
  243. [ExpectedException (typeof (InvalidOperationException))]
  244. #endif
  245. public void ZeroLengthBodyTest1 ()
  246. {
  247. MethodBuilder mb = genClass.DefineMethod (
  248. genMethodName (), 0, typeof (void),
  249. new Type [2] { typeof (int), typeof (int) });
  250. mb.CreateMethodBody (new byte [2], 0);
  251. genClass.CreateType ();
  252. }
  253. // A zero length method body can be created
  254. [Test]
  255. public void ZeroLengthBodyTest2 ()
  256. {
  257. MethodBuilder mb = genClass.DefineMethod (
  258. genMethodName (), 0, typeof (void),
  259. new Type [2] { typeof (int), typeof (int) });
  260. mb.CreateMethodBody (new byte [2], 0);
  261. }
  262. [Test]
  263. public void TestHashCode ()
  264. {
  265. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  266. string methodName = genMethodName ();
  267. MethodBuilder mb = tb.DefineMethod (methodName, 0, typeof (void),
  268. new Type [2] { typeof(int), typeof(int) });
  269. Assert.AreEqual (methodName.GetHashCode (), mb.GetHashCode ());
  270. }
  271. [Test]
  272. public void TestGetBaseDefinition ()
  273. {
  274. MethodBuilder mb = genClass.DefineMethod (
  275. genMethodName (), 0, typeof (void), new Type [0]);
  276. Assert.AreEqual (mb.GetBaseDefinition (), mb);
  277. }
  278. [Test]
  279. public void TestGetILGenerator ()
  280. {
  281. MethodBuilder mb = genClass.DefineMethod (
  282. genMethodName (), 0, typeof (void), new Type [0]);
  283. // The same instance is returned on the second call
  284. ILGenerator ilgen1 = mb.GetILGenerator ();
  285. ILGenerator ilgen2 = mb.GetILGenerator ();
  286. Assert.AreEqual (ilgen1, ilgen2, "#1");
  287. // Does not work on unmanaged code
  288. MethodBuilder mb2 = genClass.DefineMethod (
  289. genMethodName (), 0, typeof (void), new Type [0]);
  290. try {
  291. mb2.SetImplementationFlags (MethodImplAttributes.Unmanaged);
  292. mb2.GetILGenerator ();
  293. Assert.Fail ("#2");
  294. } catch (InvalidOperationException) {
  295. }
  296. try {
  297. mb2.SetImplementationFlags (MethodImplAttributes.Native);
  298. mb2.GetILGenerator ();
  299. Assert.Fail ("#3");
  300. } catch (InvalidOperationException) {
  301. }
  302. }
  303. [Test]
  304. public void TestMethodImplementationFlags ()
  305. {
  306. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  307. MethodBuilder mb = tb.DefineMethod (
  308. genMethodName (), 0, typeof (void), new Type [0]);
  309. Assert.AreEqual (MethodImplAttributes.Managed | MethodImplAttributes.IL,
  310. mb.GetMethodImplementationFlags (), "#1");
  311. mb.SetImplementationFlags (MethodImplAttributes.OPTIL);
  312. Assert.AreEqual (MethodImplAttributes.OPTIL, mb.GetMethodImplementationFlags (), "#2");
  313. mb.CreateMethodBody (new byte [2], 1);
  314. mb.SetImplementationFlags (MethodImplAttributes.Managed);
  315. tb.CreateType ();
  316. try {
  317. mb.SetImplementationFlags (MethodImplAttributes.OPTIL);
  318. Assert.Fail ("#3");
  319. } catch (InvalidOperationException) {
  320. }
  321. }
  322. [Test]
  323. public void TestGetModule ()
  324. {
  325. MethodBuilder mb = genClass.DefineMethod (
  326. genMethodName (), 0, typeof (void), new Type [0]);
  327. Assert.AreEqual (module, mb.GetModule ());
  328. }
  329. [Test]
  330. public void TestGetParameters ()
  331. {
  332. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  333. MethodBuilder mb = tb.DefineMethod (genMethodName (), 0, typeof (void),
  334. new Type [1] { typeof (void) });
  335. /*
  336. * According to the MSDN docs, this method should fail with a
  337. * NotSupportedException. In reality, it throws an
  338. * InvalidOperationException under MS .NET, and returns the
  339. * requested data under mono.
  340. */
  341. /*
  342. try {
  343. mb.GetParameters ();
  344. Fail ("#161");
  345. } catch (InvalidOperationException ex) {
  346. Console.WriteLine (ex);
  347. }
  348. */
  349. }
  350. [Test]
  351. public void TestGetToken ()
  352. {
  353. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  354. MethodBuilder mb = tb.DefineMethod (
  355. genMethodName (), 0, typeof (void), new Type [1] { typeof (void) });
  356. mb.GetToken ();
  357. }
  358. [Test]
  359. public void TestInvoke ()
  360. {
  361. MethodBuilder mb = genClass.DefineMethod (
  362. genMethodName (), 0, typeof (void),
  363. new Type [1] { typeof (int) });
  364. try {
  365. mb.Invoke (null, new object [1] { 42 });
  366. Assert.Fail ("#1");
  367. } catch (NotSupportedException) {
  368. }
  369. try {
  370. mb.Invoke (null, 0, null, new object [1] { 42 }, null);
  371. Assert.Fail ("#2");
  372. } catch (NotSupportedException) {
  373. }
  374. }
  375. [Test]
  376. [ExpectedException (typeof (NotSupportedException))]
  377. public void TestIsDefined ()
  378. {
  379. MethodBuilder mb = genClass.DefineMethod (
  380. genMethodName (), 0, typeof (void),
  381. new Type [1] { typeof (int) });
  382. mb.IsDefined (null, true);
  383. }
  384. [Test]
  385. public void TestGetCustomAttributes_Incomplete ()
  386. {
  387. MethodBuilder mb = genClass.DefineMethod (
  388. genMethodName (), 0, typeof (void),
  389. new Type [1] { typeof (int) });
  390. try {
  391. mb.GetCustomAttributes (true);
  392. Assert.Fail ("#1");
  393. } catch (NotSupportedException) {
  394. }
  395. try {
  396. mb.GetCustomAttributes (null, true);
  397. Assert.Fail ("#2");
  398. } catch (NotSupportedException) {
  399. }
  400. }
  401. [Test]
  402. [Category ("NotWorking")]
  403. public void TestGetCustomAttributes_Complete ()
  404. {
  405. MethodBuilder mb = genClass.DefineMethod (
  406. genMethodName (), 0, typeof (void),
  407. new Type [1] { typeof (int) });
  408. mb.GetILGenerator ().Emit (OpCodes.Ret);
  409. genClass.CreateType ();
  410. try {
  411. mb.GetCustomAttributes (true);
  412. Assert.Fail ("#1");
  413. } catch (NotSupportedException) {
  414. }
  415. try {
  416. mb.GetCustomAttributes (null, true);
  417. Assert.Fail ("#2");
  418. } catch (NotSupportedException) {
  419. }
  420. }
  421. [Test]
  422. public void TestSetCustomAttribute ()
  423. {
  424. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  425. string name = genMethodName ();
  426. MethodBuilder mb = tb.DefineMethod (
  427. name, MethodAttributes.Public, typeof (void),
  428. new Type [1] { typeof (int) });
  429. // Null argument
  430. try {
  431. mb.SetCustomAttribute (null);
  432. Assert.Fail ("#1");
  433. } catch (ArgumentNullException) {
  434. }
  435. byte [] custAttrData = { 1, 0, 0, 0, 0 };
  436. Type attrType = Type.GetType
  437. ("System.Reflection.AssemblyKeyNameAttribute");
  438. Type [] paramTypes = new Type [1];
  439. paramTypes [0] = typeof (String);
  440. ConstructorInfo ctorInfo =
  441. attrType.GetConstructor (paramTypes);
  442. mb.SetCustomAttribute (ctorInfo, custAttrData);
  443. // Test MethodImplAttribute
  444. mb.SetCustomAttribute (new CustomAttributeBuilder (typeof (MethodImplAttribute).GetConstructor (new Type [1] { typeof (short) }), new object [1] { (short) MethodImplAttributes.Synchronized }));
  445. mb.GetILGenerator ().Emit (OpCodes.Ret);
  446. Type t = tb.CreateType ();
  447. Assert.AreEqual (t.GetMethod (name).GetMethodImplementationFlags (),
  448. MethodImplAttributes.Synchronized, "#2");
  449. // Null arguments again
  450. try {
  451. mb.SetCustomAttribute (null, new byte [2]);
  452. Assert.Fail ("#3");
  453. } catch (ArgumentNullException) {
  454. }
  455. try {
  456. mb.SetCustomAttribute (ctorInfo, null);
  457. Assert.Fail ("#4");
  458. } catch (ArgumentNullException) {
  459. }
  460. }
  461. [Test]
  462. public void SetCustomAttribute_DllImport_DllName_Empty ()
  463. {
  464. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  465. MethodBuilder mb = tb.DefineMethod (genMethodName (),
  466. MethodAttributes.Public, typeof (void),
  467. new Type [1] { typeof (int) });
  468. ConstructorInfo ctorInfo = typeof (DllImportAttribute).GetConstructor (
  469. new Type [] { typeof (string) });
  470. try {
  471. mb.SetCustomAttribute (new CustomAttributeBuilder (ctorInfo,
  472. new object [] { string.Empty }));
  473. Assert.Fail ("#1");
  474. } catch (ArgumentException ex) {
  475. Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
  476. Assert.IsNull (ex.InnerException, "#3");
  477. Assert.IsNotNull (ex.Message, "#4");
  478. Assert.IsNull (ex.ParamName, "#5");
  479. }
  480. }
  481. [Test]
  482. public void SetCustomAttribute_DllImport_DllName_Null ()
  483. {
  484. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  485. MethodBuilder mb = tb.DefineMethod (genMethodName (),
  486. MethodAttributes.Public, typeof (void),
  487. new Type [1] { typeof (int) });
  488. ConstructorInfo ctorInfo = typeof (DllImportAttribute).GetConstructor (
  489. new Type [] { typeof (string) });
  490. try {
  491. mb.SetCustomAttribute (new CustomAttributeBuilder (ctorInfo,
  492. new object [] { null }));
  493. Assert.Fail ("#1");
  494. } catch (ArgumentException ex) {
  495. Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
  496. Assert.IsNull (ex.InnerException, "#3");
  497. Assert.IsNotNull (ex.Message, "#4");
  498. Assert.IsNull (ex.ParamName, "#5");
  499. }
  500. }
  501. [Test]
  502. public void SetCustomAttribute_SuppressUnmanagedCodeSecurity ()
  503. {
  504. string mname = genMethodName ();
  505. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  506. MethodBuilder mb = tb.DefineMethod (mname, MethodAttributes.Public,
  507. typeof (void), new Type [] { typeof (int), typeof (string) });
  508. ConstructorInfo attrCtor = typeof (SuppressUnmanagedCodeSecurityAttribute).
  509. GetConstructor (new Type [0]);
  510. CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (
  511. attrCtor, new object [0]);
  512. Assert.IsTrue ((mb.Attributes & MethodAttributes.HasSecurity) == 0, "#1");
  513. mb.SetCustomAttribute (caBuilder);
  514. //Assert.IsTrue ((mb.Attributes & MethodAttributes.HasSecurity) == 0, "#2");
  515. mb.GetILGenerator ().Emit (OpCodes.Ret);
  516. Type emittedType = tb.CreateType ();
  517. MethodInfo emittedMethod = emittedType.GetMethod (mname);
  518. Assert.AreEqual (MethodAttributes.HasSecurity, emittedMethod.Attributes & MethodAttributes.HasSecurity, "#3");
  519. //Assert.IsTrue ((mb.Attributes & MethodAttributes.HasSecurity) == 0, "#4");
  520. object [] emittedAttrs = emittedMethod.GetCustomAttributes (typeof (SuppressUnmanagedCodeSecurityAttribute), true);
  521. Assert.AreEqual (1, emittedAttrs.Length, "#5");
  522. }
  523. [AttributeUsage (AttributeTargets.Parameter)]
  524. class PrivateAttribute : Attribute
  525. {
  526. public PrivateAttribute ()
  527. {
  528. }
  529. }
  530. [Test]
  531. public void GetCustomAttributes ()
  532. {
  533. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  534. MethodBuilder mb = tb.DefineMethod ("foo", MethodAttributes.Public,
  535. typeof (void),
  536. new Type [1] { typeof (int) });
  537. mb.GetILGenerator ().Emit (OpCodes.Ret);
  538. Type attrType = typeof (ObsoleteAttribute);
  539. ConstructorInfo ctorInfo =
  540. attrType.GetConstructor (new Type [] { typeof (String) });
  541. mb.SetCustomAttribute (new CustomAttributeBuilder (ctorInfo, new object [] { "FOO" }));
  542. // Check that attributes not accessible are not returned
  543. mb.SetCustomAttribute (new CustomAttributeBuilder (typeof (PrivateAttribute).GetConstructor (new Type [0]), new object [] { }));
  544. Type t = tb.CreateType ();
  545. // Try the created type
  546. {
  547. MethodInfo mi = t.GetMethod ("foo");
  548. object [] attrs = mi.GetCustomAttributes (true);
  549. Assert.AreEqual (1, attrs.Length, "#A1");
  550. Assert.IsTrue (attrs [0] is ObsoleteAttribute, "#A2");
  551. Assert.AreEqual ("FOO", ((ObsoleteAttribute) attrs [0]).Message, "#A3");
  552. }
  553. // Try the type builder
  554. {
  555. MethodInfo mi = tb.GetMethod ("foo");
  556. object [] attrs = mi.GetCustomAttributes (true);
  557. Assert.AreEqual (1, attrs.Length, "#B1");
  558. Assert.IsTrue (attrs [0] is ObsoleteAttribute, "#B2");
  559. Assert.AreEqual ("FOO", ((ObsoleteAttribute) attrs [0]).Message, "#B3");
  560. }
  561. }
  562. [Test]
  563. [ExpectedException (typeof (InvalidOperationException))]
  564. public void TestAddDeclarativeSecurityAlreadyCreated ()
  565. {
  566. MethodBuilder mb = genClass.DefineMethod (
  567. genMethodName (), MethodAttributes.Public, typeof (void),
  568. new Type [0]);
  569. ILGenerator ilgen = mb.GetILGenerator ();
  570. ilgen.Emit (OpCodes.Ret);
  571. genClass.CreateType ();
  572. PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
  573. mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
  574. }
  575. [Test]
  576. [ExpectedException (typeof (ArgumentNullException))]
  577. public void TestAddDeclarativeSecurityNullPermissionSet ()
  578. {
  579. MethodBuilder mb = genClass.DefineMethod (
  580. genMethodName (), MethodAttributes.Public, typeof (void),
  581. new Type [0]);
  582. mb.AddDeclarativeSecurity (SecurityAction.Demand, null);
  583. }
  584. [Test]
  585. public void TestAddDeclarativeSecurityInvalidAction ()
  586. {
  587. MethodBuilder mb = genClass.DefineMethod (
  588. genMethodName (), MethodAttributes.Public, typeof (void),
  589. new Type [0]);
  590. SecurityAction [] actions = new SecurityAction [] {
  591. SecurityAction.RequestMinimum,
  592. SecurityAction.RequestOptional,
  593. SecurityAction.RequestRefuse };
  594. PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
  595. foreach (SecurityAction action in actions) {
  596. try {
  597. mb.AddDeclarativeSecurity (action, set);
  598. Assert.Fail ();
  599. } catch (ArgumentOutOfRangeException) {
  600. }
  601. }
  602. }
  603. [Test]
  604. [ExpectedException (typeof (InvalidOperationException))]
  605. public void TestAddDeclarativeSecurityDuplicateAction ()
  606. {
  607. MethodBuilder mb = genClass.DefineMethod (
  608. genMethodName (), MethodAttributes.Public, typeof (void),
  609. new Type [0]);
  610. PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
  611. mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
  612. mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
  613. }
  614. [AttributeUsage (AttributeTargets.Parameter)]
  615. class ParamAttribute : Attribute
  616. {
  617. public ParamAttribute ()
  618. {
  619. }
  620. }
  621. [Test]
  622. public void TestDynamicParams ()
  623. {
  624. string mname = genMethodName ();
  625. MethodBuilder mb = genClass.DefineMethod (
  626. mname, MethodAttributes.Public, typeof (void),
  627. new Type [] { typeof (int), typeof (string) });
  628. ParameterBuilder pb = mb.DefineParameter (1, ParameterAttributes.In, "foo");
  629. pb.SetConstant (52);
  630. pb.SetCustomAttribute (new CustomAttributeBuilder (typeof (ParamAttribute).GetConstructors () [0], new object [] { }));
  631. ParameterBuilder pb2 = mb.DefineParameter (2, 0, "bar");
  632. pb2.SetConstant ("foo");
  633. mb.GetILGenerator ().Emit (OpCodes.Ret);
  634. Type t = genClass.CreateType ();
  635. MethodInfo m = t.GetMethod (mname);
  636. ParameterInfo [] pi = m.GetParameters ();
  637. Assert.AreEqual ("foo", pi [0].Name, "#A1");
  638. Assert.IsTrue (pi [0].IsIn, "#A2");
  639. Assert.AreEqual (52, pi [0].DefaultValue, "#A3");
  640. object [] cattrs = pi [0].GetCustomAttributes (true);
  641. #if NET_2_0
  642. Assert.AreEqual (1, cattrs.Length, "#A4");
  643. Assert.AreEqual (typeof (InAttribute), cattrs [0].GetType (), "#A5");
  644. #else
  645. Assert.AreEqual (0, cattrs.Length, "#A4");
  646. #endif
  647. Assert.AreEqual ("foo", pi [1].DefaultValue, "#B1");
  648. }
  649. #if NET_2_0
  650. [Test]
  651. public void SetCustomAttribute_DllImport1 ()
  652. {
  653. string mname = genMethodName ();
  654. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  655. MethodBuilder mb = tb.DefineMethod (
  656. mname, MethodAttributes.Public, typeof (void),
  657. new Type [] { typeof (int), typeof (string) });
  658. // Create an attribute with default values
  659. mb.SetCustomAttribute (new CustomAttributeBuilder(typeof(DllImportAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { "kernel32" }));
  660. Type t = tb.CreateType ();
  661. DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]);
  662. Assert.AreEqual (CallingConvention.Winapi, attr.CallingConvention, "#1");
  663. Assert.AreEqual (mname, attr.EntryPoint, "#2");
  664. Assert.AreEqual ("kernel32", attr.Value, "#3");
  665. Assert.IsFalse (attr.ExactSpelling, "#4");
  666. Assert.IsTrue (attr.PreserveSig, "#5");
  667. Assert.IsFalse (attr.SetLastError, "#6");
  668. Assert.IsFalse (attr.BestFitMapping, "#7");
  669. Assert.IsFalse (attr.ThrowOnUnmappableChar, "#8");
  670. }
  671. [Test]
  672. public void SetCustomAttribute_DllImport2 () {
  673. string mname = genMethodName ();
  674. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  675. MethodBuilder mb = tb.DefineMethod (
  676. mname, MethodAttributes.Public, typeof (void),
  677. new Type [] { typeof (int), typeof (string) });
  678. CustomAttributeBuilder cb = new CustomAttributeBuilder (typeof (DllImportAttribute).GetConstructor (new Type [] {typeof (String)}), new object [] { "foo" }, new FieldInfo [] {typeof (DllImportAttribute).GetField ("EntryPoint"), typeof (DllImportAttribute).GetField ("CallingConvention"), typeof (DllImportAttribute).GetField ("CharSet"), typeof (DllImportAttribute).GetField ("ExactSpelling"), typeof (DllImportAttribute).GetField ("PreserveSig")}, new object [] { "bar", CallingConvention.StdCall, CharSet.Unicode, true, false });
  679. mb.SetCustomAttribute (cb);
  680. Type t = tb.CreateType ();
  681. DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]);
  682. Assert.AreEqual (CallingConvention.StdCall, attr.CallingConvention, "#1");
  683. Assert.AreEqual (CharSet.Unicode, attr.CharSet, "#2");
  684. Assert.AreEqual ("bar", attr.EntryPoint, "#3");
  685. Assert.AreEqual ("foo", attr.Value, "#4");
  686. Assert.IsTrue (attr.ExactSpelling, "#5");
  687. Assert.IsFalse (attr.PreserveSig, "#6");
  688. Assert.IsFalse (attr.SetLastError, "#7");
  689. Assert.IsFalse (attr.BestFitMapping, "#8");
  690. Assert.IsFalse (attr.ThrowOnUnmappableChar, "#9");
  691. }
  692. [Test]
  693. public void SetCustomAttribute_DllImport3 () {
  694. string mname = genMethodName ();
  695. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  696. MethodBuilder mb = tb.DefineMethod (
  697. mname, MethodAttributes.Public, typeof (void),
  698. new Type [] { typeof (int), typeof (string) });
  699. // Test attributes with three values (on/off/missing)
  700. CustomAttributeBuilder cb = new CustomAttributeBuilder (typeof (DllImportAttribute).GetConstructor (new Type [] {typeof (String)}), new object [] { "foo" }, new FieldInfo [] { typeof (DllImportAttribute).GetField ("BestFitMapping"), typeof (DllImportAttribute).GetField ("ThrowOnUnmappableChar")}, new object [] { false, false });
  701. mb.SetCustomAttribute (cb);
  702. Type t = tb.CreateType ();
  703. DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]);
  704. Assert.IsFalse (attr.BestFitMapping, "#1");
  705. Assert.IsFalse (attr.ThrowOnUnmappableChar, "#2");
  706. }
  707. [Test]
  708. public void SetCustomAttribute_DllImport4 ()
  709. {
  710. string mname = genMethodName ();
  711. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  712. MethodBuilder mb = tb.DefineMethod (
  713. mname, MethodAttributes.Public, typeof (void),
  714. new Type [] { typeof (int), typeof (string) });
  715. CustomAttributeBuilder cb = new CustomAttributeBuilder (typeof (DllImportAttribute).GetConstructor (new Type [] {typeof (String)}), new object [] { "foo" }, new FieldInfo [] { typeof (DllImportAttribute).GetField ("SetLastError"), typeof (DllImportAttribute).GetField ("BestFitMapping"), typeof (DllImportAttribute).GetField ("ThrowOnUnmappableChar")}, new object [] { true, true, true });
  716. mb.SetCustomAttribute (cb);
  717. Type t = tb.CreateType ();
  718. DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]);
  719. Assert.IsTrue (attr.SetLastError, "#1");
  720. Assert.IsTrue (attr.BestFitMapping, "#2");
  721. Assert.IsTrue (attr.ThrowOnUnmappableChar, "#3");
  722. }
  723. public class GenericFoo <T> {
  724. public static T field;
  725. }
  726. [Test]
  727. public void ILGen_GenericTypeParameterBuilder ()
  728. {
  729. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  730. MethodBuilder mb = tb.DefineMethod ("box_int",
  731. MethodAttributes.Public|MethodAttributes.Static, typeof (object), new Type [] { typeof (int) });
  732. GenericTypeParameterBuilder[] pars = mb.DefineGenericParameters (new string [] { "foo" });
  733. ILGenerator ilgen = mb.GetILGenerator ();
  734. ilgen.Emit (OpCodes.Ldarg_0);
  735. ilgen.Emit (OpCodes.Box, pars [0]);
  736. ilgen.Emit (OpCodes.Ret);
  737. Type t = tb.CreateType ();
  738. MethodInfo mi = t.GetMethod ("box_int");
  739. MethodInfo mi2 = mi.MakeGenericMethod (new Type [] { typeof (int) });
  740. Assert.AreEqual (1, mi2.Invoke (null, new object [] { 1 }));
  741. }
  742. public void ILGen_InstantiatedGenericType ()
  743. {
  744. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  745. MethodBuilder mb = tb.DefineMethod ("return_type",
  746. MethodAttributes.Public|MethodAttributes.Static, typeof (object), new Type [] { });
  747. GenericTypeParameterBuilder[] pars = mb.DefineGenericParameters (new string [] { "foo" });
  748. ILGenerator ilgen = mb.GetILGenerator ();
  749. Type genericFoo = typeof (GenericFoo<int>).GetGenericTypeDefinition ().MakeGenericType (new Type [] { pars [0] });
  750. ilgen.Emit (OpCodes.Ldtoken, genericFoo);
  751. ilgen.Emit (OpCodes.Call, typeof (Type).GetMethod ("GetTypeFromHandle"));
  752. ilgen.Emit (OpCodes.Ret);
  753. Type t = tb.CreateType ();
  754. MethodInfo mi = t.GetMethod ("box_int");
  755. MethodInfo mi2 = mi.MakeGenericMethod (new Type [] { typeof (int) });
  756. Assert.AreEqual (typeof (GenericFoo<int>), mi2.Invoke (null, new object [] { 1 }));
  757. }
  758. public void ILGen_InstantiatedTypeBuilder ()
  759. {
  760. TypeBuilder genericTb = module.DefineType (genTypeName (), TypeAttributes.Public);
  761. genericTb.DefineGenericParameters (new string [] { "foo" });
  762. Type generatedGenericType = genericTb.CreateType ();
  763. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  764. MethodBuilder mb = tb.DefineMethod ("return_type",
  765. MethodAttributes.Public|MethodAttributes.Static, typeof (object), new Type [] { });
  766. GenericTypeParameterBuilder[] pars = mb.DefineGenericParameters (new string [] { "foo" });
  767. ILGenerator ilgen = mb.GetILGenerator ();
  768. ilgen.Emit (OpCodes.Ldtoken, genericTb.MakeGenericType (new Type [] { pars [0] }));
  769. ilgen.Emit (OpCodes.Call, typeof (Type).GetMethod ("GetTypeFromHandle"));
  770. ilgen.Emit (OpCodes.Ret);
  771. Type t = tb.CreateType ();
  772. MethodInfo mi = t.GetMethod ("return_type");
  773. MethodInfo mi2 = mi.MakeGenericMethod (new Type [] { typeof (int) });
  774. Assert.AreEqual (generatedGenericType.MakeGenericType (new Type [] { typeof (int) }), mi2.Invoke (null, new object [] { 1 }));
  775. }
  776. #endif
  777. }
  778. }