[Test] Add test for ModuleBuilder.ResolveFieldToken on generic fields.
[mono.git] / mcs / class / corlib / Test / System.Reflection.Emit / ModuleBuilderTest.cs
1 //
2 // ModuleBuilderTest - NUnit Test Cases for the ModuleBuilder class
3 //
4 // Zoltan Varga (vargaz@freemail.hu)
5 //
6 // (C) Ximian, Inc.  http://www.ximian.com
7 //
8 //
9
10
11 using System;
12 using System.Threading;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.IO;
16 using System.Collections;
17 using System.Diagnostics.SymbolStore;
18 using System.Runtime.InteropServices;
19
20 using NUnit.Framework;
21
22 namespace MonoTests.System.Reflection.Emit
23 {
24         [TestFixture]
25         public class ModuleBuilderTest
26         {
27                 static string tempDir = Path.Combine (Path.GetTempPath (), typeof (ModuleBuilderTest).FullName);
28                 static int nameIndex = 0;
29
30                 [SetUp]
31                 public void SetUp ()
32                 {
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);
38                 }
39
40                 [TearDown]
41                 public void TearDown ()
42                 {
43                         try {
44                                 // This throws an exception under MS.NET, since the directory contains loaded
45                                 // assemblies.
46                                 Directory.Delete (tempDir, true);
47                         } catch (Exception) {
48                         }
49                 }
50
51                 private AssemblyName genAssemblyName ()
52                 {
53                         AssemblyName assemblyName = new AssemblyName();
54                         assemblyName.Name = typeof (ModuleBuilderTest).FullName + (nameIndex ++);
55                         return assemblyName;
56                 }
57
58                 private AssemblyBuilder genAssembly ()
59                 {
60                         return Thread.GetDomain ().DefineDynamicAssembly (genAssemblyName (),
61                                                                                                                           AssemblyBuilderAccess.RunAndSave,
62                                                                                                                           tempDir);
63                 }
64
65                 [Test]
66                 public void TestIsTransient ()
67                 {
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");
73                 }
74
75                 // Some of these tests overlap with the tests for Module
76
77                 [Test]
78                 public void TestGlobalData ()
79                 {
80                         AssemblyBuilder ab = genAssembly ();
81
82                         string resfile = Path.Combine (tempDir, "res");
83                         using (StreamWriter sw = new StreamWriter (resfile)) {
84                                 sw.WriteLine ("FOO");
85                         }
86
87                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
88
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 ();
95
96                         ab.Save ("foo.dll");
97
98                         Assembly assembly = Assembly.LoadFrom (Path.Combine (tempDir, "foo.dll"));
99
100                         Module module = assembly.GetLoadedModules () [0];
101
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);
107                         }
108                         AssertArrayEqualsSorted (expectedFieldNames, fieldNames.ToArray (typeof (string)));
109
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");
116                 }
117
118                 [Test]
119                 [Category("NotWorking")]
120                 public void TestGlobalMethods ()
121                 {
122                         AssemblyBuilder builder = genAssembly ();
123                         ModuleBuilder module = builder.DefineDynamicModule ("MessageModule");
124                         MethodBuilder method = module.DefinePInvokeMethod ("printf", "libc.so",
125                                                                                                                           MethodAttributes.PinvokeImpl | MethodAttributes.Static | MethodAttributes.Public,
126                                                                                                                           CallingConventions.Standard, typeof (void), new Type [] { typeof (string) }, CallingConvention.Winapi,
127                                                                                                                           CharSet.Auto);
128                         method.SetImplementationFlags (MethodImplAttributes.PreserveSig |
129                                                                                    method.GetMethodImplementationFlags ());
130
131                         Assert.IsNull (module.GetMethod ("printf"), "#1");
132
133                         module.CreateGlobalFunctions ();
134
135                         Assert.IsNotNull (module.GetMethod ("printf"), "#2");
136                 }
137
138                 [Test]
139                 public void DefineType_Name_Null ()
140                 {
141                         AssemblyBuilder ab = genAssembly ();
142                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
143                         try {
144                                 mb.DefineType ((string) null);
145                                 Assert.Fail ("#1");
146                         } catch (ArgumentNullException ex) {
147                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
148                                 Assert.IsNull (ex.InnerException, "#3");
149                                 Assert.IsNotNull (ex.Message, "#4");
150                                 Assert.AreEqual ("fullname", ex.ParamName, "#5");
151                         }
152                 }
153
154                 [Test]
155                 public void DefineType_Name_Empty ()
156                 {
157                         AssemblyBuilder ab = genAssembly ();
158                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
159                         try {
160                                 mb.DefineType (string.Empty);
161                                 Assert.Fail ("#1");
162                         } catch (ArgumentException ex) {
163                                 // Empty name is not legal
164                                 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
165                                 Assert.IsNull (ex.InnerException, "#3");
166                                 Assert.IsNotNull (ex.Message, "#4");
167                                 Assert.AreEqual ("fullname", ex.ParamName, "#5");
168                         }
169                 }
170
171                 [Test]
172                 public void DefineType_Name_NullChar ()
173                 {
174                         AssemblyBuilder ab = genAssembly ();
175                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
176                         try {
177                                 mb.DefineType ("\0test");
178                                 Assert.Fail ("#1");
179                         } catch (ArgumentException ex) {
180                                 // Illegal name
181                                 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
182                                 Assert.IsNull (ex.InnerException, "#3");
183                                 Assert.IsNotNull (ex.Message, "#4");
184                                 Assert.AreEqual ("fullname", ex.ParamName, "#5");
185                         }
186
187                         mb.DefineType ("te\0st");
188                 }
189
190                 [Test]
191                 public void DefineType_InterfaceNotAbstract ()
192                 {
193                         AssemblyBuilder ab = genAssembly ();
194                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
195
196                         try {
197                                 mb.DefineType ("ITest1", TypeAttributes.Interface);
198                                 Assert.Fail ("#A1");
199                         } catch (InvalidOperationException ex) {
200                                 // Interface must be declared abstract
201                                 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
202                                 Assert.IsNull (ex.InnerException, "#A3");
203                                 Assert.IsNotNull (ex.Message, "#A4");
204                         }
205
206                         try {
207                                 mb.DefineType ("ITest2", TypeAttributes.Interface, (Type) null);
208                                 Assert.Fail ("#B1");
209                         } catch (InvalidOperationException ex) {
210                                 // Interface must be declared abstract
211                                 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
212                                 Assert.IsNull (ex.InnerException, "#B3");
213                                 Assert.IsNotNull (ex.Message, "#B4");
214                         }
215
216                         // fail on MS .NET 1.1
217 #if NET_2_0
218                         TypeBuilder tb = mb.DefineType ("ITest2", TypeAttributes.Interface,
219                                 typeof (object));
220                         Assert.AreEqual (typeof (object), tb.BaseType, "#C1");
221
222                         tb = mb.DefineType ("ITest3", TypeAttributes.Interface,
223                                 typeof (IDisposable));
224                         Assert.AreEqual (typeof (IDisposable), tb.BaseType, "#D1");
225 #endif
226                 }
227
228                 [Test]
229 #if ONLY_1_1
230                 [Category ("NotDotNet")] // Parent type was not extensible by the given type
231 #endif
232                 public void DefineType_Parent_Interface ()
233                 {
234                         TypeBuilder tb;
235
236                         AssemblyBuilder ab = genAssembly ();
237                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
238
239                         tb = mb.DefineType ("Foo", TypeAttributes.Class,
240                                 typeof (ICollection));
241                         Assert.AreEqual (typeof (ICollection), tb.BaseType, "#1");
242
243                         tb = mb.DefineType ("Bar", TypeAttributes.Interface,
244                                 typeof (ICollection));
245                         Assert.AreEqual (typeof (ICollection), tb.BaseType, "#2");
246                 }
247
248                 [Test]
249                 [ExpectedException (typeof (ArgumentException))]
250                 public void DuplicateTypeName () {
251                         AssemblyBuilder ab = genAssembly ();
252                         ModuleBuilder module = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
253
254                         var itb = module.DefineType ("TBase", TypeAttributes.Public);
255
256                         itb.SetParent (typeof(ValueType));        
257
258                         var ptb = module.DefineType ("TBase", TypeAttributes.Public);
259
260                         ptb.SetParent (typeof(Enum));
261                 }
262
263                 [Test]
264                 public void DuplicateSymbolDocument ()
265                 {
266                         AssemblyBuilder ab = genAssembly ();
267                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
268
269                         // Check that it is possible to redefine a symbol document
270                         ISymbolDocumentWriter doc1 =
271                                 mb.DefineDocument ("foo.il", SymDocumentType.Text,
272                                                                   SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
273                         ISymbolDocumentWriter doc2 =
274                                 mb.DefineDocument ("foo.il", SymDocumentType.Text,
275                                                                   SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
276                 }
277
278                 [Test] // Test case for #80435.
279                 public void GetArrayMethodToStringTest ()
280                 {
281                         AssemblyBuilder assembly = genAssembly ();
282                         ModuleBuilder module = assembly.DefineDynamicModule ("m", "test.dll");
283
284                         Type [] myArrayClass = new Type [1];
285                         Type [] parameterTypes = { typeof (Array) };
286                         MethodInfo myMethodInfo = module.GetArrayMethod (myArrayClass.GetType (), "Sort", CallingConventions.Standard, null, parameterTypes);
287
288                         string str = myMethodInfo.ToString ();
289                         Assert.IsNotNull (str);
290                         // Don't compare string, since MS returns System.Reflection.Emit.SymbolMethod here 
291                         // (they do not provide an implementation of ToString).
292                 }
293
294                 private static void AssertArrayEqualsSorted (Array o1, Array o2)
295                 {
296                         Array s1 = (Array) o1.Clone ();
297                         Array s2 = (Array) o2.Clone ();
298
299                         Array.Sort (s1);
300                         Array.Sort (s2);
301
302                         Assert.AreEqual (s1.Length, s2.Length, "#1");
303                         for (int i = 0; i < s1.Length; ++i)
304                                 Assert.AreEqual (s1.GetValue (i), s2.GetValue (i), "#2: " + i);
305                 }
306
307 #if NET_2_0
308                 [Test]
309                 public void ResolveFieldTokenFieldBuilder ()
310                 {
311                         AssemblyBuilder ab = genAssembly ();
312                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
313
314                         TypeBuilder tb = mb.DefineType ("foo");
315                         FieldBuilder fb = tb.DefineField ("foo", typeof (int), 0);
316                         tb.CreateType ();
317
318                         FieldInfo fi = mb.ResolveField (0x04000001);
319                         Assert.IsNotNull (fi);
320                         Assert.AreEqual ("foo", fi.Name);
321                 }
322
323                 [Test]
324                 public void ResolveGenericFieldBuilderOnGenericTypeBuilder ()
325                 {
326                         AssemblyBuilder ab = genAssembly ();
327                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
328
329                         TypeBuilder tb = mb.DefineType ("Foo`1");
330                         var t = tb.DefineGenericParameters ("T") [0];
331                         FieldBuilder fb = tb.DefineField ("foo", t, 0);
332                         tb.CreateType ();
333
334                         FieldInfo fi = mb.ResolveField (fb.GetToken ().Token);
335                         Assert.IsNotNull (fi);
336                         Assert.AreEqual ("foo", fi.Name);
337                 }
338
339                 [Test]
340                 [ExpectedException (typeof (ArgumentException))]
341                 public void ResolveFieldTokenInvalidToken ()
342                 {
343                         AssemblyBuilder ab = genAssembly ();
344                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
345
346                         mb.ResolveField (0x4001234);
347                 }
348
349                 [Test]
350                 public void ResolveMethodTokenMethodBuilder ()
351                 {
352                         AssemblyBuilder ab = genAssembly ();
353                         ModuleBuilder moduleb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
354
355                         TypeBuilder tb = moduleb.DefineType ("foo");
356                         MethodBuilder mb = tb.DefineMethod("Frub", MethodAttributes.Static, null, new Type[] { typeof(IntPtr) });
357                         int tok = mb.GetToken().Token;
358                         mb.SetImplementationFlags(MethodImplAttributes.NoInlining);
359                         ILGenerator ilgen = mb.GetILGenerator();
360                         ilgen.Emit(OpCodes.Ret);
361
362                         tb.CreateType ();
363
364                         MethodBase mi = moduleb.ResolveMethod (tok);
365                         Assert.IsNotNull (mi);
366                         Assert.AreEqual ("Frub", mi.Name);
367                 }
368 #endif
369
370                 [Test]
371                 public void GetTypes ()
372                 {
373                         AssemblyBuilder ab = genAssembly ();
374                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
375
376                         TypeBuilder tb1 = mb.DefineType("Foo", TypeAttributes.Public);
377
378                         Type[] types = mb.GetTypes ();
379                         Assert.AreEqual (1, types.Length);
380                         Assert.AreEqual (tb1, types [0]);
381
382                         // After the type is created, MS seems to return the created type
383                         tb1.CreateType ();
384
385                         types = mb.GetTypes ();
386                         Assert.AreEqual (tb1.CreateType (), types [0]);
387                 }
388
389                 [Test] // GetTypeToken (Type)
390 #if NET_2_0
391                 [Category ("NotDotNet")] // http://support.microsoft.com/kb/950986
392 #endif
393                 public void GetTypeToken2_Type_Array ()
394                 {
395                         Type type;
396                         TypeToken typeToken;
397                         Type resolved_type;
398
399                         AssemblyName aname = genAssemblyName ();
400                         AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
401                                 aname, AssemblyBuilderAccess.RunAndSave);
402                         ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
403
404                         type = typeof (object []);
405                         typeToken = mb.GetTypeToken (type);
406 #if NET_2_0
407                         Assert.IsFalse (typeToken == TypeToken.Empty, "#A1");
408                         resolved_type = mb.ResolveType (typeToken.Token);
409                         Assert.AreEqual (type, resolved_type, "#A2");
410 #else
411                         Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#A1");
412 #endif
413
414 #if NET_2_0
415                         type = typeof (object).MakeArrayType ();
416                         typeToken = mb.GetTypeToken (type);
417                         Assert.IsFalse (typeToken == TypeToken.Empty, "#B1");
418                         resolved_type = mb.ResolveType (typeToken.Token);
419                         Assert.AreEqual (type, resolved_type, "#B2");
420 #endif
421                 }
422
423                 [Test] // GetTypeToken (Type)
424                 public void GetTypeToken2_Type_String ()
425                 {
426                         AssemblyName aname = genAssemblyName ();
427                         AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
428                                 aname, AssemblyBuilderAccess.RunAndSave);
429                         ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
430                         Type type = typeof (string);
431                         TypeToken typeToken = mb.GetTypeToken (type);
432 #if NET_2_0
433                         Assert.IsFalse (typeToken == TypeToken.Empty, "#1");
434                         Type resolved_type = mb.ResolveType (typeToken.Token);
435                         Assert.AreEqual (type, resolved_type, "#2");
436 #else
437                         Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#1");
438 #endif
439                 }
440
441 #if NET_2_0
442                 [Test] // bug #471302
443                 public void ModuleBuilder_ModuleVersionId ()
444                 {
445                         var name = new AssemblyName () { Name = "Foo" };
446                         var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
447                                 name, AssemblyBuilderAccess.Run);
448
449                         var module = assembly.DefineDynamicModule ("Foo");
450
451                         Assert.AreNotEqual (new Guid (), module.ModuleVersionId);
452                 }
453 #endif
454
455                 [Test]
456                 public void GetType_String_Null ()
457                 {
458                         AssemblyName an = genAssemblyName ();
459                         AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
460                         ModuleBuilder module = ab.DefineDynamicModule ("GetTypeNullCheck");
461
462                         try {
463                                 module.GetType (null);
464                                 Assert.Fail ("Expected ArgumentNullException for GetType(string)");
465                         }
466                         catch (ArgumentNullException) {
467                         }
468                         try {
469                                 module.GetType (null, true); // ignoreCase
470                                 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool)");
471                         }
472                         catch (ArgumentNullException) {
473                         }
474                         try {
475                                 module.GetType (null, true, true); // throwOnError, ignoreCase
476                                 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool,bool)");
477                         }
478                         catch (ArgumentNullException) {
479                         }
480                 }
481
482                 [Test]
483                 public void GetType_String_Empty ()
484                 {
485                         AssemblyName an = genAssemblyName ();
486                         AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
487                         ModuleBuilder module = ab.DefineDynamicModule ("GetTypeEmptyCheck");
488
489                         try {
490                                 module.GetType (String.Empty);
491                                 Assert.Fail ("Expected ArgumentNullException for GetType(string)");
492                         }
493                         catch (ArgumentException) {
494                         }
495                         try {
496                                 module.GetType (String.Empty, true); // ignoreCase
497                                 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool)");
498                         }
499                         catch (ArgumentException) {
500                         }
501                         try {
502                                 module.GetType (String.Empty, true, true); // throwOnError, ignoreCase
503                                 Assert.Fail ("Expected ArgumentNullException for GetType(string,bool,bool)");
504                         }
505                         catch (ArgumentException) {
506                         }
507                 }
508         }
509 }