MethodBuilderTest.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 NUnit.Framework;
  18. namespace MonoTests.System.Reflection.Emit
  19. {
  20. [TestFixture]
  21. public class MethodBuilderTest : Assertion
  22. {
  23. private TypeBuilder genClass;
  24. private ModuleBuilder module;
  25. [SetUp]
  26. protected void SetUp () {
  27. AssemblyName assemblyName = new AssemblyName();
  28. assemblyName.Name = "MonoTests.System.Reflection.Emit.MethodBuilderTest";
  29. AssemblyBuilder assembly
  30. = Thread.GetDomain().DefineDynamicAssembly(
  31. assemblyName, AssemblyBuilderAccess.Run);
  32. module = assembly.DefineDynamicModule("module1");
  33. genClass = module.DefineType(genTypeName (),
  34. TypeAttributes.Public);
  35. }
  36. static int methodIndexer = 0;
  37. static int typeIndexer = 0;
  38. // Return a unique method name
  39. private string genMethodName () {
  40. return "m" + (methodIndexer ++);
  41. }
  42. // Return a unique type name
  43. private string genTypeName () {
  44. return "class" + (typeIndexer ++);
  45. }
  46. public void TestAttributes () {
  47. MethodBuilder mb = genClass.DefineMethod (
  48. genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]);
  49. AssertEquals ("Attributes works",
  50. MethodAttributes.Public, mb.Attributes);
  51. }
  52. public void TestCallingConvention () {
  53. MethodBuilder mb = genClass.DefineMethod (
  54. genMethodName (), 0, typeof (void), new Type[0]);
  55. AssertEquals ("CallingConvetion defaults to Standard+HasThis",
  56. CallingConventions.Standard | CallingConventions.HasThis,
  57. mb.CallingConvention);
  58. MethodBuilder mb3 = genClass.DefineMethod (
  59. genMethodName (), 0, CallingConventions.VarArgs, typeof (void), new Type[0]);
  60. AssertEquals ("CallingConvetion works",
  61. CallingConventions.VarArgs | CallingConventions.HasThis,
  62. mb3.CallingConvention);
  63. MethodBuilder mb4 = genClass.DefineMethod (
  64. genMethodName (), MethodAttributes.Static, CallingConventions.Standard,
  65. typeof (void), new Type [0]);
  66. AssertEquals ("Static implies !HasThis",
  67. CallingConventions.Standard,
  68. mb4.CallingConvention);
  69. }
  70. public void TestDeclaringType () {
  71. MethodBuilder mb = genClass.DefineMethod (
  72. genMethodName (), 0, typeof (void), new Type[0]);
  73. AssertEquals ("DeclaringType works",
  74. genClass, mb.DeclaringType);
  75. }
  76. public void TestInitLocals () {
  77. MethodBuilder mb = genClass.DefineMethod (
  78. genMethodName (), 0, typeof (void), new Type[0]);
  79. Assert ("InitLocals defaults to true", mb.InitLocals);
  80. mb.InitLocals = false;
  81. Assert ("InitLocals is settable", !mb.InitLocals);
  82. }
  83. public void TestMethodHandle () {
  84. MethodBuilder mb = genClass.DefineMethod (
  85. genMethodName (), 0, typeof (void), new Type [0]);
  86. try {
  87. RuntimeMethodHandle handle = mb.MethodHandle;
  88. Fail ();
  89. } catch (NotSupportedException) {
  90. }
  91. }
  92. public void TestName () {
  93. string name = genMethodName ();
  94. MethodBuilder mb = genClass.DefineMethod (
  95. name, 0, typeof (void), new Type [0]);
  96. AssertEquals ("Name works", name, mb.Name);
  97. }
  98. public void TestReflectedType () {
  99. MethodBuilder mb = genClass.DefineMethod (
  100. genMethodName (), 0, typeof (void), new Type [0]);
  101. AssertEquals ("ReflectedType works",
  102. genClass, mb.ReflectedType);
  103. }
  104. public void TestReturnType () {
  105. MethodBuilder mb = genClass.DefineMethod (
  106. genMethodName (), 0, typeof (Console), new Type [0]);
  107. AssertEquals ("ReturnType works", typeof (Console),
  108. mb.ReturnType);
  109. MethodBuilder mb2 = genClass.DefineMethod (
  110. genMethodName (), 0, null, new Type [0]);
  111. Assert ("void ReturnType works", (mb2.ReturnType == null) || (mb2.ReturnType == typeof (void)));
  112. }
  113. public void TestReturnTypeCustomAttributes () {
  114. MethodBuilder mb = genClass.DefineMethod (
  115. genMethodName (), 0, typeof (Console), new Type [0]);
  116. AssertEquals ("ReturnTypeCustomAttributes must be null", null,
  117. mb.ReturnTypeCustomAttributes);
  118. }
  119. /*
  120. public void TestSignature () {
  121. MethodBuilder mb = genClass.DefineMethod (
  122. "m91", 0, typeof (Console), new Type [1] { typeof (Console) });
  123. Console.WriteLine (mb.Signature);
  124. }
  125. */
  126. public void TestCreateMethodBody () {
  127. MethodBuilder mb = genClass.DefineMethod (
  128. genMethodName (), 0, typeof (void), new Type [0]);
  129. // Clear body
  130. mb.CreateMethodBody (null, 999);
  131. // Check arguments 1.
  132. try {
  133. mb.CreateMethodBody (new byte[1], -1);
  134. Fail ();
  135. } catch (ArgumentException) {
  136. }
  137. // Check arguments 2.
  138. try {
  139. mb.CreateMethodBody (new byte[1], 2);
  140. Fail ();
  141. } catch (ArgumentException) {
  142. }
  143. mb.CreateMethodBody (new byte[2], 1);
  144. // Could only be called once
  145. try {
  146. mb.CreateMethodBody (new byte[2], 1);
  147. Fail ();
  148. } catch (InvalidOperationException) {
  149. }
  150. // Can not be called on a created type
  151. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  152. MethodBuilder mb2 = tb.DefineMethod (
  153. genMethodName (), 0, typeof (void), new Type [0]);
  154. ILGenerator ilgen = mb2.GetILGenerator ();
  155. ilgen.Emit (OpCodes.Ret);
  156. tb.CreateType ();
  157. try {
  158. mb2.CreateMethodBody (new byte[2], 1);
  159. Fail ();
  160. } catch (InvalidOperationException) {
  161. }
  162. }
  163. [Test]
  164. [ExpectedException (typeof(InvalidOperationException))]
  165. public void TestDefineParameterInvalidIndexComplete ()
  166. {
  167. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  168. MethodBuilder mb = tb.DefineMethod (
  169. genMethodName (), 0, typeof (void),
  170. new Type[2] {
  171. typeof(int), typeof(int)
  172. });
  173. tb.CreateType ();
  174. mb.DefineParameter (-5, ParameterAttributes.None, "param1");
  175. }
  176. [Test]
  177. [ExpectedException (typeof(InvalidOperationException))]
  178. public void TestDefineParameterValidIndexComplete ()
  179. {
  180. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  181. MethodBuilder mb = tb.DefineMethod (
  182. genMethodName (), 0, typeof (void),
  183. new Type[2] {
  184. typeof(int), typeof(int)
  185. });
  186. tb.CreateType ();
  187. mb.DefineParameter (1, ParameterAttributes.None, "param1");
  188. }
  189. public void TestDefineParameter () {
  190. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  191. MethodBuilder mb = tb.DefineMethod (
  192. genMethodName (), 0, typeof (void),
  193. new Type [2] { typeof(int), typeof(int) });
  194. // index out of range
  195. // This fails on mono because the mono version accepts a 0 index
  196. /*
  197. try {
  198. mb.DefineParameter (0, 0, "param1");
  199. Fail ();
  200. } catch (ArgumentOutOfRangeException) {
  201. }
  202. */
  203. try {
  204. mb.DefineParameter (3, 0, "param1");
  205. Fail ();
  206. } catch (ArgumentOutOfRangeException) {
  207. }
  208. // Normal usage
  209. mb.DefineParameter (1, 0, "param1");
  210. mb.DefineParameter (1, 0, "param1");
  211. mb.DefineParameter (2, 0, null);
  212. // Can not be called on a created type
  213. mb.CreateMethodBody (new byte[2], 0);
  214. tb.CreateType ();
  215. try {
  216. mb.DefineParameter (1, 0, "param1");
  217. Fail ();
  218. }
  219. catch (InvalidOperationException) {
  220. }
  221. }
  222. [Test]
  223. public void TestHashCode ()
  224. {
  225. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  226. string methodName = genMethodName ();
  227. MethodBuilder mb = tb.DefineMethod (
  228. methodName, 0, typeof (void),
  229. new Type[2] {
  230. typeof(int), typeof(int)
  231. });
  232. AssertEquals ("Hashcode of method should be equal to hashcode of method name",
  233. methodName.GetHashCode (), mb.GetHashCode ());
  234. }
  235. public void TestGetBaseDefinition () {
  236. MethodBuilder mb = genClass.DefineMethod (
  237. genMethodName (), 0, typeof (void), new Type [0]);
  238. AssertEquals ("GetBaseDefinition works",
  239. mb.GetBaseDefinition (), mb);
  240. }
  241. public void TestGetILGenerator () {
  242. MethodBuilder mb = genClass.DefineMethod (
  243. genMethodName (), 0, typeof (void), new Type [0]);
  244. // The same instance is returned on the second call
  245. ILGenerator ilgen1 = mb.GetILGenerator ();
  246. ILGenerator ilgen2 = mb.GetILGenerator ();
  247. AssertEquals ("The same ilgen is returned on the second call",
  248. ilgen1, ilgen2);
  249. // Does not work on unmanaged code
  250. MethodBuilder mb2 = genClass.DefineMethod (
  251. genMethodName (), 0, typeof (void), new Type [0]);
  252. try {
  253. mb2.SetImplementationFlags (MethodImplAttributes.Unmanaged);
  254. mb2.GetILGenerator ();
  255. Fail ();
  256. } catch (InvalidOperationException) {
  257. }
  258. try {
  259. mb2.SetImplementationFlags (MethodImplAttributes.Native);
  260. mb2.GetILGenerator ();
  261. Fail ();
  262. } catch (InvalidOperationException) {
  263. }
  264. }
  265. public void TestMethodImplementationFlags () {
  266. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  267. MethodBuilder mb = tb.DefineMethod (
  268. genMethodName (), 0, typeof (void), new Type [0]);
  269. AssertEquals ("MethodImplementationFlags defaults to Managed+IL",
  270. MethodImplAttributes.Managed | MethodImplAttributes.IL,
  271. mb.GetMethodImplementationFlags ());
  272. mb.SetImplementationFlags (MethodImplAttributes.OPTIL);
  273. AssertEquals ("SetImplementationFlags works",
  274. MethodImplAttributes.OPTIL,
  275. mb.GetMethodImplementationFlags ());
  276. // Can not be called on a created type
  277. mb.CreateMethodBody (new byte[2], 0);
  278. mb.SetImplementationFlags (MethodImplAttributes.Managed);
  279. tb.CreateType ();
  280. try {
  281. mb.SetImplementationFlags (MethodImplAttributes.OPTIL);
  282. Fail ();
  283. }
  284. catch (InvalidOperationException) {
  285. }
  286. }
  287. public void TestGetModule () {
  288. MethodBuilder mb = genClass.DefineMethod (
  289. genMethodName (), 0, typeof (void), new Type [0]);
  290. AssertEquals ("GetMethod works", module,
  291. mb.GetModule ());
  292. }
  293. public void TestGetParameters () {
  294. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  295. MethodBuilder mb = tb.DefineMethod (
  296. genMethodName (), 0, typeof (void), new Type [1] {typeof(void)});
  297. /*
  298. * According to the MSDN docs, this method should fail with a
  299. * NotSupportedException. In reality, it throws an
  300. * InvalidOperationException under MS .NET, and returns the
  301. * requested data under mono.
  302. */
  303. /*
  304. try {
  305. mb.GetParameters ();
  306. Fail ("#161");
  307. } catch (InvalidOperationException ex) {
  308. Console.WriteLine (ex);
  309. }
  310. */
  311. }
  312. public void TestGetToken () {
  313. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  314. MethodBuilder mb = tb.DefineMethod (
  315. genMethodName (), 0, typeof (void), new Type [1] {typeof(void)});
  316. mb.GetToken ();
  317. }
  318. public void TestInvoke () {
  319. MethodBuilder mb = genClass.DefineMethod (
  320. genMethodName (), 0, typeof (void),
  321. new Type [1] {typeof(int)});
  322. try {
  323. mb.Invoke (null, new object [1] { 42 });
  324. Fail ();
  325. } catch (NotSupportedException) {
  326. }
  327. try {
  328. mb.Invoke (null, 0, null, new object [1] { 42 }, null);
  329. Fail ();
  330. } catch (NotSupportedException) {
  331. }
  332. }
  333. public void TestIsDefined () {
  334. MethodBuilder mb = genClass.DefineMethod (
  335. genMethodName (), 0, typeof (void),
  336. new Type [1] {typeof(int)});
  337. try {
  338. mb.IsDefined (null, true);
  339. Fail ();
  340. } catch (NotSupportedException) {
  341. }
  342. }
  343. public void TestGetCustomAttributes () {
  344. MethodBuilder mb = genClass.DefineMethod (
  345. genMethodName (), 0, typeof (void),
  346. new Type [1] {typeof(int)});
  347. try {
  348. mb.GetCustomAttributes (true);
  349. Fail ();
  350. } catch (NotSupportedException) {
  351. }
  352. try {
  353. mb.GetCustomAttributes (null, true);
  354. Fail ();
  355. } catch (NotSupportedException) {
  356. }
  357. }
  358. public void TestSetCustomAttribute () {
  359. TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
  360. string name = genMethodName ();
  361. MethodBuilder mb = tb.DefineMethod (
  362. name, MethodAttributes.Public, typeof (void),
  363. new Type [1] {typeof(int)});
  364. // Null argument
  365. try {
  366. mb.SetCustomAttribute (null);
  367. Fail ();
  368. } catch (ArgumentNullException) {
  369. }
  370. byte[] custAttrData = { 1, 0, 0, 0, 0};
  371. Type attrType = Type.GetType
  372. ("System.Reflection.AssemblyKeyNameAttribute");
  373. Type[] paramTypes = new Type[1];
  374. paramTypes[0] = typeof(String);
  375. ConstructorInfo ctorInfo =
  376. attrType.GetConstructor(paramTypes);
  377. mb.SetCustomAttribute (ctorInfo, custAttrData);
  378. // Test MethodImplAttribute
  379. mb.SetCustomAttribute (new CustomAttributeBuilder (typeof (MethodImplAttribute).GetConstructor (new Type[1] { typeof (short) }), new object[1] {(short)MethodImplAttributes.Synchronized}));
  380. mb.GetILGenerator ().Emit (OpCodes.Ret);
  381. Type t = tb.CreateType ();
  382. AssertEquals ("Setting MethodImplAttributes works",
  383. t.GetMethod (name).GetMethodImplementationFlags (),
  384. MethodImplAttributes.Synchronized);
  385. // Null arguments again
  386. try {
  387. mb.SetCustomAttribute (null, new byte[2]);
  388. Fail ();
  389. } catch (ArgumentNullException) {
  390. }
  391. try {
  392. mb.SetCustomAttribute (ctorInfo, null);
  393. Fail ();
  394. } catch (ArgumentNullException) {
  395. }
  396. }
  397. [Test]
  398. [ExpectedException (typeof (InvalidOperationException))]
  399. public void TestAddDeclarativeSecurityAlreadyCreated () {
  400. MethodBuilder mb = genClass.DefineMethod (
  401. genMethodName (), MethodAttributes.Public, typeof (void),
  402. new Type [0]);
  403. ILGenerator ilgen = mb.GetILGenerator ();
  404. ilgen.Emit (OpCodes.Ret);
  405. genClass.CreateType ();
  406. PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
  407. mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
  408. }
  409. [Test]
  410. [ExpectedException (typeof (ArgumentNullException))]
  411. public void TestAddDeclarativeSecurityNullPermissionSet () {
  412. MethodBuilder mb = genClass.DefineMethod (
  413. genMethodName (), MethodAttributes.Public, typeof (void),
  414. new Type [0]);
  415. mb.AddDeclarativeSecurity (SecurityAction.Demand, null);
  416. }
  417. [Test]
  418. public void TestAddDeclarativeSecurityInvalidAction () {
  419. MethodBuilder mb = genClass.DefineMethod (
  420. genMethodName (), MethodAttributes.Public, typeof (void),
  421. new Type [0]);
  422. SecurityAction[] actions = new SecurityAction [] {
  423. SecurityAction.RequestMinimum,
  424. SecurityAction.RequestOptional,
  425. SecurityAction.RequestRefuse };
  426. PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
  427. foreach (SecurityAction action in actions) {
  428. try {
  429. mb.AddDeclarativeSecurity (action, set);
  430. Fail ();
  431. }
  432. catch (ArgumentException) {
  433. }
  434. }
  435. }
  436. [Test]
  437. [ExpectedException (typeof (InvalidOperationException))]
  438. public void TestAddDeclarativeSecurityDuplicateAction () {
  439. MethodBuilder mb = genClass.DefineMethod (
  440. genMethodName (), MethodAttributes.Public, typeof (void),
  441. new Type [0]);
  442. PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
  443. mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
  444. mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
  445. }
  446. [AttributeUsage (AttributeTargets.Parameter)]
  447. class ParamAttribute : Attribute {
  448. public ParamAttribute () {
  449. }
  450. }
  451. [Test]
  452. public void TestDynamicParams () {
  453. string mname = genMethodName ();
  454. MethodBuilder mb = genClass.DefineMethod (
  455. mname, MethodAttributes.Public, typeof (void),
  456. new Type [] { typeof (string) });
  457. ParameterBuilder pb = mb.DefineParameter (1, 0, "foo");
  458. pb.SetCustomAttribute (new CustomAttributeBuilder (typeof (ParamAttribute).GetConstructors () [0], new object [] { }));
  459. mb.GetILGenerator ().Emit (OpCodes.Ret);
  460. Type t = genClass.CreateType ();
  461. MethodInfo m = t.GetMethod (mname);
  462. ParameterInfo pi = m.GetParameters ()[0];
  463. AssertEquals ("foo", pi.Name);
  464. object[] cattrs = pi.GetCustomAttributes (true);
  465. /* This test does not run under MS.NET: */
  466. /*
  467. AssertEquals (1, cattrs.Length);
  468. AssertEquals (typeof (ParamAttribute), cattrs [0].GetType ());
  469. */
  470. }
  471. }
  472. }