2008-09-20 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / appdomain.c
1 /*
2  * appdomain.c: AppDomain functions
3  *
4  * Authors:
5  *      Dietmar Maurer (dietmar@ximian.com)
6  *      Patrik Torstensson
7  *      Gonzalo Paniagua Javier (gonzalo@ximian.com)
8  *
9  * (c) 2001-2003 Ximian, Inc. (http://www.ximian.com)
10  */
11 #undef ASSEMBLY_LOAD_DEBUG
12 #include <config.h>
13 #include <glib.h>
14 #include <string.h>
15 #ifdef HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18 #include <errno.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #ifdef HAVE_UTIME_H
22 #include <utime.h>
23 #else
24 #ifdef HAVE_SYS_UTIME_H
25 #include <sys/utime.h>
26 #endif
27 #endif
28
29 #include <mono/metadata/gc-internal.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/domain-internals.h>
32 #include "mono/metadata/metadata-internals.h"
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/exception.h>
35 #include <mono/metadata/threads.h>
36 #include <mono/metadata/socket-io.h>
37 #include <mono/metadata/tabledefs.h>
38 #include <mono/metadata/gc-internal.h>
39 #include <mono/metadata/mono-gc.h>
40 #include <mono/metadata/marshal.h>
41 #include <mono/metadata/monitor.h>
42 #include <mono/metadata/threadpool.h>
43 #include <mono/metadata/mono-debug.h>
44 #include <mono/utils/mono-uri.h>
45 #include <mono/utils/mono-logger.h>
46 #include <mono/utils/mono-path.h>
47 #include <mono/utils/mono-stdlib.h>
48 #include <mono/utils/mono-io-portability.h>
49 #ifdef PLATFORM_WIN32
50 #include <direct.h>
51 #endif
52
53 /*
54  * This is the version number of the corlib-runtime interface. When
55  * making changes to this interface (by changing the layout
56  * of classes the runtime knows about, changing icall signature or
57  * semantics etc), increment this variable. Also increment the
58  * pair of this variable in mscorlib in:
59  *       mcs/class/mscorlib/System/Environment.cs
60  *
61  * Changes which are already detected at runtime, like the addition
62  * of icalls, do not require an increment.
63  */
64 #define MONO_CORLIB_VERSION 69
65
66 typedef struct
67 {
68         int runtime_count;
69         int assemblybinding_count;
70         MonoDomain *domain;
71 } RuntimeConfig;
72
73 CRITICAL_SECTION mono_delegate_section;
74
75 static gunichar2 process_guid [36];
76 static gboolean process_guid_set = FALSE;
77
78 static gboolean shutting_down = FALSE;
79
80 static gboolean no_exec = FALSE;
81
82 static MonoAssembly *
83 mono_domain_assembly_preload (MonoAssemblyName *aname,
84                               gchar **assemblies_path,
85                               gpointer user_data);
86
87 static MonoAssembly *
88 mono_domain_assembly_search (MonoAssemblyName *aname,
89                                                          gpointer user_data);
90
91 static MonoAssembly *
92 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
93                                                                           gpointer user_data);
94
95 static void
96 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
97
98 static void
99 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
100
101 static void
102 mono_domain_unload (MonoDomain *domain);
103
104 static MonoLoadFunc load_function = NULL;
105
106 void
107 mono_install_runtime_load (MonoLoadFunc func)
108 {
109         load_function = func;
110 }
111
112 MonoDomain*
113 mono_runtime_load (const char *filename, const char *runtime_version)
114 {
115         g_assert (load_function);
116         return load_function (filename, runtime_version);
117 }
118
119 /*
120  * mono_runtime_set_no_exec:
121  *
122  *   Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
123  * code execution. This is useful for running the AOT compiler on platforms which
124  * allow full-aot execution only.
125  * This should be called before mono_runtime_init ().
126  */
127 void
128 mono_runtime_set_no_exec (gboolean val)
129 {
130         no_exec = val;
131 }
132
133 gboolean
134 mono_runtime_get_no_exec (void)
135 {
136         return no_exec;
137 }
138
139 /**
140  * mono_runtime_init:
141  * @domain: domain returned by mono_init ()
142  *
143  * Initialize the core AppDomain: this function will run also some
144  * IL initialization code, so it needs the execution engine to be fully 
145  * operational.
146  *
147  * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
148  * we know the entry_assembly.
149  *
150  */
151 void
152 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
153                    MonoThreadAttachCB attach_cb)
154 {
155         MonoAppDomainSetup *setup;
156         MonoAppDomain *ad;
157         MonoClass *class;
158         MonoString *arg;
159
160         mono_portability_helpers_init ();
161         
162         mono_gc_base_init ();
163         mono_monitor_init ();
164         mono_thread_pool_init ();
165         mono_marshal_init ();
166
167         mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
168         mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
169         mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
170         mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
171         mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
172         mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
173         mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
174         mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
175
176         mono_thread_init (start_cb, attach_cb);
177
178         class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
179         setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
180
181         class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
182         ad = (MonoAppDomain *) mono_object_new (domain, class);
183         ad->data = domain;
184         domain->domain = ad;
185         domain->setup = setup;
186
187         InitializeCriticalSection (&mono_delegate_section);
188
189         mono_thread_attach (domain);
190         mono_context_init (domain);
191         mono_context_set (domain->default_context);
192
193         mono_type_initialization_init ();
194
195         if (!mono_runtime_get_no_exec ()) {
196                 /*
197                  * Create an instance early since we can't do it when there is no memory.
198                  */
199                 arg = mono_string_new (domain, "Out of memory");
200                 domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
201         
202                 /* 
203                  * These two are needed because the signal handlers might be executing on
204                  * an alternate stack, and Boehm GC can't handle that.
205                  */
206                 arg = mono_string_new (domain, "A null value was found where an object instance was required");
207                 domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
208                 arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
209                 domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
210         }
211
212         /* GC init has to happen after thread init */
213         mono_gc_init ();
214
215         mono_network_init ();
216
217         /* mscorlib is loaded before we install the load hook */
218         mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
219         
220         return;
221 }
222
223 static int
224 mono_get_corlib_version (void)
225 {
226         MonoClass *klass;
227         MonoClassField *field;
228         MonoObject *value;
229
230         klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
231         mono_class_init (klass);
232         field = mono_class_get_field_from_name (klass, "mono_corlib_version");
233         if (!field)
234                 return -1;
235         if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
236                 return -1;
237         value = mono_field_get_value_object (mono_domain_get (), field, NULL);
238         return *(gint32*)((gchar*)value + sizeof (MonoObject));
239 }
240
241 const char*
242 mono_check_corlib_version (void)
243 {
244         int version = mono_get_corlib_version ();
245         if (version != MONO_CORLIB_VERSION)
246                 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
247         else
248                 return NULL;
249 }
250
251 void
252 mono_context_init (MonoDomain *domain)
253 {
254         MonoClass *class;
255         MonoAppContext *context;
256
257         class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
258         context = (MonoAppContext *) mono_object_new (domain, class);
259         context->domain_id = domain->domain_id;
260         context->context_id = 0;
261         domain->default_context = context;
262 }
263
264 /**
265  * mono_runtime_cleanup:
266  * @domain: unused.
267  *
268  * Internal routine.
269  *
270  * This must not be called while there are still running threads executing
271  * managed code.
272  */
273 void
274 mono_runtime_cleanup (MonoDomain *domain)
275 {
276         shutting_down = TRUE;
277
278         /* This ends up calling any pending pending (for at most 2 seconds) */
279         mono_gc_cleanup ();
280
281         mono_thread_cleanup ();
282
283         mono_network_cleanup ();
284
285         mono_marshal_cleanup ();
286
287         mono_type_initialization_cleanup ();
288
289         mono_monitor_cleanup ();
290
291 #ifndef PLATFORM_WIN32
292         _wapi_cleanup ();
293 #endif
294 }
295
296 static MonoDomainFunc quit_function = NULL;
297
298 void
299 mono_install_runtime_cleanup (MonoDomainFunc func)
300 {
301         quit_function = func;
302 }
303
304 void
305 mono_runtime_quit ()
306 {
307         if (quit_function != NULL)
308                 quit_function (mono_get_root_domain (), NULL);
309 }
310
311 /** 
312  * mono_runtime_set_shutting_down:
313  *
314  * Invoked by System.Environment.Exit to flag that the runtime
315  * is shutting down.
316  */
317 void
318 mono_runtime_set_shutting_down (void)
319 {
320         shutting_down = TRUE;
321 }
322
323 /**
324  * mono_runtime_is_shutting_down:
325  *
326  * Returns whether the runtime has been flagged for shutdown.
327  *
328  * This is consumed by the P:System.Environment.HasShutdownStarted
329  * property.
330  *
331  */
332 gboolean
333 mono_runtime_is_shutting_down (void)
334 {
335         return shutting_down;
336 }
337
338 /**
339  * mono_domain_has_type_resolve:
340  * @domain: application domains being looked up
341  *
342  * Returns true if the AppDomain.TypeResolve field has been
343  * set.
344  */
345 gboolean
346 mono_domain_has_type_resolve (MonoDomain *domain)
347 {
348         static MonoClassField *field = NULL;
349         MonoObject *o;
350
351         if (field == NULL) {
352                 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
353                 g_assert (field);
354         }
355
356         mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
357         return o != NULL;
358 }
359
360 /**
361  * mono_domain_try_type_resolve:
362  * @domain: application domainwhere the name where the type is going to be resolved
363  * @name: the name of the type to resolve or NULL.
364  * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
365  *
366  * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
367  * the assembly that matches name.
368  *
369  * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
370  *
371  * Returns: A MonoReflectionAssembly or NULL if not found
372  */
373 MonoReflectionAssembly *
374 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
375 {
376         MonoClass *klass;
377         void *params [1];
378         static MonoMethod *method = NULL;
379
380         g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
381
382         if (method == NULL) {
383                 klass = domain->domain->mbr.obj.vtable->klass;
384                 g_assert (klass);
385
386                 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
387                 if (method == NULL) {
388                         g_warning ("Method AppDomain.DoTypeResolve not found.\n");
389                         return NULL;
390                 }
391         }
392
393         if (name)
394                 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
395         else
396                 *params = tb;
397         return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
398 }
399
400 /**
401  * mono_domain_owns_vtable_slot:
402  *
403  *  Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
404  */
405 gboolean
406 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
407 {
408         gboolean res;
409
410         mono_domain_lock (domain);
411         res = mono_mempool_contains_addr (domain->mp, vtable_slot);
412         mono_domain_unlock (domain);
413         return res;
414 }
415
416 /**
417  * mono_domain_set:
418  * @domain: domain
419  * @force: force setting.
420  *
421  * Set the current appdomain to @domain. If @force is set, set it even
422  * if it is being unloaded.
423  *
424  * Returns:
425  *   TRUE on success;
426  *   FALSE if the domain is unloaded
427  */
428 gboolean
429 mono_domain_set (MonoDomain *domain, gboolean force)
430 {
431         if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
432                 return FALSE;
433
434         mono_domain_set_internal (domain);
435
436         return TRUE;
437 }
438
439 MonoObject *
440 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
441 {
442         MonoDomain *add;
443         MonoObject *o;
444         char *str;
445
446         MONO_ARCH_SAVE_REGS;
447
448         g_assert (ad != NULL);
449         add = ad->data;
450         g_assert (add != NULL);
451
452         if (name == NULL)
453                 mono_raise_exception (mono_get_exception_argument_null ("name"));
454
455         str = mono_string_to_utf8 (name);
456
457         mono_domain_lock (add);
458
459         if (!strcmp (str, "APPBASE"))
460                 o = (MonoObject *)add->setup->application_base;
461         else if (!strcmp (str, "APP_CONFIG_FILE"))
462                 o = (MonoObject *)add->setup->configuration_file;
463         else if (!strcmp (str, "DYNAMIC_BASE"))
464                 o = (MonoObject *)add->setup->dynamic_base;
465         else if (!strcmp (str, "APP_NAME"))
466                 o = (MonoObject *)add->setup->application_name;
467         else if (!strcmp (str, "CACHE_BASE"))
468                 o = (MonoObject *)add->setup->cache_path;
469         else if (!strcmp (str, "PRIVATE_BINPATH"))
470                 o = (MonoObject *)add->setup->private_bin_path;
471         else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
472                 o = (MonoObject *)add->setup->private_bin_path_probe;
473         else if (!strcmp (str, "SHADOW_COPY_DIRS"))
474                 o = (MonoObject *)add->setup->shadow_copy_directories;
475         else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
476                 o = (MonoObject *)add->setup->shadow_copy_files;
477         else 
478                 o = mono_g_hash_table_lookup (add->env, name);
479
480         mono_domain_unlock (add);
481         g_free (str);
482
483         if (!o)
484                 return NULL;
485
486         return o;
487 }
488
489 void
490 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
491 {
492         MonoDomain *add;
493
494         MONO_ARCH_SAVE_REGS;
495
496         g_assert (ad != NULL);
497         add = ad->data;
498         g_assert (add != NULL);
499
500         if (name == NULL)
501                 mono_raise_exception (mono_get_exception_argument_null ("name"));
502
503         mono_domain_lock (add);
504
505         mono_g_hash_table_insert (add->env, name, data);
506
507         mono_domain_unlock (add);
508 }
509
510 MonoAppDomainSetup *
511 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
512 {
513         MONO_ARCH_SAVE_REGS;
514
515         g_assert (ad != NULL);
516         g_assert (ad->data != NULL);
517
518         return ad->data->setup;
519 }
520
521 MonoString *
522 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
523 {
524         MONO_ARCH_SAVE_REGS;
525
526         g_assert (ad != NULL);
527         g_assert (ad->data != NULL);
528
529         return mono_string_new (ad->data, ad->data->friendly_name);
530 }
531
532 MonoAppDomain *
533 ves_icall_System_AppDomain_getCurDomain ()
534 {
535         MonoDomain *add = mono_domain_get ();
536
537         MONO_ARCH_SAVE_REGS;
538
539         return add->domain;
540 }
541
542 MonoAppDomain *
543 ves_icall_System_AppDomain_getRootDomain ()
544 {
545         MonoDomain *root = mono_get_root_domain ();
546
547         MONO_ARCH_SAVE_REGS;
548
549         return root->domain;
550 }
551
552 static char*
553 get_attribute_value (const gchar **attribute_names, 
554                      const gchar **attribute_values, 
555                      const char *att_name)
556 {
557         int n;
558         for (n = 0; attribute_names [n] != NULL; n++) {
559                 if (strcmp (attribute_names [n], att_name) == 0)
560                         return g_strdup (attribute_values [n]);
561         }
562         return NULL;
563 }
564
565 static void
566 start_element (GMarkupParseContext *context, 
567                const gchar         *element_name,
568                const gchar        **attribute_names,
569                const gchar        **attribute_values,
570                gpointer             user_data,
571                GError             **error)
572 {
573         RuntimeConfig *runtime_config = user_data;
574         
575         if (strcmp (element_name, "runtime") == 0) {
576                 runtime_config->runtime_count++;
577                 return;
578         }
579
580         if (strcmp (element_name, "assemblyBinding") == 0) {
581                 runtime_config->assemblybinding_count++;
582                 return;
583         }
584         
585         if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
586                 return;
587
588         if (strcmp (element_name, "probing") != 0)
589                 return;
590
591         g_free (runtime_config->domain->private_bin_path);
592         runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
593         if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
594                 g_free (runtime_config->domain->private_bin_path);
595                 runtime_config->domain->private_bin_path = NULL;
596                 return;
597         }
598 }
599
600 static void
601 end_element (GMarkupParseContext *context,
602              const gchar         *element_name,
603              gpointer             user_data,
604              GError             **error)
605 {
606         RuntimeConfig *runtime_config = user_data;
607         if (strcmp (element_name, "runtime") == 0)
608                 runtime_config->runtime_count--;
609         else if (strcmp (element_name, "assemblyBinding") == 0)
610                 runtime_config->assemblybinding_count--;
611 }
612
613 static const GMarkupParser
614 mono_parser = {
615         start_element,
616         end_element,
617         NULL,
618         NULL,
619         NULL
620 };
621
622 static void
623 mono_set_private_bin_path_from_config (MonoDomain *domain)
624 {
625         gchar *config_file, *text;
626         gsize len;
627         struct stat sbuf;
628         GMarkupParseContext *context;
629         RuntimeConfig runtime_config;
630         
631         if (!domain || !domain->setup || !domain->setup->configuration_file)
632                 return;
633
634         config_file = mono_string_to_utf8 (domain->setup->configuration_file);
635         if (stat (config_file, &sbuf) != 0) {
636                 g_free (config_file);
637                 return;
638         }
639
640         if (!g_file_get_contents (config_file, &text, &len, NULL)) {
641                 g_free (config_file);
642                 return;
643         }
644         g_free (config_file);
645
646         runtime_config.runtime_count = 0;
647         runtime_config.assemblybinding_count = 0;
648         runtime_config.domain = domain;
649         
650         context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
651         if (g_markup_parse_context_parse (context, text, len, NULL))
652                 g_markup_parse_context_end_parse (context, NULL);
653         g_markup_parse_context_free (context);
654         g_free (text);
655 }
656
657 MonoAppDomain *
658 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
659 {
660         MonoClass *adclass;
661         MonoAppDomain *ad;
662         MonoDomain *data;
663         
664         MONO_ARCH_SAVE_REGS;
665
666         adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
667
668         /* FIXME: pin all those objects */
669         data = mono_domain_create();
670
671         ad = (MonoAppDomain *) mono_object_new (data, adclass);
672         ad->data = data;
673         data->domain = ad;
674         data->setup = setup;
675         data->friendly_name = mono_string_to_utf8 (friendly_name);
676         // FIXME: The ctor runs in the current domain
677         // FIXME: Initialize null_reference_ex and stack_overflow_ex
678         data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
679
680         if (!setup->application_base) {
681                 /* Inherit from the root domain since MS.NET does this */
682                 MonoDomain *root = mono_get_root_domain ();
683                 if (root->setup->application_base)
684                         MONO_OBJECT_SETREF (setup, application_base, mono_string_new_utf16 (data, mono_string_chars (root->setup->application_base), mono_string_length (root->setup->application_base)));
685         }
686
687         mono_set_private_bin_path_from_config (data);
688         
689         mono_context_init (data);
690
691         add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
692
693         return ad;
694 }
695
696 MonoArray *
697 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
698 {
699         MonoDomain *domain = ad->data; 
700         MonoAssembly* ass;
701         static MonoClass *System_Reflection_Assembly;
702         MonoArray *res;
703         GSList *tmp;
704         int i;
705         GPtrArray *assemblies;
706
707         MONO_ARCH_SAVE_REGS;
708
709         if (!System_Reflection_Assembly)
710                 System_Reflection_Assembly = mono_class_from_name (
711                         mono_defaults.corlib, "System.Reflection", "Assembly");
712
713         /* 
714          * Make a copy of the list of assemblies because we can't hold the assemblies
715          * lock while creating objects etc.
716          */
717         assemblies = g_ptr_array_new ();
718         /* Need to skip internal assembly builders created by remoting */
719         mono_domain_assemblies_lock (domain);
720         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
721                 ass = tmp->data;
722                 if (refonly && !ass->ref_only)
723                         continue;
724                 if (ass->corlib_internal)
725                         continue;
726                 g_ptr_array_add (assemblies, ass);
727         }
728         mono_domain_assemblies_unlock (domain);
729
730         res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
731         for (i = 0; i < assemblies->len; ++i) {
732                 ass = g_ptr_array_index (assemblies, i);
733                 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
734         }
735
736         g_ptr_array_free (assemblies, TRUE);
737
738         return res;
739 }
740
741 MonoReflectionAssembly *
742 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
743 {
744         MonoClass *klass;
745         MonoMethod *method;
746         MonoBoolean isrefonly;
747         gpointer params [2];
748
749         g_assert (domain != NULL && fname != NULL);
750
751         klass = domain->domain->mbr.obj.vtable->klass;
752         g_assert (klass);
753         
754         method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
755         if (method == NULL) {
756                 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
757                 return NULL;
758         }
759
760         isrefonly = refonly ? 1 : 0;
761         params [0] = fname;
762         params [1] = &isrefonly;
763         return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
764 }
765
766 static MonoAssembly *
767 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
768                                                                           gpointer user_data)
769 {
770         gboolean refonly = GPOINTER_TO_UINT (user_data);
771         MonoReflectionAssembly *assembly;
772         MonoDomain *domain = mono_domain_get ();
773         char *aname_str;
774
775         aname_str = mono_stringify_assembly_name (aname);
776
777         /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
778         assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
779
780         g_free (aname_str);
781
782         if (assembly)
783                 return assembly->assembly;
784         else
785                 return NULL;
786 }
787         
788 /*
789  * LOCKING: assumes assemblies_lock in the domain is already locked.
790  */
791 static void
792 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
793 {
794         gint i;
795         GSList *tmp;
796         gboolean destroy_ht = FALSE;
797
798         if (!ass->aname.name)
799                 return;
800
801         if (!ht) {
802                 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
803                 destroy_ht = TRUE;
804         }
805
806         /* FIXME: handle lazy loaded assemblies */
807         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
808                 g_hash_table_insert (ht, tmp->data, tmp->data);
809         }
810         if (!g_hash_table_lookup (ht, ass)) {
811                 mono_assembly_addref (ass);
812                 g_hash_table_insert (ht, ass, ass);
813                 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
814                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly %s %p added to domain %s, ref_count=%d\n", ass->aname.name, ass, domain->friendly_name, ass->ref_count);
815         }
816
817         if (ass->image->references) {
818                 for (i = 0; ass->image->references [i] != NULL; i++) {
819                         if (ass->image->references [i] != REFERENCE_MISSING)
820                                 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
821                                         add_assemblies_to_domain (domain, ass->image->references [i], ht);
822                                 }
823                 }
824         }
825         if (destroy_ht)
826                 g_hash_table_destroy (ht);
827 }
828
829 static void
830 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
831 {
832         static MonoClassField *assembly_load_field;
833         static MonoMethod *assembly_load_method;
834         MonoDomain *domain = mono_domain_get ();
835         MonoReflectionAssembly *ref_assembly;
836         MonoClass *klass;
837         gpointer load_value;
838         void *params [1];
839
840         if (!domain->domain)
841                 /* This can happen during startup */
842                 return;
843 #ifdef ASSEMBLY_LOAD_DEBUG
844         fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
845 #endif
846         klass = domain->domain->mbr.obj.vtable->klass;
847
848         mono_domain_assemblies_lock (domain);
849         add_assemblies_to_domain (domain, assembly, NULL);
850         mono_domain_assemblies_unlock (domain);
851
852         if (assembly_load_field == NULL) {
853                 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
854                 g_assert (assembly_load_field);
855         }
856
857         mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
858         if (load_value == NULL) {
859                 /* No events waiting to be triggered */
860                 return;
861         }
862
863         ref_assembly = mono_assembly_get_object (domain, assembly);
864         g_assert (ref_assembly);
865
866         if (assembly_load_method == NULL) {
867                 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
868                 g_assert (assembly_load_method);
869         }
870
871         *params = ref_assembly;
872         mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
873 }
874
875 /*
876  * LOCKING: Acquires the domain assemblies lock.
877  */
878 static void
879 set_domain_search_path (MonoDomain *domain)
880 {
881         MonoAppDomainSetup *setup;
882         gchar **tmp;
883         gchar *search_path = NULL;
884         gint i;
885         gint npaths = 0;
886         gchar **pvt_split = NULL;
887         GError *error = NULL;
888         gint appbaselen = -1;
889
890         /* 
891          * We use the low-level domain assemblies lock, since this is called from
892          * assembly loads hooks, which means this thread might hold the loader lock.
893          */
894         mono_domain_assemblies_lock (domain);
895
896         if ((domain->search_path != NULL) && !domain->setup->path_changed) {
897                 mono_domain_assemblies_unlock (domain);
898                 return;
899         }
900         if (!domain->setup) {
901                 mono_domain_assemblies_unlock (domain);
902                 return;
903         }
904
905         setup = domain->setup;
906         if (!setup->application_base) {
907                 mono_domain_assemblies_unlock (domain);
908                 return; /* Must set application base to get private path working */
909         }
910
911         npaths++;
912         
913         if (setup->private_bin_path)
914                 search_path = mono_string_to_utf8 (setup->private_bin_path);
915         
916         if (domain->private_bin_path) {
917                 if (search_path == NULL)
918                         search_path = domain->private_bin_path;
919                 else {
920                         gchar *tmp2 = search_path;
921                         search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
922                         g_free (tmp2);
923                 }
924         }
925         
926         if (search_path) {
927                 /*
928                  * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
929                  * directories relative to ApplicationBase separated by semicolons (see
930                  * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
931                  * The loop below copes with the fact that some Unix applications may use ':' (or
932                  * System.IO.Path.PathSeparator) as the path search separator. We replace it with
933                  * ';' for the subsequent split.
934                  *
935                  * The issue was reported in bug #81446
936                  */
937
938 #ifndef PLATFORM_WIN32
939                 gint slen;
940
941                 slen = strlen (search_path);
942                 for (i = 0; i < slen; i++)
943                         if (search_path [i] == ':')
944                                 search_path [i] = ';';
945 #endif
946                 
947                 pvt_split = g_strsplit (search_path, ";", 1000);
948                 g_free (search_path);
949                 for (tmp = pvt_split; *tmp; tmp++, npaths++);
950         }
951
952         if (!npaths) {
953                 if (pvt_split)
954                         g_strfreev (pvt_split);
955                 /*
956                  * Don't do this because the first time is called, the domain
957                  * setup is not finished.
958                  *
959                  * domain->search_path = g_malloc (sizeof (char *));
960                  * domain->search_path [0] = NULL;
961                 */
962                 mono_domain_assemblies_unlock (domain);
963                 return;
964         }
965
966         if (domain->search_path)
967                 g_strfreev (domain->search_path);
968
969         domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
970         tmp [npaths] = NULL;
971
972         *tmp = mono_string_to_utf8 (setup->application_base);
973
974         /* FIXME: is this needed? */
975         if (strncmp (*tmp, "file://", 7) == 0) {
976                 gchar *file = *tmp;
977                 gchar *uri = *tmp;
978                 gchar *tmpuri;
979
980                 if (uri [7] != '/')
981                         uri = g_strdup_printf ("file:///%s", uri + 7);
982
983                 tmpuri = uri;
984                 uri = mono_escape_uri_string (tmpuri);
985                 *tmp = g_filename_from_uri (uri, NULL, &error);
986                 g_free (uri);
987
988                 if (tmpuri != file)
989                         g_free (tmpuri);
990
991                 if (error != NULL) {
992                         g_warning ("%s\n", error->message);
993                         g_error_free (error);
994                         *tmp = file;
995                 } else {
996                         g_free (file);
997                 }
998         }
999
1000         for (i = 1; pvt_split && i < npaths; i++) {
1001                 if (g_path_is_absolute (pvt_split [i - 1])) {
1002                         tmp [i] = g_strdup (pvt_split [i - 1]);
1003                 } else {
1004                         tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1005                 }
1006
1007                 if (strchr (tmp [i], '.')) {
1008                         gchar *reduced;
1009                         gchar *freeme;
1010
1011                         reduced = mono_path_canonicalize (tmp [i]);
1012                         if (appbaselen == -1)
1013                                 appbaselen = strlen (tmp [0]);
1014
1015                         if (strncmp (tmp [0], reduced, appbaselen)) {
1016                                 g_free (reduced);
1017                                 g_free (tmp [i]);
1018                                 tmp [i] = g_strdup ("");
1019                                 continue;
1020                         }
1021
1022                         freeme = tmp [i];
1023                         tmp [i] = reduced;
1024                         g_free (freeme);
1025                 }
1026         }
1027         
1028         if (setup->private_bin_path_probe != NULL) {
1029                 g_free (tmp [0]);
1030                 tmp [0] = g_strdup ("");
1031         }
1032                 
1033         domain->setup->path_changed = FALSE;
1034
1035         g_strfreev (pvt_split);
1036
1037         mono_domain_assemblies_unlock (domain);
1038 }
1039
1040 static gboolean
1041 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1042 {
1043         guint16 *orig, *dest;
1044         gboolean copy_result;
1045         
1046         strcpy (src + srclen - tail_len, extension);
1047         if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
1048                 return TRUE;
1049         orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1050
1051         strcpy (target + targetlen - tail_len, extension);
1052         dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1053         
1054         DeleteFile (dest);
1055         copy_result = CopyFile (orig, dest, FALSE);
1056         g_free (orig);
1057         g_free (dest);
1058         
1059         return copy_result;
1060 }
1061
1062 static gint32 
1063 get_cstring_hash (const char *str)
1064 {
1065         int len, i;
1066         const char *p;
1067         gint32 h = 0;
1068         
1069         if (!str || !str [0])
1070                 return 0;
1071                 
1072         len = strlen (str);
1073         p = str;
1074         for (i = 0; i < len; i++) {
1075                 h = (h << 5) - h + *p;
1076                 p++;
1077         }
1078         
1079         return h;
1080 }
1081
1082 static char *
1083 get_shadow_assembly_location (const char *filename)
1084 {
1085         gint32 hash = 0, hash2 = 0;
1086         char name_hash [9];
1087         char path_hash [30];
1088         char *bname = g_path_get_basename (filename);
1089         char *dirname = g_path_get_dirname (filename);
1090         char *location, *dyn_base;
1091         MonoDomain *domain = mono_domain_get ();
1092         
1093         hash = get_cstring_hash (bname);
1094         hash2 = get_cstring_hash (dirname);
1095         g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1096         g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1097         dyn_base = mono_string_to_utf8 (domain->setup->dynamic_base);
1098         location = g_build_filename (dyn_base, "assembly", "shadow", name_hash, path_hash, bname, NULL);
1099         g_free (dyn_base);
1100         g_free (bname);
1101         g_free (dirname);
1102         return location;
1103 }
1104
1105 static gboolean
1106 ensure_directory_exists (const char *filename)
1107 {
1108 #ifdef PLATFORM_WIN32
1109         gchar *dir_utf8 = g_path_get_dirname (filename);
1110         gunichar2 *p;
1111         gunichar2 *dir_utf16 = NULL;
1112         int retval;
1113         
1114         if (!dir_utf8 || !dir_utf8 [0])
1115                 return FALSE;
1116
1117         dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1118         g_free (dir_utf8);
1119
1120         if (!dir_utf16)
1121                 return FALSE;
1122
1123         p = dir_utf16;
1124
1125         /* make life easy and only use one directory seperator */
1126         while (*p != '\0')
1127         {
1128                 if (*p == '/')
1129                         *p = '\\';
1130                 p++;
1131         }
1132
1133         p = dir_utf16;
1134
1135         /* get past C:\ )*/
1136         while (*p++ != '\\')    
1137         {
1138         }
1139
1140         while (1) {
1141                 BOOL bRet = FALSE;
1142                 p = wcschr (p, '\\');
1143                 if (p)
1144                         *p = '\0';
1145                 retval = _wmkdir (dir_utf16);
1146                 if (retval != 0 && errno != EEXIST) {
1147                         g_free (dir_utf16);
1148                         return FALSE;
1149                 }
1150                 if (!p)
1151                         break;
1152                 *p++ = '\\';
1153         }
1154         
1155         g_free (dir_utf16);
1156         return TRUE;
1157 #else
1158         char *p;
1159         gchar *dir = g_path_get_dirname (filename);
1160         int retval;
1161         struct stat sbuf;
1162         
1163         if (!dir || !dir [0]) {
1164                 g_free (dir);
1165                 return FALSE;
1166         }
1167         
1168         if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1169                 g_free (dir);
1170                 return TRUE;
1171         }
1172         
1173         p = dir;
1174         while (*p == '/')
1175                 p++;
1176
1177         while (1) {
1178                 p = strchr (p, '/');
1179                 if (p)
1180                         *p = '\0';
1181                 retval = mkdir (dir, 0777);
1182                 if (retval != 0 && errno != EEXIST) {
1183                         g_free (dir);
1184                         return FALSE;
1185                 }
1186                 if (!p)
1187                         break;
1188                 *p++ = '/';
1189         }
1190         
1191         g_free (dir);
1192         return TRUE;
1193 #endif
1194 }
1195
1196 static gboolean
1197 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1198 {
1199         struct stat sbuf_dest;
1200         
1201         if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
1202                 return TRUE;
1203
1204         if (sbuf_src->st_mode == sbuf_dest.st_mode &&
1205             sbuf_src->st_size == sbuf_dest.st_size &&
1206             sbuf_src->st_mtime == sbuf_dest.st_mtime)
1207                 return FALSE;
1208
1209         return TRUE;
1210 }
1211
1212 char *
1213 mono_make_shadow_copy (const char *filename)
1214 {
1215         gchar *sibling_source, *sibling_target;
1216         gint sibling_source_len, sibling_target_len;
1217         guint16 *orig, *dest;
1218         char *shadow;
1219         gboolean copy_result;
1220         gboolean is_private = FALSE;
1221         gboolean do_copy = FALSE;
1222         MonoException *exc;
1223         gchar **path;
1224         struct stat src_sbuf;
1225         struct utimbuf utbuf;
1226         char *dir_name = g_path_get_dirname (filename);
1227         MonoDomain *domain = mono_domain_get ();
1228         set_domain_search_path (domain);
1229
1230         if (!domain->search_path) {
1231                 g_free (dir_name);
1232                 return (char*) filename;
1233         }
1234         
1235         for (path = domain->search_path; *path; path++) {
1236                 if (**path == '\0') {
1237                         is_private = TRUE;
1238                         continue;
1239                 }
1240                 
1241                 if (!is_private)
1242                         continue;
1243
1244                 if (strstr (dir_name, *path) == dir_name) {
1245                         do_copy = TRUE;
1246                         break;
1247                 }
1248         }
1249         g_free (dir_name);
1250
1251         if (!do_copy)
1252                 return (char*) filename;
1253         
1254         shadow = get_shadow_assembly_location (filename);
1255         if (ensure_directory_exists (shadow) == FALSE) {
1256                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1257                 mono_raise_exception (exc);
1258         }       
1259
1260         if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1261                 return (char*) shadow;
1262
1263         orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1264         dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1265         DeleteFile (dest);
1266         copy_result = CopyFile (orig, dest, FALSE);
1267         g_free (dest);
1268         g_free (orig);
1269
1270         if (copy_result == FALSE) {
1271                 g_free (shadow);
1272                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1273                 mono_raise_exception (exc);
1274         }
1275
1276         /* attempt to copy .mdb, .config if they exist */
1277         sibling_source = g_strconcat (filename, ".config", NULL);
1278         sibling_source_len = strlen (sibling_source);
1279         sibling_target = g_strconcat (shadow, ".config", NULL);
1280         sibling_target_len = strlen (sibling_target);
1281         
1282         copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1283         if (copy_result == TRUE)
1284                 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1285         
1286         g_free (sibling_source);
1287         g_free (sibling_target);
1288         
1289         if (copy_result == FALSE)  {
1290                 g_free (shadow);
1291                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1292                 mono_raise_exception (exc);
1293         }
1294
1295         utbuf.actime = src_sbuf.st_atime;
1296         utbuf.modtime = src_sbuf.st_mtime;
1297         utime (shadow, &utbuf);
1298         
1299         return shadow;
1300 }
1301
1302
1303 MonoDomain *
1304 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1305 {
1306         if (appdomain == NULL)
1307                 return NULL;
1308         
1309         return appdomain->data;
1310 }
1311
1312 static gboolean
1313 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1314                                         const gchar *path3, const gchar *path4,
1315                                         gboolean refonly, gboolean is_private)
1316 {
1317         gchar *fullpath;
1318         gboolean found = FALSE;
1319         
1320         *assembly = NULL;
1321         fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1322
1323         if (IS_PORTABILITY_SET) {
1324                 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1325                 if (new_fullpath) {
1326                         g_free (fullpath);
1327                         fullpath = new_fullpath;
1328                         found = TRUE;
1329                 }
1330         } else
1331                 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1332         
1333         if (found)
1334                 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1335
1336         g_free (fullpath);
1337         return (*assembly != NULL);
1338 }
1339
1340 static MonoAssembly *
1341 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1342 {
1343         MonoAssembly *result = NULL;
1344         gchar **path;
1345         gchar *filename;
1346         const gchar *local_culture;
1347         gint len;
1348         gboolean is_private = FALSE;
1349
1350         if (!culture || *culture == '\0') {
1351                 local_culture = "";
1352         } else {
1353                 local_culture = culture;
1354         }
1355
1356         filename =  g_strconcat (name, ".dll", NULL);
1357         len = strlen (filename);
1358
1359         for (path = search_path; *path; path++) {
1360                 if (**path == '\0') {
1361                         is_private = TRUE;
1362                         continue; /* Ignore empty ApplicationBase */
1363                 }
1364
1365                 /* See test cases in bug #58992 and bug #57710 */
1366                 /* 1st try: [culture]/[name].dll (culture may be empty) */
1367                 strcpy (filename + len - 4, ".dll");
1368                 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1369                         break;
1370
1371                 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1372                 strcpy (filename + len - 4, ".exe");
1373                 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1374                         break;
1375
1376                 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1377                 strcpy (filename + len - 4, ".dll");
1378                 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1379                         break;
1380
1381                 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1382                 strcpy (filename + len - 4, ".exe");
1383                 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1384                         break;
1385         }
1386
1387         g_free (filename);
1388         return result;
1389 }
1390
1391 /*
1392  * Try loading the assembly from ApplicationBase and PrivateBinPath 
1393  * and then from assemblies_path if any.
1394  * LOCKING: This is called from the assembly loading code, which means the caller
1395  * might hold the loader lock. Thus, this function must not acquire the domain lock.
1396  */
1397 static MonoAssembly *
1398 mono_domain_assembly_preload (MonoAssemblyName *aname,
1399                               gchar **assemblies_path,
1400                               gpointer user_data)
1401 {
1402         MonoDomain *domain = mono_domain_get ();
1403         MonoAssembly *result = NULL;
1404         gboolean refonly = GPOINTER_TO_UINT (user_data);
1405
1406         set_domain_search_path (domain);
1407
1408         if (domain->search_path && domain->search_path [0] != NULL) {
1409                 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1410         }
1411
1412         if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1413                 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1414         }
1415
1416         return result;
1417 }
1418
1419 /*
1420  * Check whenever a given assembly was already loaded in the current appdomain.
1421  */
1422 static MonoAssembly *
1423 mono_domain_assembly_search (MonoAssemblyName *aname,
1424                                                          gpointer user_data)
1425 {
1426         MonoDomain *domain = mono_domain_get ();
1427         GSList *tmp;
1428         MonoAssembly *ass;
1429         gboolean refonly = GPOINTER_TO_UINT (user_data);
1430
1431         mono_domain_assemblies_lock (domain);
1432         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1433                 ass = tmp->data;
1434                 /* Dynamic assemblies can't match here in MS.NET */
1435                 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1436                         continue;
1437
1438                 mono_domain_assemblies_unlock (domain);
1439                 return ass;
1440         }
1441         mono_domain_assemblies_unlock (domain);
1442
1443         return NULL;
1444 }
1445
1446 MonoReflectionAssembly *
1447 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1448 {
1449         MonoDomain *domain = mono_domain_get ();
1450         char *name, *filename;
1451         MonoImageOpenStatus status = MONO_IMAGE_OK;
1452         MonoAssembly *ass;
1453
1454         MONO_ARCH_SAVE_REGS;
1455
1456         if (fname == NULL) {
1457                 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1458                 mono_raise_exception (exc);
1459         }
1460                 
1461         name = filename = mono_string_to_utf8 (fname);
1462         
1463         ass = mono_assembly_open_full (filename, &status, refOnly);
1464         
1465         if (!ass){
1466                 MonoException *exc;
1467
1468                 if (status == MONO_IMAGE_IMAGE_INVALID)
1469                         exc = mono_get_exception_bad_image_format2 (NULL, fname);
1470                 else
1471                         exc = mono_get_exception_file_not_found2 (NULL, fname);
1472                 g_free (name);
1473                 mono_raise_exception (exc);
1474         }
1475
1476         g_free (name);
1477
1478         return mono_assembly_get_object (domain, ass);
1479 }
1480
1481 MonoReflectionAssembly *
1482 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad, 
1483                                             MonoArray *raw_assembly,
1484                                             MonoArray *raw_symbol_store, MonoObject *evidence,
1485                                             MonoBoolean refonly)
1486 {
1487         MonoAssembly *ass;
1488         MonoReflectionAssembly *refass = NULL;
1489         MonoDomain *domain = ad->data;
1490         MonoImageOpenStatus status;
1491         guint32 raw_assembly_len = mono_array_length (raw_assembly);
1492         MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1493
1494         if (!image) {
1495                 mono_raise_exception (mono_get_exception_bad_image_format (""));
1496                 return NULL;
1497         }
1498
1499         if (raw_symbol_store != NULL)
1500                 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1501
1502         ass = mono_assembly_load_from_full (image, "", &status, refonly);
1503
1504
1505         if (!ass) {
1506                 mono_image_close (image);
1507                 mono_raise_exception (mono_get_exception_bad_image_format (""));
1508                 return NULL; 
1509         }
1510
1511         refass = mono_assembly_get_object (domain, ass);
1512         MONO_OBJECT_SETREF (refass, evidence, evidence);
1513         return refass;
1514 }
1515
1516 MonoReflectionAssembly *
1517 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad,  MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1518 {
1519         MonoDomain *domain = ad->data; 
1520         MonoImageOpenStatus status = MONO_IMAGE_OK;
1521         MonoAssembly *ass;
1522         MonoAssemblyName aname;
1523         MonoReflectionAssembly *refass = NULL;
1524         gchar *name;
1525         gboolean parsed;
1526
1527         MONO_ARCH_SAVE_REGS;
1528
1529         g_assert (assRef != NULL);
1530
1531         name = mono_string_to_utf8 (assRef);
1532         parsed = mono_assembly_name_parse (name, &aname);
1533         g_free (name);
1534
1535         if (!parsed) {
1536                 MonoException *exc;
1537
1538                 /* This is a parse error... */
1539                 exc = mono_get_exception_file_not_found2 (NULL, assRef);
1540                 mono_raise_exception (exc);
1541         }
1542
1543         ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1544         mono_assembly_name_free (&aname);
1545
1546         if (!ass) {
1547                 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1548                 if (!refOnly)
1549                         refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1550                 else
1551                         refass = NULL;
1552                 if (!refass) {
1553                         /* FIXME: it doesn't make much sense since we really don't have a filename ... */
1554                         MonoException *exc = mono_get_exception_file_not_found2 (NULL, assRef);
1555                         mono_raise_exception (exc);
1556                 }
1557         }
1558
1559         if (refass == NULL)
1560                 refass = mono_assembly_get_object (domain, ass);
1561
1562         MONO_OBJECT_SETREF (refass, evidence, evidence);
1563         return refass;
1564 }
1565
1566 void
1567 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1568 {
1569         MonoDomain * domain = mono_domain_get_by_id (domain_id);
1570
1571         MONO_ARCH_SAVE_REGS;
1572
1573         if (NULL == domain) {
1574                 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1575                 mono_raise_exception (exc);
1576         }
1577         
1578         if (domain == mono_get_root_domain ()) {
1579                 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1580                 return;
1581         }
1582
1583         /* 
1584          * Unloading seems to cause problems when running NUnit/NAnt, hence
1585          * this workaround.
1586          */
1587         if (g_getenv ("MONO_NO_UNLOAD"))
1588                 return;
1589
1590         mono_domain_unload (domain);
1591 }
1592
1593 gboolean
1594 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1595 {
1596         MonoDomain *domain = mono_domain_get_by_id (domain_id);
1597
1598         if (!domain)
1599                 return TRUE;
1600
1601         return mono_domain_is_unloading (domain);
1602 }
1603
1604 gint32
1605 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad, 
1606                                                                                         MonoReflectionAssembly *refass, MonoArray *args)
1607 {
1608         MonoImage *image;
1609         MonoMethod *method;
1610
1611         MONO_ARCH_SAVE_REGS;
1612
1613         g_assert (refass);
1614         image = refass->assembly->image;
1615         g_assert (image);
1616
1617         method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1618
1619         if (!method)
1620                 g_error ("No entry point method found in %s", image->name);
1621
1622         if (!args)
1623                 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1624
1625         return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1626 }
1627
1628 gint32 
1629 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad) 
1630 {
1631         MONO_ARCH_SAVE_REGS;
1632
1633         return ad->data->domain_id;
1634 }
1635
1636 MonoAppDomain * 
1637 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1638 {
1639         MonoDomain *old_domain = mono_domain_get();
1640
1641         MONO_ARCH_SAVE_REGS;
1642
1643         if (!mono_domain_set (ad->data, FALSE))
1644                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1645
1646         return old_domain->domain;
1647 }
1648
1649 MonoAppDomain * 
1650 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1651 {
1652         MonoDomain *current_domain = mono_domain_get ();
1653         MonoDomain *domain = mono_domain_get_by_id (domainid);
1654
1655         MONO_ARCH_SAVE_REGS;
1656
1657         if (!domain || !mono_domain_set (domain, FALSE))        
1658                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1659
1660         return current_domain->domain;
1661 }
1662
1663 void
1664 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1665 {
1666         MONO_ARCH_SAVE_REGS;
1667
1668         mono_thread_push_appdomain_ref (ad->data);
1669 }
1670
1671 void
1672 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1673 {
1674         MonoDomain *domain = mono_domain_get_by_id (domain_id);
1675
1676         MONO_ARCH_SAVE_REGS;
1677
1678         if (!domain)
1679                 /* 
1680                  * Raise an exception to prevent the managed code from executing a pop
1681                  * later.
1682                  */
1683                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1684
1685         mono_thread_push_appdomain_ref (domain);
1686 }
1687
1688 void
1689 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1690 {
1691         MONO_ARCH_SAVE_REGS;
1692
1693         mono_thread_pop_appdomain_ref ();
1694 }
1695
1696 MonoAppContext * 
1697 ves_icall_System_AppDomain_InternalGetContext ()
1698 {
1699         MONO_ARCH_SAVE_REGS;
1700
1701         return mono_context_get ();
1702 }
1703
1704 MonoAppContext * 
1705 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1706 {
1707         MONO_ARCH_SAVE_REGS;
1708
1709         return mono_domain_get ()->default_context;
1710 }
1711
1712 MonoAppContext * 
1713 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1714 {
1715         MonoAppContext *old_context = mono_context_get ();
1716
1717         MONO_ARCH_SAVE_REGS;
1718
1719         mono_context_set (mc);
1720
1721         return old_context;
1722 }
1723
1724 MonoString *
1725 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1726 {
1727         MonoDomain* mono_root_domain = mono_get_root_domain ();
1728         mono_domain_lock (mono_root_domain);
1729         if (process_guid_set) {
1730                 mono_domain_unlock (mono_root_domain);
1731                 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1732         }
1733         memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1734         process_guid_set = TRUE;
1735         mono_domain_unlock (mono_root_domain);
1736         return newguid;
1737 }
1738
1739 gboolean
1740 mono_domain_is_unloading (MonoDomain *domain)
1741 {
1742         if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1743                 return TRUE;
1744         else
1745                 return FALSE;
1746 }
1747
1748 static void
1749 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1750 {
1751         MonoClass *klass = (MonoClass*)key;
1752         MonoDomain *domain = (MonoDomain*)user_data;
1753         MonoClassRuntimeInfo *runtime_info;
1754
1755         runtime_info = klass->runtime_info;
1756         if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1757                 runtime_info->domain_vtables [domain->domain_id] = NULL;
1758 }
1759
1760 typedef struct unload_data {
1761         MonoDomain *domain;
1762         char *failure_reason;
1763 } unload_data;
1764
1765 static guint32 WINAPI
1766 unload_thread_main (void *arg)
1767 {
1768         unload_data *data = (unload_data*)arg;
1769         MonoDomain *domain = data->domain;
1770
1771         /* Have to attach to the runtime so shutdown can wait for this thread */
1772         mono_thread_attach (mono_get_root_domain ());
1773
1774         /* 
1775          * FIXME: Abort our parent thread last, so we can return a failure 
1776          * indication if aborting times out.
1777          */
1778         if (!mono_threads_abort_appdomain_threads (domain, -1)) {
1779                 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1780                 return 1;
1781         }
1782
1783         /* Finalize all finalizable objects in the doomed appdomain */
1784         if (!mono_domain_finalize (domain, -1)) {
1785                 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1786                 return 1;
1787         }
1788
1789         /* Clear references to our vtables in class->runtime_info.
1790          * We also hold the loader lock because we're going to change
1791          * class->runtime_info.
1792          */
1793         mono_domain_lock (domain);
1794         mono_loader_lock ();
1795         g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1796         mono_loader_unlock ();
1797         mono_domain_unlock (domain);
1798
1799         mono_threads_clear_cached_culture (domain);
1800
1801         domain->state = MONO_APPDOMAIN_UNLOADED;
1802
1803         /* printf ("UNLOADED %s.\n", domain->friendly_name); */
1804
1805         /* remove from the handle table the items related to this domain */
1806         mono_gchandle_free_domain (domain);
1807
1808         mono_domain_free (domain, FALSE);
1809
1810         mono_gc_collect (mono_gc_max_generation ());
1811
1812         return 0;
1813 }
1814
1815 /*
1816  * mono_domain_unload:
1817  * @domain: The domain to unload
1818  *
1819  *  Unloads an appdomain. Follows the process outlined in:
1820  *  http://blogs.gotdotnet.com/cbrumme
1821  *
1822  *  If doing things the 'right' way is too hard or complex, we do it the 
1823  *  'simple' way, which means do everything needed to avoid crashes and
1824  *  memory leaks, but not much else.
1825  */
1826 static void
1827 mono_domain_unload (MonoDomain *domain)
1828 {
1829         HANDLE thread_handle;
1830         gsize tid;
1831         guint32 res;
1832         MonoAppDomainState prev_state;
1833         MonoMethod *method;
1834         MonoObject *exc;
1835         unload_data thread_data;
1836         MonoDomain *caller_domain = mono_domain_get ();
1837
1838         /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
1839
1840         /* Atomically change our state to UNLOADING */
1841         prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
1842                                                                                          MONO_APPDOMAIN_UNLOADING,
1843                                                                                          MONO_APPDOMAIN_CREATED);
1844         if (prev_state != MONO_APPDOMAIN_CREATED) {
1845                 if (prev_state == MONO_APPDOMAIN_UNLOADING)
1846                         mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
1847                 else
1848                         if (prev_state == MONO_APPDOMAIN_UNLOADED)
1849                                 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
1850                 else
1851                         g_assert_not_reached ();
1852         }
1853
1854         mono_domain_set (domain, FALSE);
1855         /* Notify OnDomainUnload listeners */
1856         method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1); 
1857         g_assert (method);
1858
1859         exc = NULL;
1860         mono_runtime_invoke (method, domain->domain, NULL, &exc);
1861         if (exc) {
1862                 /* Roll back the state change */
1863                 domain->state = MONO_APPDOMAIN_CREATED;
1864                 mono_domain_set (caller_domain, FALSE);
1865                 mono_raise_exception ((MonoException*)exc);
1866         }
1867
1868         thread_data.domain = domain;
1869         thread_data.failure_reason = NULL;
1870
1871         /* 
1872          * First we create a separate thread for unloading, since
1873          * we might have to abort some threads, including the current one.
1874          */
1875         /*
1876          * If we create a non-suspended thread, the runtime will hang.
1877          * See:
1878          * http://bugzilla.ximian.com/show_bug.cgi?id=27663
1879          */ 
1880 #if 0
1881         thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
1882 #else
1883         thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
1884         if (thread_handle == NULL) {
1885                 return;
1886         }
1887         ResumeThread (thread_handle);
1888 #endif
1889
1890         /* Wait for the thread */       
1891         while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
1892                 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
1893                         /* The unload thread tries to abort us */
1894                         /* The icall wrapper will execute the abort */
1895                         CloseHandle (thread_handle);
1896                         return;
1897         }
1898         CloseHandle (thread_handle);
1899
1900         mono_domain_set (caller_domain, FALSE);
1901
1902         if (thread_data.failure_reason) {
1903                 MonoException *ex;
1904
1905                 /* Roll back the state change */
1906                 domain->state = MONO_APPDOMAIN_CREATED;
1907
1908                 g_warning (thread_data.failure_reason);
1909
1910                 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
1911
1912                 g_free (thread_data.failure_reason);
1913                 thread_data.failure_reason = NULL;
1914
1915                 mono_raise_exception (ex);
1916         }
1917 }