2 // ModuleBuilderTest - NUnit Test Cases for the ModuleBuilder class
4 // Zoltan Varga (vargaz@freemail.hu)
6 // (C) Ximian, Inc. http://www.ximian.com
12 using System.Threading;
13 using System.Reflection;
14 using System.Reflection.Emit;
16 using System.Collections;
17 using System.Diagnostics.SymbolStore;
18 using System.Runtime.InteropServices;
20 using NUnit.Framework;
22 namespace MonoTests.System.Reflection.Emit
25 public class ModuleBuilderTest
27 static string tempDir = Path.Combine (Path.GetTempPath (), typeof (ModuleBuilderTest).FullName);
28 static int nameIndex = 0;
33 Random AutoRand = new Random ();
34 string basePath = tempDir;
35 while (Directory.Exists (tempDir))
36 tempDir = Path.Combine (basePath, AutoRand.Next ().ToString ());
37 Directory.CreateDirectory (tempDir);
41 public void TearDown ()
44 // This throws an exception under MS.NET, since the directory contains loaded
46 Directory.Delete (tempDir, true);
51 private AssemblyName genAssemblyName ()
53 AssemblyName assemblyName = new AssemblyName();
54 assemblyName.Name = typeof (ModuleBuilderTest).FullName + (nameIndex ++);
58 private AssemblyBuilder genAssembly ()
60 return Thread.GetDomain ().DefineDynamicAssembly (genAssemblyName (),
61 AssemblyBuilderAccess.RunAndSave,
66 public void TestIsTransient ()
68 AssemblyBuilder ab = genAssembly ();
69 ModuleBuilder mb1 = ab.DefineDynamicModule ("foo.dll");
70 Assert.IsTrue (mb1.IsTransient (), "#1");
71 ModuleBuilder mb2 = ab.DefineDynamicModule ("foo2.dll", "foo2.dll");
72 Assert.IsFalse (mb2.IsTransient (), "#2");
75 // Some of these tests overlap with the tests for Module
78 public void TestGlobalData ()
80 AssemblyBuilder ab = genAssembly ();
82 string resfile = Path.Combine (tempDir, "res");
83 using (StreamWriter sw = new StreamWriter (resfile)) {
87 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
89 mb.DefineInitializedData ("DATA", new byte [100], FieldAttributes.Public);
90 mb.DefineInitializedData ("DATA2", new byte [100], FieldAttributes.Public);
91 mb.DefineInitializedData ("DATA3", new byte [99], FieldAttributes.Public);
92 mb.DefineUninitializedData ("DATA4", 101, FieldAttributes.Public);
93 mb.DefineInitializedData ("DATA_PRIVATE", new byte [100], 0);
94 mb.CreateGlobalFunctions ();
98 Assembly assembly = Assembly.LoadFrom (Path.Combine (tempDir, "foo.dll"));
100 Module module = assembly.GetLoadedModules () [0];
102 string [] expectedFieldNames = new string [] {
103 "DATA", "DATA2", "DATA3", "DATA4" };
104 ArrayList fieldNames = new ArrayList ();
105 foreach (FieldInfo fi in module.GetFields ()) {
106 fieldNames.Add (fi.Name);
108 AssertArrayEqualsSorted (expectedFieldNames, fieldNames.ToArray (typeof (string)));
110 Assert.IsNotNull (module.GetField ("DATA"), "#1");
111 Assert.IsNotNull (module.GetField ("DATA2"), "#2");
112 Assert.IsNotNull (module.GetField ("DATA3"), "#3");
113 Assert.IsNotNull (module.GetField ("DATA4"), "#4");
114 Assert.IsNull (module.GetField ("DATA_PRIVATE"), "#5");
115 Assert.IsNotNull (module.GetField ("DATA_PRIVATE", BindingFlags.NonPublic | BindingFlags.Static), "#6");
119 public void TestGlobalMethods ()
121 AssemblyBuilder builder = genAssembly ();
122 ModuleBuilder module = builder.DefineDynamicModule ("MessageModule");
123 MethodBuilder method = module.DefinePInvokeMethod ("printf", "libc.so",
124 MethodAttributes.PinvokeImpl | MethodAttributes.Static | MethodAttributes.Public,
125 CallingConventions.Standard, typeof (void), new Type [] { typeof (string) }, CallingConvention.Winapi,
127 method.SetImplementationFlags (MethodImplAttributes.PreserveSig |
128 method.GetMethodImplementationFlags ());
130 Assert.IsNull (module.GetMethod ("printf"), "#1");
132 module.CreateGlobalFunctions ();
134 Assert.IsNotNull (module.GetMethod ("printf"), "#2");
138 public void DefineType_Name_Null ()
140 AssemblyBuilder ab = genAssembly ();
141 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
143 mb.DefineType ((string) null);
145 } catch (ArgumentNullException ex) {
146 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
147 Assert.IsNull (ex.InnerException, "#3");
148 Assert.IsNotNull (ex.Message, "#4");
149 Assert.AreEqual ("fullname", ex.ParamName, "#5");
154 public void DefineType_Name_Empty ()
156 AssemblyBuilder ab = genAssembly ();
157 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
159 mb.DefineType (string.Empty);
161 } catch (ArgumentException ex) {
162 // Empty name is not legal
163 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
164 Assert.IsNull (ex.InnerException, "#3");
165 Assert.IsNotNull (ex.Message, "#4");
166 Assert.AreEqual ("fullname", ex.ParamName, "#5");
171 public void DefineType_Name_NullChar ()
173 AssemblyBuilder ab = genAssembly ();
174 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
176 mb.DefineType ("\0test");
178 } catch (ArgumentException ex) {
180 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
181 Assert.IsNull (ex.InnerException, "#3");
182 Assert.IsNotNull (ex.Message, "#4");
183 Assert.AreEqual ("fullname", ex.ParamName, "#5");
186 mb.DefineType ("te\0st");
190 public void DefineType_InterfaceNotAbstract ()
192 AssemblyBuilder ab = genAssembly ();
193 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
196 mb.DefineType ("ITest1", TypeAttributes.Interface);
198 } catch (InvalidOperationException ex) {
199 // Interface must be declared abstract
200 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
201 Assert.IsNull (ex.InnerException, "#A3");
202 Assert.IsNotNull (ex.Message, "#A4");
206 mb.DefineType ("ITest2", TypeAttributes.Interface, (Type) null);
208 } catch (InvalidOperationException ex) {
209 // Interface must be declared abstract
210 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
211 Assert.IsNull (ex.InnerException, "#B3");
212 Assert.IsNotNull (ex.Message, "#B4");
215 // fail on MS .NET 1.1
217 TypeBuilder tb = mb.DefineType ("ITest2", TypeAttributes.Interface,
219 Assert.AreEqual (typeof (object), tb.BaseType, "#C1");
221 tb = mb.DefineType ("ITest3", TypeAttributes.Interface,
222 typeof (IDisposable));
223 Assert.AreEqual (typeof (IDisposable), tb.BaseType, "#D1");
229 [Category ("NotDotNet")] // Parent type was not extensible by the given type
231 public void DefineType_Parent_Interface ()
235 AssemblyBuilder ab = genAssembly ();
236 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
238 tb = mb.DefineType ("Foo", TypeAttributes.Class,
239 typeof (ICollection));
240 Assert.AreEqual (typeof (ICollection), tb.BaseType, "#1");
242 tb = mb.DefineType ("Bar", TypeAttributes.Interface,
243 typeof (ICollection));
244 Assert.AreEqual (typeof (ICollection), tb.BaseType, "#2");
248 [ExpectedException (typeof (ArgumentException))]
249 public void DuplicateTypeName () {
250 AssemblyBuilder ab = genAssembly ();
251 ModuleBuilder module = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
253 var itb = module.DefineType ("TBase", TypeAttributes.Public);
255 itb.SetParent (typeof(ValueType));
257 var ptb = module.DefineType ("TBase", TypeAttributes.Public);
259 ptb.SetParent (typeof(Enum));
263 public void DuplicateSymbolDocument ()
265 AssemblyBuilder ab = genAssembly ();
266 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
268 // Check that it is possible to redefine a symbol document
269 ISymbolDocumentWriter doc1 =
270 mb.DefineDocument ("foo.il", SymDocumentType.Text,
271 SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
272 ISymbolDocumentWriter doc2 =
273 mb.DefineDocument ("foo.il", SymDocumentType.Text,
274 SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
277 [Test] // Test case for #80435.
278 public void GetArrayMethodToStringTest ()
280 AssemblyBuilder assembly = genAssembly ();
281 ModuleBuilder module = assembly.DefineDynamicModule ("m", "test.dll");
283 Type [] myArrayClass = new Type [1];
284 Type [] parameterTypes = { typeof (Array) };
285 MethodInfo myMethodInfo = module.GetArrayMethod (myArrayClass.GetType (), "Sort", CallingConventions.Standard, null, parameterTypes);
287 string str = myMethodInfo.ToString ();
288 Assert.IsNotNull (str);
289 // Don't compare string, since MS returns System.Reflection.Emit.SymbolMethod here
290 // (they do not provide an implementation of ToString).
293 private static void AssertArrayEqualsSorted (Array o1, Array o2)
295 Array s1 = (Array) o1.Clone ();
296 Array s2 = (Array) o2.Clone ();
301 Assert.AreEqual (s1.Length, s2.Length, "#1");
302 for (int i = 0; i < s1.Length; ++i)
303 Assert.AreEqual (s1.GetValue (i), s2.GetValue (i), "#2: " + i);
308 public void ResolveFieldTokenFieldBuilder ()
310 AssemblyBuilder ab = genAssembly ();
311 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
313 TypeBuilder tb = mb.DefineType ("foo");
314 FieldBuilder fb = tb.DefineField ("foo", typeof (int), 0);
317 FieldInfo fi = mb.ResolveField (fb.GetToken ().Token);
318 Assert.IsNotNull (fi);
319 Assert.AreEqual ("foo", fi.Name);
323 [ExpectedException (typeof (ArgumentException))]
324 public void ResolveFieldTokenInvalidToken ()
326 AssemblyBuilder ab = genAssembly ();
327 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
329 mb.ResolveField (0x4001234);
333 public void ResolveMethodTokenMethodBuilder ()
335 AssemblyBuilder ab = genAssembly ();
336 ModuleBuilder moduleb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
338 TypeBuilder tb = moduleb.DefineType ("foo");
339 MethodBuilder mb = tb.DefineMethod("Frub", MethodAttributes.Static, null, new Type[] { typeof(IntPtr) });
340 int tok = mb.GetToken().Token;
341 mb.SetImplementationFlags(MethodImplAttributes.NoInlining);
342 ILGenerator ilgen = mb.GetILGenerator();
343 ilgen.Emit(OpCodes.Ret);
347 MethodBase mi = moduleb.ResolveMethod (tok);
348 Assert.IsNotNull (mi);
349 Assert.AreEqual ("Frub", mi.Name);
354 public void GetTypes ()
356 AssemblyBuilder ab = genAssembly ();
357 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
359 TypeBuilder tb1 = mb.DefineType("Foo", TypeAttributes.Public);
361 Type[] types = mb.GetTypes ();
362 Assert.AreEqual (1, types.Length);
363 Assert.AreEqual (tb1, types [0]);
365 // After the type is created, MS seems to return the created type
368 types = mb.GetTypes ();
369 Assert.AreEqual (tb1.CreateType (), types [0]);
372 [Test] // GetTypeToken (Type)
374 [Category ("NotDotNet")] // http://support.microsoft.com/kb/950986
376 public void GetTypeToken2_Type_Array ()
382 AssemblyName aname = genAssemblyName ();
383 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
384 aname, AssemblyBuilderAccess.RunAndSave);
385 ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
387 type = typeof (object []);
388 typeToken = mb.GetTypeToken (type);
390 Assert.IsFalse (typeToken == TypeToken.Empty, "#A1");
391 resolved_type = mb.ResolveType (typeToken.Token);
392 Assert.AreEqual (type, resolved_type, "#A2");
394 Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#A1");
398 type = typeof (object).MakeArrayType ();
399 typeToken = mb.GetTypeToken (type);
400 Assert.IsFalse (typeToken == TypeToken.Empty, "#B1");
401 resolved_type = mb.ResolveType (typeToken.Token);
402 Assert.AreEqual (type, resolved_type, "#B2");
406 [Test] // GetTypeToken (Type)
407 public void GetTypeToken2_Type_String ()
409 AssemblyName aname = genAssemblyName ();
410 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
411 aname, AssemblyBuilderAccess.RunAndSave);
412 ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
413 Type type = typeof (string);
414 TypeToken typeToken = mb.GetTypeToken (type);
416 Assert.IsFalse (typeToken == TypeToken.Empty, "#1");
417 Type resolved_type = mb.ResolveType (typeToken.Token);
418 Assert.AreEqual (type, resolved_type, "#2");
420 Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#1");
425 [Test] // bug #471302
426 public void ModuleBuilder_ModuleVersionId ()
428 var name = new AssemblyName () { Name = "Foo" };
429 var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
430 name, AssemblyBuilderAccess.Run);
432 var module = assembly.DefineDynamicModule ("Foo");
434 Assert.AreNotEqual (new Guid (), module.ModuleVersionId);
439 public void GetType_String_Null ()
441 AssemblyName an = genAssemblyName ();
442 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
443 ModuleBuilder module = ab.DefineDynamicModule ("GetTypeNullCheck");
446 module.GetType (null);
447 Assert.Fail ("Expected ArgumentNullException for GetType(string)");
449 catch (ArgumentNullException) {
452 module.GetType (null, true); // ignoreCase
453 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool)");
455 catch (ArgumentNullException) {
458 module.GetType (null, true, true); // throwOnError, ignoreCase
459 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool,bool)");
461 catch (ArgumentNullException) {
466 public void GetType_String_Empty ()
468 AssemblyName an = genAssemblyName ();
469 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
470 ModuleBuilder module = ab.DefineDynamicModule ("GetTypeEmptyCheck");
473 module.GetType (String.Empty);
474 Assert.Fail ("Expected ArgumentNullException for GetType(string)");
476 catch (ArgumentException) {
479 module.GetType (String.Empty, true); // ignoreCase
480 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool)");
482 catch (ArgumentException) {
485 module.GetType (String.Empty, true, true); // throwOnError, ignoreCase
486 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool,bool)");
488 catch (ArgumentException) {