ModuleBuilderTest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. public void DuplicateSymbolDocument ()
  195. {
  196. AssemblyBuilder ab = genAssembly ();
  197. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
  198. // Check that it is possible to redefine a symbol document
  199. ISymbolDocumentWriter doc1 =
  200. mb.DefineDocument ("foo.il", SymDocumentType.Text,
  201. SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
  202. ISymbolDocumentWriter doc2 =
  203. mb.DefineDocument ("foo.il", SymDocumentType.Text,
  204. SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
  205. }
  206. [Test] // Test case for #80435.
  207. public void GetArrayMethodToStringTest ()
  208. {
  209. AssemblyBuilder assembly = genAssembly ();
  210. ModuleBuilder module = assembly.DefineDynamicModule ("m", "test.dll");
  211. Type [] myArrayClass = new Type [1];
  212. Type [] parameterTypes = { typeof (Array) };
  213. MethodInfo myMethodInfo = module.GetArrayMethod (myArrayClass.GetType (), "Sort", CallingConventions.Standard, null, parameterTypes);
  214. string str = myMethodInfo.ToString ();
  215. Assert.IsNotNull (str);
  216. // Don't compare string, since MS returns System.Reflection.Emit.SymbolMethod here
  217. // (they do not provide an implementation of ToString).
  218. }
  219. private static void AssertArrayEqualsSorted (Array o1, Array o2)
  220. {
  221. Array s1 = (Array) o1.Clone ();
  222. Array s2 = (Array) o2.Clone ();
  223. Array.Sort (s1);
  224. Array.Sort (s2);
  225. Assert.AreEqual (s1.Length, s2.Length, "#1");
  226. for (int i = 0; i < s1.Length; ++i)
  227. Assert.AreEqual (s1.GetValue (i), s2.GetValue (i), "#2: " + i);
  228. }
  229. #if NET_2_0
  230. [Test]
  231. public void ResolveFieldTokenFieldBuilder ()
  232. {
  233. AssemblyBuilder ab = genAssembly ();
  234. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  235. TypeBuilder tb = mb.DefineType ("foo");
  236. FieldBuilder fb = tb.DefineField ("foo", typeof (int), 0);
  237. tb.CreateType ();
  238. FieldInfo fi = mb.ResolveField (fb.GetToken ().Token);
  239. Assert.IsNotNull (fi);
  240. Assert.AreEqual ("foo", fi.Name);
  241. }
  242. [Test]
  243. [ExpectedException (typeof (ArgumentException))]
  244. public void ResolveFieldTokenInvalidToken ()
  245. {
  246. AssemblyBuilder ab = genAssembly ();
  247. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  248. mb.ResolveField (0x4001234);
  249. }
  250. [Test]
  251. public void ResolveMethodTokenMethodBuilder ()
  252. {
  253. AssemblyBuilder ab = genAssembly ();
  254. ModuleBuilder moduleb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  255. TypeBuilder tb = moduleb.DefineType ("foo");
  256. MethodBuilder mb = tb.DefineMethod("Frub", MethodAttributes.Static, null, new Type[] { typeof(IntPtr) });
  257. int tok = mb.GetToken().Token;
  258. mb.SetImplementationFlags(MethodImplAttributes.NoInlining);
  259. ILGenerator ilgen = mb.GetILGenerator();
  260. ilgen.Emit(OpCodes.Ret);
  261. tb.CreateType ();
  262. MethodBase mi = moduleb.ResolveMethod (tok);
  263. Assert.IsNotNull (mi);
  264. Assert.AreEqual ("Frub", mi.Name);
  265. }
  266. #endif
  267. [Test]
  268. public void GetTypes ()
  269. {
  270. AssemblyBuilder ab = genAssembly ();
  271. ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
  272. TypeBuilder tb1 = mb.DefineType("Foo", TypeAttributes.Public);
  273. Type[] types = mb.GetTypes ();
  274. Assert.AreEqual (1, types.Length);
  275. Assert.AreEqual (tb1, types [0]);
  276. // After the type is created, MS seems to return the created type
  277. tb1.CreateType ();
  278. types = mb.GetTypes ();
  279. Assert.AreEqual (tb1.CreateType (), types [0]);
  280. }
  281. [Test] // GetTypeToken (Type)
  282. #if NET_2_0
  283. [Category ("NotDotNet")] // http://support.microsoft.com/kb/950986
  284. #endif
  285. public void GetTypeToken2_Type_Array ()
  286. {
  287. Type type;
  288. TypeToken typeToken;
  289. Type resolved_type;
  290. AssemblyName aname = genAssemblyName ();
  291. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
  292. aname, AssemblyBuilderAccess.RunAndSave);
  293. ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
  294. type = typeof (object []);
  295. typeToken = mb.GetTypeToken (type);
  296. #if NET_2_0
  297. Assert.IsFalse (typeToken == TypeToken.Empty, "#A1");
  298. resolved_type = mb.ResolveType (typeToken.Token);
  299. Assert.AreEqual (type, resolved_type, "#A2");
  300. #else
  301. Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#A1");
  302. #endif
  303. #if NET_2_0
  304. type = typeof (object).MakeArrayType ();
  305. typeToken = mb.GetTypeToken (type);
  306. Assert.IsFalse (typeToken == TypeToken.Empty, "#B1");
  307. resolved_type = mb.ResolveType (typeToken.Token);
  308. Assert.AreEqual (type, resolved_type, "#B2");
  309. #endif
  310. }
  311. [Test] // GetTypeToken (Type)
  312. public void GetTypeToken2_Type_String ()
  313. {
  314. AssemblyName aname = genAssemblyName ();
  315. AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
  316. aname, AssemblyBuilderAccess.RunAndSave);
  317. ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
  318. Type type = typeof (string);
  319. TypeToken typeToken = mb.GetTypeToken (type);
  320. #if NET_2_0
  321. Assert.IsFalse (typeToken == TypeToken.Empty, "#1");
  322. Type resolved_type = mb.ResolveType (typeToken.Token);
  323. Assert.AreEqual (type, resolved_type, "#2");
  324. #else
  325. Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#1");
  326. #endif
  327. }
  328. }
  329. }