2009-05-27 Zoltan Varga <vargaz@gmail.com>
[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                 public void TestGlobalMethods ()
120                 {
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,
126                                                                                                                           CharSet.Auto);
127                         method.SetImplementationFlags (MethodImplAttributes.PreserveSig |
128                                                                                    method.GetMethodImplementationFlags ());
129                         module.CreateGlobalFunctions ();
130
131                         Assert.IsNotNull (module.GetMethod ("printf"));
132                 }
133
134                 [Test]
135                 public void DefineType_Name_Null ()
136                 {
137                         AssemblyBuilder ab = genAssembly ();
138                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
139                         try {
140                                 mb.DefineType ((string) null);
141                                 Assert.Fail ("#1");
142                         } catch (ArgumentNullException ex) {
143                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
144                                 Assert.IsNull (ex.InnerException, "#3");
145                                 Assert.IsNotNull (ex.Message, "#4");
146                                 Assert.AreEqual ("fullname", ex.ParamName, "#5");
147                         }
148                 }
149
150                 [Test]
151                 public void DefineType_Name_Empty ()
152                 {
153                         AssemblyBuilder ab = genAssembly ();
154                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
155                         try {
156                                 mb.DefineType (string.Empty);
157                                 Assert.Fail ("#1");
158                         } catch (ArgumentException ex) {
159                                 // Empty name is not legal
160                                 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
161                                 Assert.IsNull (ex.InnerException, "#3");
162                                 Assert.IsNotNull (ex.Message, "#4");
163                                 Assert.AreEqual ("fullname", ex.ParamName, "#5");
164                         }
165                 }
166
167                 [Test]
168                 public void DefineType_Name_NullChar ()
169                 {
170                         AssemblyBuilder ab = genAssembly ();
171                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
172                         try {
173                                 mb.DefineType ("\0test");
174                                 Assert.Fail ("#1");
175                         } catch (ArgumentException ex) {
176                                 // Illegal name
177                                 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
178                                 Assert.IsNull (ex.InnerException, "#3");
179                                 Assert.IsNotNull (ex.Message, "#4");
180                                 Assert.AreEqual ("fullname", ex.ParamName, "#5");
181                         }
182
183                         mb.DefineType ("te\0st");
184                 }
185
186                 [Test]
187                 public void DefineType_InterfaceNotAbstract ()
188                 {
189                         AssemblyBuilder ab = genAssembly ();
190                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
191
192                         try {
193                                 mb.DefineType ("ITest1", TypeAttributes.Interface);
194                                 Assert.Fail ("#A1");
195                         } catch (InvalidOperationException ex) {
196                                 // Interface must be declared abstract
197                                 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
198                                 Assert.IsNull (ex.InnerException, "#A3");
199                                 Assert.IsNotNull (ex.Message, "#A4");
200                         }
201
202                         try {
203                                 mb.DefineType ("ITest2", TypeAttributes.Interface, (Type) null);
204                                 Assert.Fail ("#B1");
205                         } catch (InvalidOperationException ex) {
206                                 // Interface must be declared abstract
207                                 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
208                                 Assert.IsNull (ex.InnerException, "#B3");
209                                 Assert.IsNotNull (ex.Message, "#B4");
210                         }
211
212                         // fail on MS .NET 1.1
213 #if NET_2_0
214                         TypeBuilder tb = mb.DefineType ("ITest2", TypeAttributes.Interface,
215                                 typeof (object));
216                         Assert.AreEqual (typeof (object), tb.BaseType, "#C1");
217
218                         tb = mb.DefineType ("ITest3", TypeAttributes.Interface,
219                                 typeof (IDisposable));
220                         Assert.AreEqual (typeof (IDisposable), tb.BaseType, "#D1");
221 #endif
222                 }
223
224                 [Test]
225 #if ONLY_1_1
226                 [Category ("NotDotNet")] // Parent type was not extensible by the given type
227 #endif
228                 public void DefineType_Parent_Interface ()
229                 {
230                         TypeBuilder tb;
231
232                         AssemblyBuilder ab = genAssembly ();
233                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
234
235                         tb = mb.DefineType ("Foo", TypeAttributes.Class,
236                                 typeof (ICollection));
237                         Assert.AreEqual (typeof (ICollection), tb.BaseType, "#1");
238
239                         tb = mb.DefineType ("Bar", TypeAttributes.Interface,
240                                 typeof (ICollection));
241                         Assert.AreEqual (typeof (ICollection), tb.BaseType, "#2");
242                 }
243
244                 [Test]
245                 public void DuplicateSymbolDocument ()
246                 {
247                         AssemblyBuilder ab = genAssembly ();
248                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
249
250                         // Check that it is possible to redefine a symbol document
251                         ISymbolDocumentWriter doc1 =
252                                 mb.DefineDocument ("foo.il", SymDocumentType.Text,
253                                                                   SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
254                         ISymbolDocumentWriter doc2 =
255                                 mb.DefineDocument ("foo.il", SymDocumentType.Text,
256                                                                   SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
257                 }
258
259                 [Test] // Test case for #80435.
260                 public void GetArrayMethodToStringTest ()
261                 {
262                         AssemblyBuilder assembly = genAssembly ();
263                         ModuleBuilder module = assembly.DefineDynamicModule ("m", "test.dll");
264
265                         Type [] myArrayClass = new Type [1];
266                         Type [] parameterTypes = { typeof (Array) };
267                         MethodInfo myMethodInfo = module.GetArrayMethod (myArrayClass.GetType (), "Sort", CallingConventions.Standard, null, parameterTypes);
268
269                         string str = myMethodInfo.ToString ();
270                         Assert.IsNotNull (str);
271                         // Don't compare string, since MS returns System.Reflection.Emit.SymbolMethod here 
272                         // (they do not provide an implementation of ToString).
273                 }
274
275                 private static void AssertArrayEqualsSorted (Array o1, Array o2)
276                 {
277                         Array s1 = (Array) o1.Clone ();
278                         Array s2 = (Array) o2.Clone ();
279
280                         Array.Sort (s1);
281                         Array.Sort (s2);
282
283                         Assert.AreEqual (s1.Length, s2.Length, "#1");
284                         for (int i = 0; i < s1.Length; ++i)
285                                 Assert.AreEqual (s1.GetValue (i), s2.GetValue (i), "#2: " + i);
286                 }
287
288 #if NET_2_0
289                 [Test]
290                 public void ResolveFieldTokenFieldBuilder ()
291                 {
292                         AssemblyBuilder ab = genAssembly ();
293                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
294
295                         TypeBuilder tb = mb.DefineType ("foo");
296                         FieldBuilder fb = tb.DefineField ("foo", typeof (int), 0);
297                         tb.CreateType ();
298
299                         FieldInfo fi = mb.ResolveField (fb.GetToken ().Token);
300                         Assert.IsNotNull (fi);
301                         Assert.AreEqual ("foo", fi.Name);
302                 }
303
304                 [Test]
305                 [ExpectedException (typeof (ArgumentException))]
306                 public void ResolveFieldTokenInvalidToken ()
307                 {
308                         AssemblyBuilder ab = genAssembly ();
309                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
310
311                         mb.ResolveField (0x4001234);
312                 }
313
314                 [Test]
315                 public void ResolveMethodTokenMethodBuilder ()
316                 {
317                         AssemblyBuilder ab = genAssembly ();
318                         ModuleBuilder moduleb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
319
320                         TypeBuilder tb = moduleb.DefineType ("foo");
321                         MethodBuilder mb = tb.DefineMethod("Frub", MethodAttributes.Static, null, new Type[] { typeof(IntPtr) });
322                         int tok = mb.GetToken().Token;
323                         mb.SetImplementationFlags(MethodImplAttributes.NoInlining);
324                         ILGenerator ilgen = mb.GetILGenerator();
325                         ilgen.Emit(OpCodes.Ret);
326
327                         tb.CreateType ();
328
329                         MethodBase mi = moduleb.ResolveMethod (tok);
330                         Assert.IsNotNull (mi);
331                         Assert.AreEqual ("Frub", mi.Name);
332                 }
333 #endif
334
335                 [Test]
336                 public void GetTypes ()
337                 {
338                         AssemblyBuilder ab = genAssembly ();
339                         ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", "foo.dll");
340
341                         TypeBuilder tb1 = mb.DefineType("Foo", TypeAttributes.Public);
342
343                         Type[] types = mb.GetTypes ();
344                         Assert.AreEqual (1, types.Length);
345                         Assert.AreEqual (tb1, types [0]);
346
347                         // After the type is created, MS seems to return the created type
348                         tb1.CreateType ();
349
350                         types = mb.GetTypes ();
351                         Assert.AreEqual (tb1.CreateType (), types [0]);
352                 }
353
354                 [Test] // GetTypeToken (Type)
355 #if NET_2_0
356                 [Category ("NotDotNet")] // http://support.microsoft.com/kb/950986
357 #endif
358                 public void GetTypeToken2_Type_Array ()
359                 {
360                         Type type;
361                         TypeToken typeToken;
362                         Type resolved_type;
363
364                         AssemblyName aname = genAssemblyName ();
365                         AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
366                                 aname, AssemblyBuilderAccess.RunAndSave);
367                         ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
368
369                         type = typeof (object []);
370                         typeToken = mb.GetTypeToken (type);
371 #if NET_2_0
372                         Assert.IsFalse (typeToken == TypeToken.Empty, "#A1");
373                         resolved_type = mb.ResolveType (typeToken.Token);
374                         Assert.AreEqual (type, resolved_type, "#A2");
375 #else
376                         Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#A1");
377 #endif
378
379 #if NET_2_0
380                         type = typeof (object).MakeArrayType ();
381                         typeToken = mb.GetTypeToken (type);
382                         Assert.IsFalse (typeToken == TypeToken.Empty, "#B1");
383                         resolved_type = mb.ResolveType (typeToken.Token);
384                         Assert.AreEqual (type, resolved_type, "#B2");
385 #endif
386                 }
387
388                 [Test] // GetTypeToken (Type)
389                 public void GetTypeToken2_Type_String ()
390                 {
391                         AssemblyName aname = genAssemblyName ();
392                         AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
393                                 aname, AssemblyBuilderAccess.RunAndSave);
394                         ModuleBuilder mb = ab.DefineDynamicModule ("MyModule");
395                         Type type = typeof (string);
396                         TypeToken typeToken = mb.GetTypeToken (type);
397 #if NET_2_0
398                         Assert.IsFalse (typeToken == TypeToken.Empty, "#1");
399                         Type resolved_type = mb.ResolveType (typeToken.Token);
400                         Assert.AreEqual (type, resolved_type, "#2");
401 #else
402                         Assert.IsFalse (typeToken.Token == TypeToken.Empty.Token, "#1");
403 #endif
404                 }
405
406 #if NET_2_0
407                 [Test] // bug #471302
408                 public void ModuleBuilder_ModuleVersionId ()
409                 {
410                         var name = new AssemblyName () { Name = "Foo" };
411                         var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
412                                 name, AssemblyBuilderAccess.Run);
413
414                         var module = assembly.DefineDynamicModule ("Foo");
415
416                         Assert.AreNotEqual (new Guid (), module.ModuleVersionId);
417                 }
418 #endif
419
420                 [Test]
421                 public void GetGenericArguments_Returns_Null_For_Non_Generic_Methods ()
422                 {
423                         
424                 }
425         }
426 }