ModuleBuilderTest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. //
  2. // ModuleBuilderTest - NUnit Test Cases for the ModuleBuilder class
  3. //
  4. // Zoltan Varga ([email protected])
  5. //
  6. // (C) Ximian, Inc. http://www.ximian.com
  7. //
  8. //
  9. using System;
  10. using System.Threading;
  11. using System.Reflection;
  12. using System.Reflection.Emit;
  13. using System.IO;
  14. using System.Collections;
  15. using System.Diagnostics.SymbolStore;
  16. using System.Runtime.InteropServices;
  17. using NUnit.Framework;
  18. namespace MonoTests.System.Reflection.Emit
  19. {
  20. [TestFixture]
  21. public class ModuleBuilderTest
  22. {
  23. static string tempDir = Path.Combine (Path.GetTempPath (), typeof (ModuleBuilderTest).FullName);
  24. static int nameIndex = 0;
  25. [SetUp]
  26. public void SetUp ()
  27. {
  28. Random AutoRand = new Random ();
  29. string basePath = tempDir;
  30. while (Directory.Exists (tempDir))
  31. tempDir = Path.Combine (basePath, AutoRand.Next ().ToString ());
  32. Directory.CreateDirectory (tempDir);
  33. }
  34. [TearDown]
  35. public void TearDown ()
  36. {
  37. try {
  38. // This throws an exception under MS.NET, since the directory contains loaded
  39. // assemblies.
  40. Directory.Delete (tempDir, true);
  41. } catch (Exception) {
  42. }
  43. }
  44. private AssemblyName genAssemblyName ()
  45. {
  46. AssemblyName assemblyName = new AssemblyName();
  47. assemblyName.Name = typeof (ModuleBuilderTest).FullName + (nameIndex ++);
  48. return assemblyName;
  49. }
  50. private AssemblyBuilder genAssembly ()
  51. {
  52. return Thread.GetDomain ().DefineDynamicAssembly (genAssemblyName (),
  53. AssemblyBuilderAccess.RunAndSave,
  54. tempDir);
  55. }
  56. [Test]
  57. public void TestIsTransient ()
  58. {
  59. AssemblyBuilder ab = genAssembly ();
  60. ModuleBuilder mb1 = ab.DefineDynamicModule ("foo.dll");
  61. Assert.IsTrue (mb1.IsTransient (), "#1");
  62. ModuleBuilder mb2 = ab.DefineDynamicModule ("foo2.dll", "foo2.dll");
  63. Assert.IsFalse (mb2.IsTransient (), "#2");
  64. }
  65. // Some of these tests overlap with the tests for Module
  66. [Test]
  67. public void TestGlobalData ()
  68. {
  69. AssemblyBuilder ab = genAssembly ();
  70. string resfile = Path.Combine (tempDir, "res");
  71. using (StreamWriter sw = new StreamWriter (resfile)) {
  72. sw.WriteLine ("FOO");
  73. }
  74. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  75. mb.DefineInitializedData ("DATA", new byte [100], FieldAttributes.Public);
  76. mb.DefineInitializedData ("DATA2", new byte [100], FieldAttributes.Public);
  77. mb.DefineInitializedData ("DATA3", new byte [99], FieldAttributes.Public);
  78. mb.DefineUninitializedData ("DATA4", 101, FieldAttributes.Public);
  79. mb.DefineInitializedData ("DATA_PRIVATE", new byte [100], 0);
  80. mb.CreateGlobalFunctions ();
  81. ab.Save ("foo.dll");
  82. Assembly assembly = Assembly.LoadFrom (Path.Combine (tempDir, "foo.dll"));
  83. Module module = assembly.GetLoadedModules () [0];
  84. string [] expectedFieldNames = new string [] {
  85. "DATA", "DATA2", "DATA3", "DATA4" };
  86. ArrayList fieldNames = new ArrayList ();
  87. foreach (FieldInfo fi in module.GetFields ()) {
  88. fieldNames.Add (fi.Name);
  89. }
  90. AssertArrayEqualsSorted (expectedFieldNames, fieldNames.ToArray (typeof (string)));
  91. Assert.IsNotNull (module.GetField ("DATA"), "#1");
  92. Assert.IsNotNull (module.GetField ("DATA2"), "#2");
  93. Assert.IsNotNull (module.GetField ("DATA3"), "#3");
  94. Assert.IsNotNull (module.GetField ("DATA4"), "#4");
  95. Assert.IsNull (module.GetField ("DATA_PRIVATE"), "#5");
  96. Assert.IsNotNull (module.GetField ("DATA_PRIVATE", BindingFlags.NonPublic | BindingFlags.Static), "#6");
  97. }
  98. [Test]
  99. public void TestGlobalMethods ()
  100. {
  101. AssemblyBuilder builder = genAssembly ();
  102. ModuleBuilder module = builder.DefineDynamicModule ("MessageModule");
  103. MethodBuilder method = module.DefinePInvokeMethod ("printf", "libc.so",
  104. MethodAttributes.PinvokeImpl | MethodAttributes.Static | MethodAttributes.Public,
  105. CallingConventions.Standard, typeof (void), new Type [] { typeof (string) }, CallingConvention.Winapi,
  106. CharSet.Auto);
  107. method.SetImplementationFlags (MethodImplAttributes.PreserveSig |
  108. method.GetMethodImplementationFlags ());
  109. module.CreateGlobalFunctions ();
  110. Assert.IsNotNull (module.GetMethod ("printf"));
  111. }
  112. [Test]
  113. public void DefineType_Name_Null ()
  114. {
  115. AssemblyBuilder ab = genAssembly ();
  116. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  117. try {
  118. mb.DefineType ((string) null);
  119. Assert.Fail ("#1");
  120. } catch (ArgumentNullException ex) {
  121. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  122. Assert.IsNull (ex.InnerException, "#3");
  123. Assert.IsNotNull (ex.Message, "#4");
  124. Assert.AreEqual ("fullname", ex.ParamName, "#5");
  125. }
  126. }
  127. [Test]
  128. public void DefineType_Name_Empty ()
  129. {
  130. AssemblyBuilder ab = genAssembly ();
  131. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  132. try {
  133. mb.DefineType (string.Empty);
  134. Assert.Fail ("#1");
  135. } catch (ArgumentException ex) {
  136. // Empty name is not legal
  137. Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
  138. Assert.IsNull (ex.InnerException, "#3");
  139. Assert.IsNotNull (ex.Message, "#4");
  140. Assert.AreEqual ("fullname", ex.ParamName, "#5");
  141. }
  142. }
  143. [Test]
  144. public void DefineType_Name_NullChar ()
  145. {
  146. AssemblyBuilder ab = genAssembly ();
  147. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  148. try {
  149. mb.DefineType ("\0test");
  150. Assert.Fail ("#1");
  151. } catch (ArgumentException ex) {
  152. // Illegal name
  153. Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
  154. Assert.IsNull (ex.InnerException, "#3");
  155. Assert.IsNotNull (ex.Message, "#4");
  156. Assert.AreEqual ("fullname", ex.ParamName, "#5");
  157. }
  158. mb.DefineType ("te\0st");
  159. }
  160. [Test]
  161. public void DefineType_InterfaceNotAbstract ()
  162. {
  163. AssemblyBuilder ab = genAssembly ();
  164. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  165. try {
  166. mb.DefineType ("ITest1", TypeAttributes.Interface);
  167. Assert.Fail ("#A1");
  168. } catch (InvalidOperationException ex) {
  169. // Interface must be declared abstract
  170. Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
  171. Assert.IsNull (ex.InnerException, "#A3");
  172. Assert.IsNotNull (ex.Message, "#A4");
  173. }
  174. try {
  175. mb.DefineType ("ITest2", TypeAttributes.Interface, (Type) null);
  176. Assert.Fail ("#B1");
  177. } catch (InvalidOperationException ex) {
  178. // Interface must be declared abstract
  179. Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
  180. Assert.IsNull (ex.InnerException, "#B3");
  181. Assert.IsNotNull (ex.Message, "#B4");
  182. }
  183. // fail on MS .NET 1.1
  184. #if NET_2_0
  185. TypeBuilder tb = mb.DefineType ("ITest2", TypeAttributes.Interface,
  186. typeof (object));
  187. Assert.AreEqual (typeof (object), tb.BaseType, "#C1");
  188. tb = mb.DefineType ("ITest3", TypeAttributes.Interface,
  189. typeof (IDisposable));
  190. Assert.AreEqual (typeof (IDisposable), tb.BaseType, "#D1");
  191. #endif
  192. }
  193. [Test]
  194. #if ONLY_1_1
  195. [Category ("NotDotNet")] // Parent type was not extensible by the given type
  196. #endif
  197. public void DefineType_Parent_Interface ()
  198. {
  199. TypeBuilder tb;
  200. AssemblyBuilder ab = genAssembly ();
  201. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  202. tb = mb.DefineType ("Foo", TypeAttributes.Class,
  203. typeof (ICollection));
  204. Assert.AreEqual (typeof (ICollection), tb.BaseType, "#1");
  205. tb = mb.DefineType ("Bar", TypeAttributes.Interface,
  206. typeof (ICollection));
  207. Assert.AreEqual (typeof (ICollection), tb.BaseType, "#2");
  208. }
  209. [Test]
  210. public void DuplicateSymbolDocument ()
  211. {
  212. AssemblyBuilder ab = genAssembly ();
  213. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  214. // Check that it is possible to redefine a symbol document
  215. ISymbolDocumentWriter doc1 =
  216. mb.DefineDocument ("foo.il", SymDocumentType.Text,
  217. SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
  218. ISymbolDocumentWriter doc2 =
  219. mb.DefineDocument ("foo.il", SymDocumentType.Text,
  220. SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
  221. }
  222. [Test] // Test case for #80435.
  223. public void GetArrayMethodToStringTest ()
  224. {
  225. AssemblyBuilder assembly = genAssembly ();
  226. ModuleBuilder module = assembly.DefineDynamicModule ("m", "test.dll");
  227. Type [] myArrayClass = new Type [1];
  228. Type [] parameterTypes = { typeof (Array) };
  229. MethodInfo myMethodInfo = module.GetArrayMethod (myArrayClass.GetType (), "Sort", CallingConventions.Standard, null, parameterTypes);
  230. string str = myMethodInfo.ToString ();
  231. Assert.IsNotNull (str);
  232. // Don't compare string, since MS returns System.Reflection.Emit.SymbolMethod here
  233. // (they do not provide an implementation of ToString).
  234. }
  235. private static void AssertArrayEqualsSorted (Array o1, Array o2)
  236. {
  237. Array s1 = (Array) o1.Clone ();
  238. Array s2 = (Array) o2.Clone ();
  239. Array.Sort (s1);
  240. Array.Sort (s2);
  241. Assert.AreEqual (s1.Length, s2.Length, "#1");
  242. for (int i = 0; i < s1.Length; ++i)
  243. Assert.AreEqual (s1.GetValue (i), s2.GetValue (i), "#2: " + i);
  244. }
  245. #if NET_2_0
  246. [Test]
  247. public void ResolveFieldTokenFieldBuilder ()
  248. {
  249. AssemblyBuilder ab = genAssembly ();
  250. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  251. TypeBuilder tb = mb.DefineType ("foo");
  252. FieldBuilder fb = tb.DefineField ("foo", typeof (int), 0);
  253. tb.CreateType ();
  254. FieldInfo fi = mb.ResolveField (fb.GetToken ().Token);
  255. Assert.IsNotNull (fi);
  256. Assert.AreEqual ("foo", fi.Name);
  257. }
  258. [Test]
  259. [ExpectedException (typeof (ArgumentException))]
  260. public void ResolveFieldTokenInvalidToken ()
  261. {
  262. AssemblyBuilder ab = genAssembly ();
  263. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  264. mb.ResolveField (0x4001234);
  265. }
  266. [Test]
  267. public void ResolveMethodTokenMethodBuilder ()
  268. {
  269. AssemblyBuilder ab = genAssembly ();
  270. ModuleBuilder moduleb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  271. TypeBuilder tb = moduleb.DefineType ("foo");
  272. MethodBuilder mb = tb.DefineMethod("Frub", MethodAttributes.Static, null, new Type[] { typeof(IntPtr) });
  273. int tok = mb.GetToken().Token;
  274. mb.SetImplementationFlags(MethodImplAttributes.NoInlining);
  275. ILGenerator ilgen = mb.GetILGenerator();
  276. ilgen.Emit(OpCodes.Ret);
  277. tb.CreateType ();
  278. MethodBase mi = moduleb.ResolveMethod (tok);
  279. Assert.IsNotNull (mi);
  280. Assert.AreEqual ("Frub", mi.Name);
  281. }
  282. #endif
  283. [Test]
  284. public void GetTypes ()
  285. {
  286. AssemblyBuilder ab = genAssembly ();
  287. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  288. TypeBuilder tb1 = mb.DefineType("Foo", TypeAttributes.Public);
  289. Type[] types = mb.GetTypes ();
  290. Assert.AreEqual (1, types.Length);
  291. Assert.AreEqual (tb1, types [0]);
  292. // After the type is created, MS seems to return the created type
  293. tb1.CreateType ();
  294. types = mb.GetTypes ();
  295. Assert.AreEqual (tb1.CreateType (), types [0]);
  296. }
  297. [Test] // GetTypeToken (Type)
  298. #if NET_2_0
  299. [Category ("NotDotNet")] // http://support.microsoft.com/kb/950986
  300. #endif
  301. public void GetTypeToken2_Type_Array ()
  302. {
  303. Type type;
  304. TypeToken typeToken;
  305. Type resolved_type;
  306. AssemblyName aname = genAssemblyName ();
  307. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
  308. aname, AssemblyBuilderAccess.RunAndSave);
  309. ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
  310. type = typeof (object []);
  311. typeToken = mb.GetTypeToken (type);
  312. #if NET_2_0
  313. Assert.IsFalse (typeToken == TypeToken.Empty, "#A1");
  314. resolved_type = mb.ResolveType (typeToken.Token);
  315. Assert.AreEqual (type, resolved_type, "#A2");
  316. #else
  317. Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#A1");
  318. #endif
  319. #if NET_2_0
  320. type = typeof (object).MakeArrayType ();
  321. typeToken = mb.GetTypeToken (type);
  322. Assert.IsFalse (typeToken == TypeToken.Empty, "#B1");
  323. resolved_type = mb.ResolveType (typeToken.Token);
  324. Assert.AreEqual (type, resolved_type, "#B2");
  325. #endif
  326. }
  327. [Test] // GetTypeToken (Type)
  328. public void GetTypeToken2_Type_String ()
  329. {
  330. AssemblyName aname = genAssemblyName ();
  331. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
  332. aname, AssemblyBuilderAccess.RunAndSave);
  333. ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
  334. Type type = typeof (string);
  335. TypeToken typeToken = mb.GetTypeToken (type);
  336. #if NET_2_0
  337. Assert.IsFalse (typeToken == TypeToken.Empty, "#1");
  338. Type resolved_type = mb.ResolveType (typeToken.Token);
  339. Assert.AreEqual (type, resolved_type, "#2");
  340. #else
  341. Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#1");
  342. #endif
  343. }
  344. #if NET_2_0
  345. [Test] // bug #471302
  346. public void ModuleBuilder_ModuleVersionId ()
  347. {
  348. var name = new AssemblyName () { Name = "Foo" };
  349. var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
  350. name, AssemblyBuilderAccess.Run);
  351. var module = assembly.DefineDynamicModule ("Foo");
  352. Assert.AreNotEqual (new Guid (), module.ModuleVersionId);
  353. }
  354. #endif
  355. [Test]
  356. public void GetType_String_Null ()
  357. {
  358. AssemblyName an = genAssemblyName ();
  359. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
  360. ModuleBuilder module = ab.DefineDynamicModule ("GetTypeNullCheck");
  361. try {
  362. module.GetType (null);
  363. Assert.Fail ("Expected ArgumentNullException for GetType(string)");
  364. }
  365. catch (ArgumentNullException) {
  366. }
  367. try {
  368. module.GetType (null, true); // ignoreCase
  369. Assert.Fail ("Expected ArgumentNullException for GetType(string,bool)");
  370. }
  371. catch (ArgumentNullException) {
  372. }
  373. try {
  374. module.GetType (null, true, true); // throwOnError, ignoreCase
  375. Assert.Fail ("Expected ArgumentNullException for GetType(string,bool,bool)");
  376. }
  377. catch (ArgumentNullException) {
  378. }
  379. }
  380. [Test]
  381. public void GetType_String_Empty ()
  382. {
  383. AssemblyName an = genAssemblyName ();
  384. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
  385. ModuleBuilder module = ab.DefineDynamicModule ("GetTypeEmptyCheck");
  386. try {
  387. module.GetType (String.Empty);
  388. Assert.Fail ("Expected ArgumentNullException for GetType(string)");
  389. }
  390. catch (ArgumentException) {
  391. }
  392. try {
  393. module.GetType (String.Empty, true); // ignoreCase
  394. Assert.Fail ("Expected ArgumentNullException for GetType(string,bool)");
  395. }
  396. catch (ArgumentException) {
  397. }
  398. try {
  399. module.GetType (String.Empty, true, true); // throwOnError, ignoreCase
  400. Assert.Fail ("Expected ArgumentNullException for GetType(string,bool,bool)");
  401. }
  402. catch (ArgumentException) {
  403. }
  404. }
  405. }
  406. }