Merge pull request #642 from Ventero/CleanCopyLocal
[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  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  * Copyright 2012 Xamarin Inc
12  */
13 #undef ASSEMBLY_LOAD_DEBUG
14 #include <config.h>
15 #include <glib.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <time.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #ifdef HAVE_SYS_TIME_H
22 #include <sys/time.h>
23 #endif
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_UTIME_H
28 #include <utime.h>
29 #else
30 #ifdef HAVE_SYS_UTIME_H
31 #include <sys/utime.h>
32 #endif
33 #endif
34
35 #include <mono/metadata/gc-internal.h>
36 #include <mono/metadata/object.h>
37 #include <mono/metadata/domain-internals.h>
38 #include "mono/metadata/metadata-internals.h"
39 #include <mono/metadata/assembly.h>
40 #include <mono/metadata/exception.h>
41 #include <mono/metadata/threads.h>
42 #include <mono/metadata/socket-io.h>
43 #include <mono/metadata/tabledefs.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/mono-gc.h>
46 #include <mono/metadata/marshal.h>
47 #include <mono/metadata/monitor.h>
48 #include <mono/metadata/threadpool.h>
49 #include <mono/metadata/mono-debug.h>
50 #include <mono/metadata/mono-debug-debugger.h>
51 #include <mono/metadata/attach.h>
52 #include <mono/metadata/file-io.h>
53 #include <mono/metadata/lock-tracer.h>
54 #include <mono/metadata/console-io.h>
55 #include <mono/metadata/threads-types.h>
56 #include <mono/metadata/tokentype.h>
57 #include <mono/utils/mono-uri.h>
58 #include <mono/utils/mono-logger-internal.h>
59 #include <mono/utils/mono-path.h>
60 #include <mono/utils/mono-stdlib.h>
61 #include <mono/utils/mono-io-portability.h>
62 #include <mono/utils/mono-error-internals.h>
63 #include <mono/utils/atomic.h>
64 #include <mono/utils/mono-memory-model.h>
65 #ifdef HOST_WIN32
66 #include <direct.h>
67 #endif
68
69 /*
70  * This is the version number of the corlib-runtime interface. When
71  * making changes to this interface (by changing the layout
72  * of classes the runtime knows about, changing icall signature or
73  * semantics etc), increment this variable. Also increment the
74  * pair of this variable in mscorlib in:
75  *       mcs/class/mscorlib/System/Environment.cs
76  *
77  * Changes which are already detected at runtime, like the addition
78  * of icalls, do not require an increment.
79  */
80 #define MONO_CORLIB_VERSION 110
81
82 typedef struct
83 {
84         int runtime_count;
85         int assemblybinding_count;
86         MonoDomain *domain;
87         gchar *filename;
88 } RuntimeConfig;
89
90 CRITICAL_SECTION mono_delegate_section;
91
92 CRITICAL_SECTION mono_strtod_mutex;
93
94 static gunichar2 process_guid [36];
95 static gboolean process_guid_set = FALSE;
96
97 static gboolean no_exec = FALSE;
98
99 static MonoAssembly *
100 mono_domain_assembly_preload (MonoAssemblyName *aname,
101                               gchar **assemblies_path,
102                               gpointer user_data);
103
104 static MonoAssembly *
105 mono_domain_assembly_search (MonoAssemblyName *aname,
106                                                          gpointer user_data);
107
108 static MonoAssembly *
109 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
110                                                                           gpointer user_data);
111
112 static void
113 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
114
115 static void
116 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
117
118 static MonoAppDomain *
119 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup);
120
121 static char *
122 get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error);
123
124 static MonoLoadFunc load_function = NULL;
125
126 void
127 mono_install_runtime_load (MonoLoadFunc func)
128 {
129         load_function = func;
130 }
131
132 MonoDomain*
133 mono_runtime_load (const char *filename, const char *runtime_version)
134 {
135         g_assert (load_function);
136         return load_function (filename, runtime_version);
137 }
138
139 /**
140  * mono_runtime_set_no_exec:
141  *
142  * Instructs the runtime to operate in static mode, i.e. avoid/do not
143  * allow managed code execution. This is useful for running the AOT
144  * compiler on platforms which allow full-aot execution only.  This
145  * should be called before mono_runtime_init ().
146  */
147 void
148 mono_runtime_set_no_exec (gboolean val)
149 {
150         no_exec = val;
151 }
152
153 /**
154  * mono_runtime_get_no_exec:
155  *
156  * If true, then the runtime will not allow managed code execution.
157  */
158 gboolean
159 mono_runtime_get_no_exec (void)
160 {
161         return no_exec;
162 }
163
164 static void
165 create_domain_objects (MonoDomain *domain)
166 {
167         MonoDomain *old_domain = mono_domain_get ();
168         MonoString *arg;
169
170         if (domain != old_domain) {
171                 mono_thread_push_appdomain_ref (domain);
172                 mono_domain_set_internal_with_options (domain, FALSE);
173         }
174
175         /*
176          * Create an instance early since we can't do it when there is no memory.
177          */
178         arg = mono_string_new (domain, "Out of memory");
179         domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
180
181         /* 
182          * These two are needed because the signal handlers might be executing on
183          * an alternate stack, and Boehm GC can't handle that.
184          */
185         arg = mono_string_new (domain, "A null value was found where an object instance was required");
186         domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
187         arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
188         domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
189
190         /*The ephemeron tombstone i*/
191         domain->ephemeron_tombstone = mono_object_new (domain, mono_defaults.object_class);
192
193         if (domain != old_domain) {
194                 mono_thread_pop_appdomain_ref ();
195                 mono_domain_set_internal_with_options (old_domain, FALSE);
196         }
197
198         /* 
199          * This class is used during exception handling, so initialize it here, to prevent
200          * stack overflows while handling stack overflows.
201          */
202         mono_class_init (mono_array_class_get (mono_defaults.int_class, 1));
203 }
204
205 /**
206  * mono_runtime_init:
207  * @domain: domain returned by mono_init ()
208  *
209  * Initialize the core AppDomain: this function will run also some
210  * IL initialization code, so it needs the execution engine to be fully 
211  * operational.
212  *
213  * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
214  * we know the entry_assembly.
215  *
216  */
217 void
218 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
219                    MonoThreadAttachCB attach_cb)
220 {
221         MonoAppDomainSetup *setup;
222         MonoAppDomain *ad;
223         MonoClass *class;
224
225         mono_portability_helpers_init ();
226         
227         mono_gc_base_init ();
228         mono_monitor_init ();
229         mono_thread_pool_init ();
230         mono_marshal_init ();
231
232         mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
233         mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
234         mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
235         mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
236         mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
237         mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
238         mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
239         mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
240
241         mono_thread_init (start_cb, attach_cb);
242
243         class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
244         setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
245
246         class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
247         ad = (MonoAppDomain *) mono_object_new (domain, class);
248         ad->data = domain;
249         domain->domain = ad;
250         domain->setup = setup;
251
252         InitializeCriticalSection (&mono_delegate_section);
253
254         InitializeCriticalSection (&mono_strtod_mutex);
255         
256         mono_thread_attach (domain);
257         mono_context_init (domain);
258         mono_context_set (domain->default_context);
259
260         mono_type_initialization_init ();
261
262         if (!mono_runtime_get_no_exec ())
263                 create_domain_objects (domain);
264
265         /* GC init has to happen after thread init */
266         mono_gc_init ();
267
268 #ifndef DISABLE_SOCKETS
269         mono_network_init ();
270 #endif
271         
272         mono_console_init ();
273         mono_attach_init ();
274
275         mono_locks_tracer_init ();
276
277         /* mscorlib is loaded before we install the load hook */
278         mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
279         
280         return;
281 }
282
283 static int
284 mono_get_corlib_version (void)
285 {
286         MonoClass *klass;
287         MonoClassField *field;
288         MonoObject *value;
289
290         klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
291         mono_class_init (klass);
292         field = mono_class_get_field_from_name (klass, "mono_corlib_version");
293         if (!field)
294                 return -1;
295         if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
296                 return -1;
297         value = mono_field_get_value_object (mono_domain_get (), field, NULL);
298         return *(gint32*)((gchar*)value + sizeof (MonoObject));
299 }
300
301 /**
302  * mono_check_corlib_version
303  *
304  * Checks that the corlib that is loaded matches the version of this runtime.
305  *
306  * Returns: NULL if the runtime will work with the corlib, or a g_malloc
307  * allocated string with the error otherwise.
308  */
309 const char*
310 mono_check_corlib_version (void)
311 {
312         int version = mono_get_corlib_version ();
313         if (version != MONO_CORLIB_VERSION)
314                 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
315         else
316                 return NULL;
317 }
318
319 /**
320  * mono_context_init:
321  * @domain: The domain where the System.Runtime.Remoting.Context.Context is initialized
322  *
323  * Initializes the @domain's default System.Runtime.Remoting's Context.
324  */
325 void
326 mono_context_init (MonoDomain *domain)
327 {
328         MonoClass *class;
329         MonoAppContext *context;
330
331         class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
332         context = (MonoAppContext *) mono_object_new (domain, class);
333         context->domain_id = domain->domain_id;
334         context->context_id = 0;
335         domain->default_context = context;
336 }
337
338 /**
339  * mono_runtime_cleanup:
340  * @domain: unused.
341  *
342  * Internal routine.
343  *
344  * This must not be called while there are still running threads executing
345  * managed code.
346  */
347 void
348 mono_runtime_cleanup (MonoDomain *domain)
349 {
350         mono_attach_cleanup ();
351
352         /* This ends up calling any pending pending (for at most 2 seconds) */
353         mono_gc_cleanup ();
354
355         mono_thread_cleanup ();
356
357 #ifndef DISABLE_SOCKETS
358         mono_network_cleanup ();
359 #endif
360         mono_marshal_cleanup ();
361
362         mono_type_initialization_cleanup ();
363
364         mono_monitor_cleanup ();
365 }
366
367 static MonoDomainFunc quit_function = NULL;
368
369 void
370 mono_install_runtime_cleanup (MonoDomainFunc func)
371 {
372         quit_function = func;
373 }
374
375 void
376 mono_runtime_quit ()
377 {
378         if (quit_function != NULL)
379                 quit_function (mono_get_root_domain (), NULL);
380 }
381
382 /**
383  * mono_domain_create_appdomain:
384  * @friendly_name: The friendly name of the appdomain to create
385  * @configuration_file: The configuration file to initialize the appdomain with
386  * 
387  * Returns a MonoDomain initialized with the appdomain
388  */
389 MonoDomain *
390 mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
391 {
392         MonoAppDomain *ad;
393         MonoAppDomainSetup *setup;
394         MonoClass *class;
395
396         class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
397         setup = (MonoAppDomainSetup *) mono_object_new (mono_domain_get (), class);
398         setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL;
399
400         ad = mono_domain_create_appdomain_internal (friendly_name, setup);
401
402         return mono_domain_from_appdomain (ad);
403 }
404
405 static MonoAppDomainSetup*
406 copy_app_domain_setup (MonoDomain *domain, MonoAppDomainSetup *setup)
407 {
408         MonoDomain *caller_domain = mono_domain_get ();
409         MonoClass *ads_class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
410         MonoAppDomainSetup *copy = (MonoAppDomainSetup*)mono_object_new (domain, ads_class);
411
412         mono_domain_set_internal (domain);
413
414         MONO_OBJECT_SETREF (copy, application_base, mono_marshal_xdomain_copy_value ((MonoObject*)setup->application_base));
415         MONO_OBJECT_SETREF (copy, application_name, mono_marshal_xdomain_copy_value ((MonoObject*)setup->application_name));
416         MONO_OBJECT_SETREF (copy, cache_path, mono_marshal_xdomain_copy_value ((MonoObject*)setup->cache_path));
417         MONO_OBJECT_SETREF (copy, configuration_file, mono_marshal_xdomain_copy_value ((MonoObject*)setup->configuration_file));
418         MONO_OBJECT_SETREF (copy, dynamic_base, mono_marshal_xdomain_copy_value ((MonoObject*)setup->dynamic_base));
419         MONO_OBJECT_SETREF (copy, license_file, mono_marshal_xdomain_copy_value ((MonoObject*)setup->license_file));
420         MONO_OBJECT_SETREF (copy, private_bin_path, mono_marshal_xdomain_copy_value ((MonoObject*)setup->private_bin_path));
421         MONO_OBJECT_SETREF (copy, private_bin_path_probe, mono_marshal_xdomain_copy_value ((MonoObject*)setup->private_bin_path_probe));
422         MONO_OBJECT_SETREF (copy, shadow_copy_directories, mono_marshal_xdomain_copy_value ((MonoObject*)setup->shadow_copy_directories));
423         MONO_OBJECT_SETREF (copy, shadow_copy_files, mono_marshal_xdomain_copy_value ((MonoObject*)setup->shadow_copy_files));
424         copy->publisher_policy = setup->publisher_policy;
425         copy->path_changed = setup->path_changed;
426         copy->loader_optimization = setup->loader_optimization;
427         copy->disallow_binding_redirects = setup->disallow_binding_redirects;
428         copy->disallow_code_downloads = setup->disallow_code_downloads;
429         MONO_OBJECT_SETREF (copy, domain_initializer_args, mono_marshal_xdomain_copy_value ((MonoObject*)setup->domain_initializer_args));
430         copy->disallow_appbase_probe = setup->disallow_appbase_probe;
431         MONO_OBJECT_SETREF (copy, application_trust, mono_marshal_xdomain_copy_value ((MonoObject*)setup->application_trust));
432         MONO_OBJECT_SETREF (copy, configuration_bytes, mono_marshal_xdomain_copy_value ((MonoObject*)setup->configuration_bytes));
433         MONO_OBJECT_SETREF (copy, serialized_non_primitives, mono_marshal_xdomain_copy_value ((MonoObject*)setup->serialized_non_primitives));
434
435         mono_domain_set_internal (caller_domain);
436
437         return copy;
438 }
439
440 static MonoAppDomain *
441 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup)
442 {
443         MonoError error;
444         MonoClass *adclass;
445         MonoAppDomain *ad;
446         MonoDomain *data;
447         char *shadow_location;
448         
449         MONO_ARCH_SAVE_REGS;
450
451         adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
452
453         /* FIXME: pin all those objects */
454         data = mono_domain_create();
455
456         ad = (MonoAppDomain *) mono_object_new (data, adclass);
457         ad->data = data;
458         data->domain = ad;
459         data->friendly_name = g_strdup (friendly_name);
460
461         if (!setup->application_base) {
462                 /* Inherit from the root domain since MS.NET does this */
463                 MonoDomain *root = mono_get_root_domain ();
464                 if (root->setup->application_base)
465                         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)));
466         }
467
468         mono_context_init (data);
469
470         data->setup = copy_app_domain_setup (data, setup);
471         mono_set_private_bin_path_from_config (data);
472         add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
473
474 #ifndef DISABLE_SHADOW_COPY
475         /*FIXME, guard this for when the debugger is not running */
476         shadow_location = get_shadow_assembly_location_base (data, &error);
477         if (!mono_error_ok (&error))
478                 mono_error_raise_exception (&error);
479         mono_debugger_event_create_appdomain (data, shadow_location);
480         g_free (shadow_location);
481 #endif
482
483         create_domain_objects (data);
484
485         return ad;
486 }
487
488 /**
489  * mono_domain_has_type_resolve:
490  * @domain: application domains being looked up
491  *
492  * Returns true if the AppDomain.TypeResolve field has been
493  * set.
494  */
495 gboolean
496 mono_domain_has_type_resolve (MonoDomain *domain)
497 {
498         static MonoClassField *field = NULL;
499         MonoObject *o;
500
501         if (field == NULL) {
502                 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
503                 g_assert (field);
504         }
505
506         /*pedump doesn't create an appdomin, so the domain object doesn't exist.*/
507         if (!domain->domain)
508                 return FALSE;
509
510         mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
511         return o != NULL;
512 }
513
514 /**
515  * mono_domain_try_type_resolve:
516  * @domain: application domainwhere the name where the type is going to be resolved
517  * @name: the name of the type to resolve or NULL.
518  * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
519  *
520  * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
521  * the assembly that matches name.
522  *
523  * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
524  *
525  * Returns: A MonoReflectionAssembly or NULL if not found
526  */
527 MonoReflectionAssembly *
528 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
529 {
530         MonoClass *klass;
531         void *params [1];
532         static MonoMethod *method = NULL;
533
534         g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
535
536         if (method == NULL) {
537                 klass = domain->domain->mbr.obj.vtable->klass;
538                 g_assert (klass);
539
540                 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
541                 if (method == NULL) {
542                         g_warning ("Method AppDomain.DoTypeResolve not found.\n");
543                         return NULL;
544                 }
545         }
546
547         if (name)
548                 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
549         else
550                 *params = tb;
551         return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
552 }
553
554 /**
555  * mono_domain_owns_vtable_slot:
556  *
557  *  Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
558  */
559 gboolean
560 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
561 {
562         gboolean res;
563
564         mono_domain_lock (domain);
565         res = mono_mempool_contains_addr (domain->mp, vtable_slot);
566         mono_domain_unlock (domain);
567         return res;
568 }
569
570 /**
571  * mono_domain_set:
572  * @domain: domain
573  * @force: force setting.
574  *
575  * Set the current appdomain to @domain. If @force is set, set it even
576  * if it is being unloaded.
577  *
578  * Returns:
579  *   TRUE on success;
580  *   FALSE if the domain is unloaded
581  */
582 gboolean
583 mono_domain_set (MonoDomain *domain, gboolean force)
584 {
585         if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
586                 return FALSE;
587
588         mono_domain_set_internal (domain);
589
590         return TRUE;
591 }
592
593 MonoObject *
594 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
595 {
596         MonoDomain *add;
597         MonoObject *o;
598         char *str;
599
600         MONO_ARCH_SAVE_REGS;
601
602         g_assert (ad != NULL);
603         add = ad->data;
604         g_assert (add != NULL);
605
606         if (name == NULL)
607                 mono_raise_exception (mono_get_exception_argument_null ("name"));
608
609         str = mono_string_to_utf8 (name);
610
611         mono_domain_lock (add);
612
613         if (!strcmp (str, "APPBASE"))
614                 o = (MonoObject *)add->setup->application_base;
615         else if (!strcmp (str, "APP_CONFIG_FILE"))
616                 o = (MonoObject *)add->setup->configuration_file;
617         else if (!strcmp (str, "DYNAMIC_BASE"))
618                 o = (MonoObject *)add->setup->dynamic_base;
619         else if (!strcmp (str, "APP_NAME"))
620                 o = (MonoObject *)add->setup->application_name;
621         else if (!strcmp (str, "CACHE_BASE"))
622                 o = (MonoObject *)add->setup->cache_path;
623         else if (!strcmp (str, "PRIVATE_BINPATH"))
624                 o = (MonoObject *)add->setup->private_bin_path;
625         else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
626                 o = (MonoObject *)add->setup->private_bin_path_probe;
627         else if (!strcmp (str, "SHADOW_COPY_DIRS"))
628                 o = (MonoObject *)add->setup->shadow_copy_directories;
629         else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
630                 o = (MonoObject *)add->setup->shadow_copy_files;
631         else 
632                 o = mono_g_hash_table_lookup (add->env, name);
633
634         mono_domain_unlock (add);
635         g_free (str);
636
637         if (!o)
638                 return NULL;
639
640         return o;
641 }
642
643 void
644 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
645 {
646         MonoDomain *add;
647
648         MONO_ARCH_SAVE_REGS;
649
650         g_assert (ad != NULL);
651         add = ad->data;
652         g_assert (add != NULL);
653
654         if (name == NULL)
655                 mono_raise_exception (mono_get_exception_argument_null ("name"));
656
657         mono_domain_lock (add);
658
659         mono_g_hash_table_insert (add->env, name, data);
660
661         mono_domain_unlock (add);
662 }
663
664 MonoAppDomainSetup *
665 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
666 {
667         MONO_ARCH_SAVE_REGS;
668
669         g_assert (ad != NULL);
670         g_assert (ad->data != NULL);
671
672         return ad->data->setup;
673 }
674
675 MonoString *
676 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
677 {
678         MONO_ARCH_SAVE_REGS;
679
680         g_assert (ad != NULL);
681         g_assert (ad->data != NULL);
682
683         return mono_string_new (ad->data, ad->data->friendly_name);
684 }
685
686 MonoAppDomain *
687 ves_icall_System_AppDomain_getCurDomain ()
688 {
689         MonoDomain *add = mono_domain_get ();
690
691         MONO_ARCH_SAVE_REGS;
692
693         return add->domain;
694 }
695
696 MonoAppDomain *
697 ves_icall_System_AppDomain_getRootDomain ()
698 {
699         MonoDomain *root = mono_get_root_domain ();
700
701         MONO_ARCH_SAVE_REGS;
702
703         return root->domain;
704 }
705
706 static char*
707 get_attribute_value (const gchar **attribute_names, 
708                      const gchar **attribute_values, 
709                      const char *att_name)
710 {
711         int n;
712         for (n = 0; attribute_names [n] != NULL; n++) {
713                 if (strcmp (attribute_names [n], att_name) == 0)
714                         return g_strdup (attribute_values [n]);
715         }
716         return NULL;
717 }
718
719 static void
720 start_element (GMarkupParseContext *context, 
721                const gchar         *element_name,
722                const gchar        **attribute_names,
723                const gchar        **attribute_values,
724                gpointer             user_data,
725                GError             **error)
726 {
727         RuntimeConfig *runtime_config = user_data;
728         
729         if (strcmp (element_name, "runtime") == 0) {
730                 runtime_config->runtime_count++;
731                 return;
732         }
733
734         if (strcmp (element_name, "assemblyBinding") == 0) {
735                 runtime_config->assemblybinding_count++;
736                 return;
737         }
738         
739         if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
740                 return;
741
742         if (strcmp (element_name, "probing") != 0)
743                 return;
744
745         g_free (runtime_config->domain->private_bin_path);
746         runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
747         if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
748                 g_free (runtime_config->domain->private_bin_path);
749                 runtime_config->domain->private_bin_path = NULL;
750                 return;
751         }
752 }
753
754 static void
755 end_element (GMarkupParseContext *context,
756              const gchar         *element_name,
757              gpointer             user_data,
758              GError             **error)
759 {
760         RuntimeConfig *runtime_config = user_data;
761         if (strcmp (element_name, "runtime") == 0)
762                 runtime_config->runtime_count--;
763         else if (strcmp (element_name, "assemblyBinding") == 0)
764                 runtime_config->assemblybinding_count--;
765 }
766
767 static void
768 parse_error   (GMarkupParseContext *context, GError *error, gpointer user_data)
769 {
770         RuntimeConfig *state = user_data;
771         const gchar *msg;
772         const gchar *filename;
773
774         filename = state && state->filename ? (gchar *) state->filename : "<unknown>";
775         msg = error && error->message ? error->message : "";
776         g_warning ("Error parsing %s: %s", filename, msg);
777 }
778
779 static const GMarkupParser
780 mono_parser = {
781         start_element,
782         end_element,
783         NULL,
784         NULL,
785         parse_error
786 };
787
788 void
789 mono_set_private_bin_path_from_config (MonoDomain *domain)
790 {
791         MonoError error;
792         gchar *config_file_name = NULL, *text = NULL, *config_file_path = NULL;
793         gsize len;
794         GMarkupParseContext *context;
795         RuntimeConfig runtime_config;
796         gint offset;
797         
798         if (!domain || !domain->setup || !domain->setup->configuration_file)
799                 return;
800
801         config_file_name = mono_string_to_utf8_checked (domain->setup->configuration_file, &error);
802         if (!mono_error_ok (&error)) {
803                 mono_error_cleanup (&error);
804                 goto free_and_out;
805         }
806
807         config_file_path = mono_portability_find_file (config_file_name, TRUE);
808         if (!config_file_path)
809                 config_file_path = config_file_name;
810
811         if (!g_file_get_contents (config_file_path, &text, &len, NULL))
812                 goto free_and_out;
813
814         runtime_config.runtime_count = 0;
815         runtime_config.assemblybinding_count = 0;
816         runtime_config.domain = domain;
817         runtime_config.filename = config_file_path;
818         
819         offset = 0;
820         if (len > 3 && text [0] == '\xef' && text [1] == (gchar) '\xbb' && text [2] == '\xbf')
821                 offset = 3; /* Skip UTF-8 BOM */
822
823         context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
824         if (g_markup_parse_context_parse (context, text + offset, len - offset, NULL))
825                 g_markup_parse_context_end_parse (context, NULL);
826         g_markup_parse_context_free (context);
827
828   free_and_out:
829         g_free (text);
830         if (config_file_name != config_file_path)
831                 g_free (config_file_name);
832         g_free (config_file_path);
833 }
834
835 MonoAppDomain *
836 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
837 {
838 #ifdef DISABLE_APPDOMAINS
839         mono_raise_exception (mono_get_exception_not_supported ("AppDomain creation is not supported on this runtime."));
840         return NULL;
841 #else
842         char *fname = mono_string_to_utf8 (friendly_name);
843         MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
844         
845         g_free (fname);
846
847         return ad;
848 #endif
849 }
850
851 MonoArray *
852 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
853 {
854         MonoDomain *domain = ad->data; 
855         MonoAssembly* ass;
856         static MonoClass *System_Reflection_Assembly;
857         MonoArray *res;
858         GSList *tmp;
859         int i;
860         GPtrArray *assemblies;
861
862         MONO_ARCH_SAVE_REGS;
863
864         if (!System_Reflection_Assembly)
865                 System_Reflection_Assembly = mono_class_from_name (
866                         mono_defaults.corlib, "System.Reflection", "Assembly");
867
868         /* 
869          * Make a copy of the list of assemblies because we can't hold the assemblies
870          * lock while creating objects etc.
871          */
872         assemblies = g_ptr_array_new ();
873         /* Need to skip internal assembly builders created by remoting */
874         mono_domain_assemblies_lock (domain);
875         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
876                 ass = tmp->data;
877                 if (refonly != ass->ref_only)
878                         continue;
879                 if (ass->corlib_internal)
880                         continue;
881                 g_ptr_array_add (assemblies, ass);
882         }
883         mono_domain_assemblies_unlock (domain);
884
885         res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
886         for (i = 0; i < assemblies->len; ++i) {
887                 ass = g_ptr_array_index (assemblies, i);
888                 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
889         }
890
891         g_ptr_array_free (assemblies, TRUE);
892
893         return res;
894 }
895
896 MonoReflectionAssembly *
897 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
898 {
899         MonoClass *klass;
900         MonoMethod *method;
901         MonoBoolean isrefonly;
902         gpointer params [2];
903
904         if (mono_runtime_get_no_exec ())
905                 return NULL;
906
907         g_assert (domain != NULL && fname != NULL);
908
909         klass = domain->domain->mbr.obj.vtable->klass;
910         g_assert (klass);
911         
912         method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
913         if (method == NULL) {
914                 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
915                 return NULL;
916         }
917
918         isrefonly = refonly ? 1 : 0;
919         params [0] = fname;
920         params [1] = &isrefonly;
921         return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
922 }
923
924 static MonoAssembly *
925 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
926                                                                           gpointer user_data)
927 {
928         gboolean refonly = GPOINTER_TO_UINT (user_data);
929         MonoReflectionAssembly *assembly;
930         MonoDomain *domain = mono_domain_get ();
931         char *aname_str;
932         MonoString *str;
933
934         aname_str = mono_stringify_assembly_name (aname);
935
936         /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
937         str = mono_string_new (domain, aname_str);
938         if (!str) {
939                 g_free (aname_str);
940                 return NULL;
941         }
942         assembly = mono_try_assembly_resolve (domain, str, refonly);
943         g_free (aname_str);
944
945         if (assembly)
946                 return assembly->assembly;
947         else
948                 return NULL;
949 }
950         
951 /*
952  * LOCKING: assumes assemblies_lock in the domain is already locked.
953  */
954 static void
955 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
956 {
957         gint i;
958         GSList *tmp;
959         gboolean destroy_ht = FALSE;
960
961         if (!ass->aname.name)
962                 return;
963
964         if (!ht) {
965                 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
966                 destroy_ht = TRUE;
967         }
968
969         /* FIXME: handle lazy loaded assemblies */
970         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
971                 g_hash_table_insert (ht, tmp->data, tmp->data);
972         }
973         if (!g_hash_table_lookup (ht, ass)) {
974                 mono_assembly_addref (ass);
975                 g_hash_table_insert (ht, ass, ass);
976                 domain->domain_assemblies = g_slist_append (domain->domain_assemblies, ass);
977                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly %s[%p] added to domain %s, ref_count=%d", ass->aname.name, ass, domain->friendly_name, ass->ref_count);
978         }
979
980         if (ass->image->references) {
981                 for (i = 0; ass->image->references [i] != NULL; i++) {
982                         if (ass->image->references [i] != REFERENCE_MISSING)
983                                 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
984                                         add_assemblies_to_domain (domain, ass->image->references [i], ht);
985                                 }
986                 }
987         }
988         if (destroy_ht)
989                 g_hash_table_destroy (ht);
990 }
991
992 static void
993 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
994 {
995         static MonoClassField *assembly_load_field;
996         static MonoMethod *assembly_load_method;
997         MonoDomain *domain = mono_domain_get ();
998         MonoReflectionAssembly *ref_assembly;
999         MonoClass *klass;
1000         gpointer load_value;
1001         void *params [1];
1002
1003         if (!domain->domain)
1004                 /* This can happen during startup */
1005                 return;
1006 #ifdef ASSEMBLY_LOAD_DEBUG
1007         fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
1008 #endif
1009         klass = domain->domain->mbr.obj.vtable->klass;
1010
1011         mono_domain_assemblies_lock (domain);
1012         add_assemblies_to_domain (domain, assembly, NULL);
1013         mono_domain_assemblies_unlock (domain);
1014
1015         if (assembly_load_field == NULL) {
1016                 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
1017                 g_assert (assembly_load_field);
1018         }
1019
1020         mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
1021         if (load_value == NULL) {
1022                 /* No events waiting to be triggered */
1023                 return;
1024         }
1025
1026         ref_assembly = mono_assembly_get_object (domain, assembly);
1027         g_assert (ref_assembly);
1028
1029         if (assembly_load_method == NULL) {
1030                 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
1031                 g_assert (assembly_load_method);
1032         }
1033
1034         *params = ref_assembly;
1035         mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
1036 }
1037
1038 /*
1039  * LOCKING: Acquires the domain assemblies lock.
1040  */
1041 static void
1042 set_domain_search_path (MonoDomain *domain)
1043 {
1044         MonoError error;
1045         MonoAppDomainSetup *setup;
1046         gchar **tmp;
1047         gchar *search_path = NULL;
1048         gint i;
1049         gint npaths = 0;
1050         gchar **pvt_split = NULL;
1051         GError *gerror = NULL;
1052         gint appbaselen = -1;
1053
1054         /* 
1055          * We use the low-level domain assemblies lock, since this is called from
1056          * assembly loads hooks, which means this thread might hold the loader lock.
1057          */
1058         mono_domain_assemblies_lock (domain);
1059
1060         if (!domain->setup) {
1061                 mono_domain_assemblies_unlock (domain);
1062                 return;
1063         }
1064
1065         if ((domain->search_path != NULL) && !domain->setup->path_changed) {
1066                 mono_domain_assemblies_unlock (domain);
1067                 return;
1068         }
1069         setup = domain->setup;
1070         if (!setup->application_base) {
1071                 mono_domain_assemblies_unlock (domain);
1072                 return; /* Must set application base to get private path working */
1073         }
1074
1075         npaths++;
1076         
1077         if (setup->private_bin_path) {
1078                 search_path = mono_string_to_utf8_checked (setup->private_bin_path, &error);
1079                 if (!mono_error_ok (&error)) { /*FIXME maybe we should bubble up the error.*/
1080                         g_warning ("Could not decode AppDomain search path since it contains invalid characters");
1081                         mono_error_cleanup (&error);
1082                         mono_domain_assemblies_unlock (domain);
1083                         return;
1084                 }
1085         }
1086         
1087         if (domain->private_bin_path) {
1088                 if (search_path == NULL)
1089                         search_path = domain->private_bin_path;
1090                 else {
1091                         gchar *tmp2 = search_path;
1092                         search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
1093                         g_free (tmp2);
1094                 }
1095         }
1096         
1097         if (search_path) {
1098                 /*
1099                  * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
1100                  * directories relative to ApplicationBase separated by semicolons (see
1101                  * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
1102                  * The loop below copes with the fact that some Unix applications may use ':' (or
1103                  * System.IO.Path.PathSeparator) as the path search separator. We replace it with
1104                  * ';' for the subsequent split.
1105                  *
1106                  * The issue was reported in bug #81446
1107                  */
1108
1109 #ifndef TARGET_WIN32
1110                 gint slen;
1111
1112                 slen = strlen (search_path);
1113                 for (i = 0; i < slen; i++)
1114                         if (search_path [i] == ':')
1115                                 search_path [i] = ';';
1116 #endif
1117                 
1118                 pvt_split = g_strsplit (search_path, ";", 1000);
1119                 g_free (search_path);
1120                 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1121         }
1122
1123         if (!npaths) {
1124                 if (pvt_split)
1125                         g_strfreev (pvt_split);
1126                 /*
1127                  * Don't do this because the first time is called, the domain
1128                  * setup is not finished.
1129                  *
1130                  * domain->search_path = g_malloc (sizeof (char *));
1131                  * domain->search_path [0] = NULL;
1132                 */
1133                 mono_domain_assemblies_unlock (domain);
1134                 return;
1135         }
1136
1137         if (domain->search_path)
1138                 g_strfreev (domain->search_path);
1139
1140         tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
1141         tmp [npaths] = NULL;
1142
1143         *tmp = mono_string_to_utf8_checked (setup->application_base, &error);
1144         if (!mono_error_ok (&error)) {
1145                 mono_error_cleanup (&error);
1146                 g_strfreev (pvt_split);
1147                 g_free (tmp);
1148
1149                 mono_domain_assemblies_unlock (domain);
1150                 return;
1151         }
1152
1153         domain->search_path = tmp;
1154
1155         /* FIXME: is this needed? */
1156         if (strncmp (*tmp, "file://", 7) == 0) {
1157                 gchar *file = *tmp;
1158                 gchar *uri = *tmp;
1159                 gchar *tmpuri;
1160
1161                 if (uri [7] != '/')
1162                         uri = g_strdup_printf ("file:///%s", uri + 7);
1163
1164                 tmpuri = uri;
1165                 uri = mono_escape_uri_string (tmpuri);
1166                 *tmp = g_filename_from_uri (uri, NULL, &gerror);
1167                 g_free (uri);
1168
1169                 if (tmpuri != file)
1170                         g_free (tmpuri);
1171
1172                 if (gerror != NULL) {
1173                         g_warning ("%s\n", gerror->message);
1174                         g_error_free (gerror);
1175                         *tmp = file;
1176                 } else {
1177                         g_free (file);
1178                 }
1179         }
1180
1181         for (i = 1; pvt_split && i < npaths; i++) {
1182                 if (g_path_is_absolute (pvt_split [i - 1])) {
1183                         tmp [i] = g_strdup (pvt_split [i - 1]);
1184                 } else {
1185                         tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1186                 }
1187
1188                 if (strchr (tmp [i], '.')) {
1189                         gchar *reduced;
1190                         gchar *freeme;
1191
1192                         reduced = mono_path_canonicalize (tmp [i]);
1193                         if (appbaselen == -1)
1194                                 appbaselen = strlen (tmp [0]);
1195
1196                         if (strncmp (tmp [0], reduced, appbaselen)) {
1197                                 g_free (reduced);
1198                                 g_free (tmp [i]);
1199                                 tmp [i] = g_strdup ("");
1200                                 continue;
1201                         }
1202
1203                         freeme = tmp [i];
1204                         tmp [i] = reduced;
1205                         g_free (freeme);
1206                 }
1207         }
1208         
1209         if (setup->private_bin_path_probe != NULL) {
1210                 g_free (tmp [0]);
1211                 tmp [0] = g_strdup ("");
1212         }
1213                 
1214         domain->setup->path_changed = FALSE;
1215
1216         g_strfreev (pvt_split);
1217
1218         mono_domain_assemblies_unlock (domain);
1219 }
1220
1221 #ifdef DISABLE_SHADOW_COPY
1222 gboolean
1223 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1224 {
1225         return FALSE;
1226 }
1227
1228 char *
1229 mono_make_shadow_copy (const char *filename)
1230 {
1231         return (char *) filename;
1232 }
1233 #else
1234 static gboolean
1235 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1236 {
1237         guint16 *orig, *dest;
1238         gboolean copy_result;
1239         
1240         strcpy (src + srclen - tail_len, extension);
1241
1242         if (IS_PORTABILITY_CASE) {
1243                 gchar *file = mono_portability_find_file (src, TRUE);
1244
1245                 if (file == NULL)
1246                         return TRUE;
1247
1248                 g_free (file);
1249         } else if (!g_file_test (src, G_FILE_TEST_IS_REGULAR)) {
1250                 return TRUE;
1251         }
1252
1253         orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1254
1255         strcpy (target + targetlen - tail_len, extension);
1256         dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1257         
1258         DeleteFile (dest);
1259         copy_result = CopyFile (orig, dest, FALSE);
1260
1261         /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
1262          * overwritten when updated in their original locations. */
1263         if (copy_result)
1264                 copy_result = SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);
1265
1266         g_free (orig);
1267         g_free (dest);
1268         
1269         return copy_result;
1270 }
1271
1272 static gint32 
1273 get_cstring_hash (const char *str)
1274 {
1275         int len, i;
1276         const char *p;
1277         gint32 h = 0;
1278         
1279         if (!str || !str [0])
1280                 return 0;
1281                 
1282         len = strlen (str);
1283         p = str;
1284         for (i = 0; i < len; i++) {
1285                 h = (h << 5) - h + *p;
1286                 p++;
1287         }
1288         
1289         return h;
1290 }
1291
1292 /*
1293  * Returned memory is malloc'd. Called must free it 
1294  */
1295 static char *
1296 get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error)
1297 {
1298         MonoAppDomainSetup *setup;
1299         char *cache_path, *appname;
1300         char *userdir;
1301         char *location;
1302
1303         mono_error_init (error);
1304         
1305         setup = domain->setup;
1306         if (setup->cache_path != NULL && setup->application_name != NULL) {
1307                 cache_path = mono_string_to_utf8_checked (setup->cache_path, error);
1308                 if (!mono_error_ok (error))
1309                         return NULL;
1310 #ifndef TARGET_WIN32
1311                 {
1312                         gint i;
1313                         for (i = strlen (cache_path) - 1; i >= 0; i--)
1314                                 if (cache_path [i] == '\\')
1315                                         cache_path [i] = '/';
1316                 }
1317 #endif
1318
1319                 appname = mono_string_to_utf8_checked (setup->application_name, error);
1320                 if (!mono_error_ok (error)) {
1321                         g_free (cache_path);
1322                         return NULL;
1323                 }
1324
1325                 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1326                 g_free (appname);
1327                 g_free (cache_path);
1328         } else {
1329                 userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1330                 location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL);
1331                 g_free (userdir);
1332         }
1333         return location;
1334 }
1335
1336 static char *
1337 get_shadow_assembly_location (const char *filename, MonoError *error)
1338 {
1339         gint32 hash = 0, hash2 = 0;
1340         char name_hash [9];
1341         char path_hash [30];
1342         char *bname = g_path_get_basename (filename);
1343         char *dirname = g_path_get_dirname (filename);
1344         char *location, *tmploc;
1345         MonoDomain *domain = mono_domain_get ();
1346
1347         mono_error_init (error);
1348         
1349         hash = get_cstring_hash (bname);
1350         hash2 = get_cstring_hash (dirname);
1351         g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1352         g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1353         tmploc = get_shadow_assembly_location_base (domain, error);
1354         if (!mono_error_ok (error)) {
1355                 g_free (bname);
1356                 g_free (dirname);
1357                 return NULL;
1358         }
1359
1360         location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
1361         g_free (tmploc);
1362         g_free (bname);
1363         g_free (dirname);
1364         return location;
1365 }
1366
1367 static gboolean
1368 ensure_directory_exists (const char *filename)
1369 {
1370 #ifdef HOST_WIN32
1371         gchar *dir_utf8 = g_path_get_dirname (filename);
1372         gunichar2 *p;
1373         gunichar2 *dir_utf16 = NULL;
1374         int retval;
1375         
1376         if (!dir_utf8 || !dir_utf8 [0])
1377                 return FALSE;
1378
1379         dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1380         g_free (dir_utf8);
1381
1382         if (!dir_utf16)
1383                 return FALSE;
1384
1385         p = dir_utf16;
1386
1387         /* make life easy and only use one directory seperator */
1388         while (*p != '\0')
1389         {
1390                 if (*p == '/')
1391                         *p = '\\';
1392                 p++;
1393         }
1394
1395         p = dir_utf16;
1396
1397         /* get past C:\ )*/
1398         while (*p++ != '\\')    
1399         {
1400         }
1401
1402         while (1) {
1403                 BOOL bRet = FALSE;
1404                 p = wcschr (p, '\\');
1405                 if (p)
1406                         *p = '\0';
1407                 retval = _wmkdir (dir_utf16);
1408                 if (retval != 0 && errno != EEXIST) {
1409                         g_free (dir_utf16);
1410                         return FALSE;
1411                 }
1412                 if (!p)
1413                         break;
1414                 *p++ = '\\';
1415         }
1416         
1417         g_free (dir_utf16);
1418         return TRUE;
1419 #else
1420         char *p;
1421         gchar *dir = g_path_get_dirname (filename);
1422         int retval;
1423         struct stat sbuf;
1424         
1425         if (!dir || !dir [0]) {
1426                 g_free (dir);
1427                 return FALSE;
1428         }
1429         
1430         if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1431                 g_free (dir);
1432                 return TRUE;
1433         }
1434         
1435         p = dir;
1436         while (*p == '/')
1437                 p++;
1438
1439         while (1) {
1440                 p = strchr (p, '/');
1441                 if (p)
1442                         *p = '\0';
1443                 retval = mkdir (dir, 0777);
1444                 if (retval != 0 && errno != EEXIST) {
1445                         g_free (dir);
1446                         return FALSE;
1447                 }
1448                 if (!p)
1449                         break;
1450                 *p++ = '/';
1451         }
1452         
1453         g_free (dir);
1454         return TRUE;
1455 #endif
1456 }
1457
1458 static gboolean
1459 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1460 {
1461         struct stat sbuf_dest;
1462         gchar *real_src = mono_portability_find_file (src, TRUE);
1463
1464         if (!real_src)
1465                 real_src = (gchar*)src;
1466         
1467         if (stat (real_src, sbuf_src) == -1) {
1468                 time_t tnow = time (NULL);
1469                 memset (sbuf_src, 0, sizeof (*sbuf_src));
1470                 sbuf_src->st_mtime = tnow;
1471                 sbuf_src->st_atime = tnow;
1472                 return TRUE;
1473         }
1474
1475         if (stat (dest, &sbuf_dest) == -1)
1476                 return TRUE;
1477         
1478         if (sbuf_src->st_size == sbuf_dest.st_size &&
1479             sbuf_src->st_mtime == sbuf_dest.st_mtime)
1480                 return FALSE;
1481
1482         return TRUE;
1483 }
1484
1485 static gboolean
1486 shadow_copy_create_ini (const char *shadow, const char *filename)
1487 {
1488         char *dir_name;
1489         char *ini_file;
1490         guint16 *u16_ini;
1491         gboolean result;
1492         guint32 n;
1493         HANDLE *handle;
1494         gchar *full_path;
1495
1496         dir_name = g_path_get_dirname (shadow);
1497         ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1498         g_free (dir_name);
1499         if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1500                 g_free (ini_file);
1501                 return TRUE;
1502         }
1503
1504         u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1505         g_free (ini_file);
1506         if (!u16_ini) {
1507                 return FALSE;
1508         }
1509         handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1510                                 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1511         g_free (u16_ini);
1512         if (handle == INVALID_HANDLE_VALUE) {
1513                 return FALSE;
1514         }
1515
1516         full_path = mono_path_resolve_symlinks (filename);
1517         result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1518         g_free (full_path);
1519         CloseHandle (handle);
1520         return result;
1521 }
1522
1523 gboolean
1524 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1525 {
1526         MonoError error;
1527         MonoAppDomainSetup *setup;
1528         gchar *all_dirs;
1529         gchar **dir_ptr;
1530         gchar **directories;
1531         gchar *shadow_status_string;
1532         gchar *base_dir;
1533         gboolean shadow_enabled;
1534         gboolean found = FALSE;
1535
1536         if (domain == NULL)
1537                 return FALSE;
1538
1539         setup = domain->setup;
1540         if (setup == NULL || setup->shadow_copy_files == NULL)
1541                 return FALSE;
1542
1543         shadow_status_string = mono_string_to_utf8_checked (setup->shadow_copy_files, &error);
1544         if (!mono_error_ok (&error)) {
1545                 mono_error_cleanup (&error);
1546                 return FALSE;
1547         }
1548         shadow_enabled = !g_ascii_strncasecmp (shadow_status_string, "true", 4);
1549         g_free (shadow_status_string);
1550
1551         if (!shadow_enabled)
1552                 return FALSE;
1553
1554         if (setup->shadow_copy_directories == NULL)
1555                 return TRUE;
1556
1557         /* Is dir_name a shadow_copy destination already? */
1558         base_dir = get_shadow_assembly_location_base (domain, &error);
1559         if (!mono_error_ok (&error)) {
1560                 mono_error_cleanup (&error);
1561                 return FALSE;
1562         }
1563
1564         if (strstr (dir_name, base_dir)) {
1565                 g_free (base_dir);
1566                 return TRUE;
1567         }
1568         g_free (base_dir);
1569
1570         all_dirs = mono_string_to_utf8_checked (setup->shadow_copy_directories, &error);
1571         if (!mono_error_ok (&error)) {
1572                 mono_error_cleanup (&error);
1573                 return FALSE;
1574         }
1575
1576         directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
1577         dir_ptr = directories;
1578         while (*dir_ptr) {
1579                 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1580                         found = TRUE;
1581                         break;
1582                 }
1583                 dir_ptr++;
1584         }
1585         g_strfreev (directories);
1586         g_free (all_dirs);
1587         return found;
1588 }
1589
1590 /*
1591 This function raises exceptions so it can cause as sorts of nasty stuff if called
1592 while holding a lock.
1593 FIXME bubble up the error instead of raising it here
1594 */
1595 char *
1596 mono_make_shadow_copy (const char *filename)
1597 {
1598         MonoError error;
1599         gchar *sibling_source, *sibling_target;
1600         gint sibling_source_len, sibling_target_len;
1601         guint16 *orig, *dest;
1602         char *shadow;
1603         gboolean copy_result;
1604         MonoException *exc;
1605         struct stat src_sbuf;
1606         struct utimbuf utbuf;
1607         char *dir_name = g_path_get_dirname (filename);
1608         MonoDomain *domain = mono_domain_get ();
1609         char *shadow_dir;
1610
1611         set_domain_search_path (domain);
1612
1613         if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
1614                 g_free (dir_name);
1615                 return (char *) filename;
1616         }
1617
1618         /* Is dir_name a shadow_copy destination already? */
1619         shadow_dir = get_shadow_assembly_location_base (domain, &error);
1620         if (!mono_error_ok (&error)) {
1621                 mono_error_cleanup (&error);
1622                 g_free (dir_name);
1623                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (invalid characters in shadow directory name).");
1624                 mono_raise_exception (exc);
1625         }
1626
1627         if (strstr (dir_name, shadow_dir)) {
1628                 g_free (shadow_dir);
1629                 g_free (dir_name);
1630                 return (char *) filename;
1631         }
1632         g_free (shadow_dir);
1633         g_free (dir_name);
1634
1635         shadow = get_shadow_assembly_location (filename, &error);
1636         if (!mono_error_ok (&error)) {
1637                 mono_error_cleanup (&error);
1638                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (invalid characters in file name).");
1639                 mono_raise_exception (exc);
1640         }
1641
1642         if (ensure_directory_exists (shadow) == FALSE) {
1643                 g_free (shadow);
1644                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1645                 mono_raise_exception (exc);
1646         }       
1647
1648         if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1649                 return (char*) shadow;
1650
1651         orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1652         dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1653         DeleteFile (dest);
1654         copy_result = CopyFile (orig, dest, FALSE);
1655
1656         /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
1657          * overwritten when updated in their original locations. */
1658         if (copy_result)
1659                 copy_result = SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);
1660
1661         g_free (dest);
1662         g_free (orig);
1663
1664         if (copy_result == FALSE) {
1665                 g_free (shadow);
1666                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1667                 mono_raise_exception (exc);
1668         }
1669
1670         /* attempt to copy .mdb, .config if they exist */
1671         sibling_source = g_strconcat (filename, ".config", NULL);
1672         sibling_source_len = strlen (sibling_source);
1673         sibling_target = g_strconcat (shadow, ".config", NULL);
1674         sibling_target_len = strlen (sibling_target);
1675         
1676         copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1677         if (copy_result == TRUE)
1678                 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1679         
1680         g_free (sibling_source);
1681         g_free (sibling_target);
1682         
1683         if (copy_result == FALSE)  {
1684                 g_free (shadow);
1685                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1686                 mono_raise_exception (exc);
1687         }
1688
1689         /* Create a .ini file containing the original assembly location */
1690         if (!shadow_copy_create_ini (shadow, filename)) {
1691                 g_free (shadow);
1692                 exc = mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1693                 mono_raise_exception (exc);
1694         }
1695
1696         utbuf.actime = src_sbuf.st_atime;
1697         utbuf.modtime = src_sbuf.st_mtime;
1698         utime (shadow, &utbuf);
1699         
1700         return shadow;
1701 }
1702 #endif /* DISABLE_SHADOW_COPY */
1703
1704 MonoDomain *
1705 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1706 {
1707         if (appdomain == NULL)
1708                 return NULL;
1709         
1710         return appdomain->data;
1711 }
1712
1713 static gboolean
1714 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1715                                         const gchar *path3, const gchar *path4,
1716                                         gboolean refonly, gboolean is_private)
1717 {
1718         gchar *fullpath;
1719         gboolean found = FALSE;
1720         
1721         *assembly = NULL;
1722         fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1723
1724         if (IS_PORTABILITY_SET) {
1725                 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1726                 if (new_fullpath) {
1727                         g_free (fullpath);
1728                         fullpath = new_fullpath;
1729                         found = TRUE;
1730                 }
1731         } else
1732                 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1733         
1734         if (found)
1735                 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1736
1737         g_free (fullpath);
1738         return (*assembly != NULL);
1739 }
1740
1741 static MonoAssembly *
1742 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1743 {
1744         MonoAssembly *result = NULL;
1745         gchar **path;
1746         gchar *filename;
1747         const gchar *local_culture;
1748         gint len;
1749         gboolean is_private = FALSE;
1750
1751         if (!culture || *culture == '\0') {
1752                 local_culture = "";
1753         } else {
1754                 local_culture = culture;
1755         }
1756
1757         filename =  g_strconcat (name, ".dll", NULL);
1758         len = strlen (filename);
1759
1760         for (path = search_path; *path; path++) {
1761                 if (**path == '\0') {
1762                         is_private = TRUE;
1763                         continue; /* Ignore empty ApplicationBase */
1764                 }
1765
1766                 /* See test cases in bug #58992 and bug #57710 */
1767                 /* 1st try: [culture]/[name].dll (culture may be empty) */
1768                 strcpy (filename + len - 4, ".dll");
1769                 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1770                         break;
1771
1772                 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1773                 strcpy (filename + len - 4, ".exe");
1774                 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1775                         break;
1776
1777                 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1778                 strcpy (filename + len - 4, ".dll");
1779                 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1780                         break;
1781
1782                 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1783                 strcpy (filename + len - 4, ".exe");
1784                 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1785                         break;
1786         }
1787
1788         g_free (filename);
1789         return result;
1790 }
1791
1792 /*
1793  * Try loading the assembly from ApplicationBase and PrivateBinPath 
1794  * and then from assemblies_path if any.
1795  * LOCKING: This is called from the assembly loading code, which means the caller
1796  * might hold the loader lock. Thus, this function must not acquire the domain lock.
1797  */
1798 static MonoAssembly *
1799 mono_domain_assembly_preload (MonoAssemblyName *aname,
1800                               gchar **assemblies_path,
1801                               gpointer user_data)
1802 {
1803         MonoDomain *domain = mono_domain_get ();
1804         MonoAssembly *result = NULL;
1805         gboolean refonly = GPOINTER_TO_UINT (user_data);
1806
1807         set_domain_search_path (domain);
1808
1809         if (domain->search_path && domain->search_path [0] != NULL) {
1810                 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1811         }
1812
1813         if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1814                 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1815         }
1816
1817         return result;
1818 }
1819
1820 /*
1821  * Check whenever a given assembly was already loaded in the current appdomain.
1822  */
1823 static MonoAssembly *
1824 mono_domain_assembly_search (MonoAssemblyName *aname,
1825                                                          gpointer user_data)
1826 {
1827         MonoDomain *domain = mono_domain_get ();
1828         GSList *tmp;
1829         MonoAssembly *ass;
1830         gboolean refonly = GPOINTER_TO_UINT (user_data);
1831
1832         mono_domain_assemblies_lock (domain);
1833         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1834                 ass = tmp->data;
1835                 /* Dynamic assemblies can't match here in MS.NET */
1836                 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1837                         continue;
1838
1839                 mono_domain_assemblies_unlock (domain);
1840                 return ass;
1841         }
1842         mono_domain_assemblies_unlock (domain);
1843
1844         return NULL;
1845 }
1846
1847 MonoReflectionAssembly *
1848 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1849 {
1850         MonoDomain *domain = mono_domain_get ();
1851         char *name, *filename;
1852         MonoImageOpenStatus status = MONO_IMAGE_OK;
1853         MonoAssembly *ass;
1854
1855         MONO_ARCH_SAVE_REGS;
1856
1857         if (fname == NULL) {
1858                 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1859                 mono_raise_exception (exc);
1860         }
1861                 
1862         name = filename = mono_string_to_utf8 (fname);
1863         
1864         ass = mono_assembly_open_full (filename, &status, refOnly);
1865         
1866         if (!ass){
1867                 MonoException *exc;
1868
1869                 if (status == MONO_IMAGE_IMAGE_INVALID)
1870                         exc = mono_get_exception_bad_image_format2 (NULL, fname);
1871                 else
1872                         exc = mono_get_exception_file_not_found2 (NULL, fname);
1873                 g_free (name);
1874                 mono_raise_exception (exc);
1875         }
1876
1877         g_free (name);
1878
1879         return mono_assembly_get_object (domain, ass);
1880 }
1881
1882 MonoReflectionAssembly *
1883 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad, 
1884                                             MonoArray *raw_assembly,
1885                                             MonoArray *raw_symbol_store, MonoObject *evidence,
1886                                             MonoBoolean refonly)
1887 {
1888         MonoAssembly *ass;
1889         MonoReflectionAssembly *refass = NULL;
1890         MonoDomain *domain = ad->data;
1891         MonoImageOpenStatus status;
1892         guint32 raw_assembly_len = mono_array_length (raw_assembly);
1893         MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1894
1895         if (!image) {
1896                 mono_raise_exception (mono_get_exception_bad_image_format (""));
1897                 return NULL;
1898         }
1899
1900         if (raw_symbol_store != NULL)
1901                 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1902
1903         ass = mono_assembly_load_from_full (image, "", &status, refonly);
1904
1905
1906         if (!ass) {
1907                 mono_image_close (image);
1908                 mono_raise_exception (mono_get_exception_bad_image_format (""));
1909                 return NULL; 
1910         }
1911
1912         refass = mono_assembly_get_object (domain, ass);
1913         MONO_OBJECT_SETREF (refass, evidence, evidence);
1914         return refass;
1915 }
1916
1917 MonoReflectionAssembly *
1918 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad,  MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1919 {
1920         MonoDomain *domain = ad->data; 
1921         MonoImageOpenStatus status = MONO_IMAGE_OK;
1922         MonoAssembly *ass;
1923         MonoAssemblyName aname;
1924         MonoReflectionAssembly *refass = NULL;
1925         gchar *name;
1926         gboolean parsed;
1927
1928         MONO_ARCH_SAVE_REGS;
1929
1930         g_assert (assRef != NULL);
1931
1932         name = mono_string_to_utf8 (assRef);
1933         parsed = mono_assembly_name_parse (name, &aname);
1934         g_free (name);
1935
1936         if (!parsed) {
1937                 /* This is a parse error... */
1938                 return NULL;
1939         }
1940
1941         ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1942         mono_assembly_name_free (&aname);
1943
1944         if (!ass) {
1945                 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1946                 if (!refOnly)
1947                         refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1948                 else
1949                         refass = NULL;
1950                 if (!refass) {
1951                         return NULL;
1952                 }
1953         }
1954
1955         if (refass == NULL)
1956                 refass = mono_assembly_get_object (domain, ass);
1957
1958         MONO_OBJECT_SETREF (refass, evidence, evidence);
1959         return refass;
1960 }
1961
1962 void
1963 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1964 {
1965         MonoDomain * domain = mono_domain_get_by_id (domain_id);
1966
1967         MONO_ARCH_SAVE_REGS;
1968
1969         if (NULL == domain) {
1970                 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1971                 mono_raise_exception (exc);
1972         }
1973         
1974         if (domain == mono_get_root_domain ()) {
1975                 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1976                 return;
1977         }
1978
1979         /* 
1980          * Unloading seems to cause problems when running NUnit/NAnt, hence
1981          * this workaround.
1982          */
1983         if (g_getenv ("MONO_NO_UNLOAD"))
1984                 return;
1985 #ifdef __native_client__
1986         return;
1987 #endif
1988
1989         mono_domain_unload (domain);
1990 }
1991
1992 gboolean
1993 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1994 {
1995         MonoDomain *domain = mono_domain_get_by_id (domain_id);
1996
1997         if (!domain)
1998                 return TRUE;
1999
2000         return mono_domain_is_unloading (domain);
2001 }
2002
2003 gint32
2004 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad, 
2005                                                                                         MonoReflectionAssembly *refass, MonoArray *args)
2006 {
2007         MonoImage *image;
2008         MonoMethod *method;
2009
2010         MONO_ARCH_SAVE_REGS;
2011
2012         g_assert (refass);
2013         image = refass->assembly->image;
2014         g_assert (image);
2015
2016         method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
2017
2018         if (!method)
2019                 g_error ("No entry point method found in %s", image->name);
2020
2021         if (!args)
2022                 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
2023
2024         return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
2025 }
2026
2027 gint32 
2028 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad) 
2029 {
2030         MONO_ARCH_SAVE_REGS;
2031
2032         return ad->data->domain_id;
2033 }
2034
2035 MonoAppDomain * 
2036 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
2037 {
2038         MonoDomain *old_domain = mono_domain_get();
2039
2040         MONO_ARCH_SAVE_REGS;
2041
2042         if (!mono_domain_set (ad->data, FALSE))
2043                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
2044
2045         return old_domain->domain;
2046 }
2047
2048 MonoAppDomain * 
2049 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
2050 {
2051         MonoDomain *current_domain = mono_domain_get ();
2052         MonoDomain *domain = mono_domain_get_by_id (domainid);
2053
2054         MONO_ARCH_SAVE_REGS;
2055
2056         if (!domain || !mono_domain_set (domain, FALSE))        
2057                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
2058
2059         return current_domain->domain;
2060 }
2061
2062 void
2063 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
2064 {
2065         MONO_ARCH_SAVE_REGS;
2066
2067         mono_thread_push_appdomain_ref (ad->data);
2068 }
2069
2070 void
2071 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
2072 {
2073         MonoDomain *domain = mono_domain_get_by_id (domain_id);
2074
2075         MONO_ARCH_SAVE_REGS;
2076
2077         if (!domain)
2078                 /* 
2079                  * Raise an exception to prevent the managed code from executing a pop
2080                  * later.
2081                  */
2082                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
2083
2084         mono_thread_push_appdomain_ref (domain);
2085 }
2086
2087 void
2088 ves_icall_System_AppDomain_InternalPopDomainRef (void)
2089 {
2090         MONO_ARCH_SAVE_REGS;
2091
2092         mono_thread_pop_appdomain_ref ();
2093 }
2094
2095 MonoAppContext * 
2096 ves_icall_System_AppDomain_InternalGetContext ()
2097 {
2098         MONO_ARCH_SAVE_REGS;
2099
2100         return mono_context_get ();
2101 }
2102
2103 MonoAppContext * 
2104 ves_icall_System_AppDomain_InternalGetDefaultContext ()
2105 {
2106         MONO_ARCH_SAVE_REGS;
2107
2108         return mono_domain_get ()->default_context;
2109 }
2110
2111 MonoAppContext * 
2112 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
2113 {
2114         MonoAppContext *old_context = mono_context_get ();
2115
2116         MONO_ARCH_SAVE_REGS;
2117
2118         mono_context_set (mc);
2119
2120         return old_context;
2121 }
2122
2123 MonoString *
2124 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
2125 {
2126         MonoDomain* mono_root_domain = mono_get_root_domain ();
2127         mono_domain_lock (mono_root_domain);
2128         if (process_guid_set) {
2129                 mono_domain_unlock (mono_root_domain);
2130                 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
2131         }
2132         memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
2133         process_guid_set = TRUE;
2134         mono_domain_unlock (mono_root_domain);
2135         return newguid;
2136 }
2137
2138 gboolean
2139 mono_domain_is_unloading (MonoDomain *domain)
2140 {
2141         if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
2142                 return TRUE;
2143         else
2144                 return FALSE;
2145 }
2146
2147 static void
2148 clear_cached_vtable (MonoVTable *vtable)
2149 {
2150         MonoClass *klass = vtable->klass;
2151         MonoDomain *domain = vtable->domain;
2152         MonoClassRuntimeInfo *runtime_info;
2153         void *data;
2154
2155         runtime_info = klass->runtime_info;
2156         if (runtime_info && runtime_info->max_domain >= domain->domain_id)
2157                 runtime_info->domain_vtables [domain->domain_id] = NULL;
2158         if (klass->has_static_refs && (data = mono_vtable_get_static_field_data (vtable)))
2159                 mono_gc_free_fixed (data);
2160 }
2161
2162 static G_GNUC_UNUSED void
2163 zero_static_data (MonoVTable *vtable)
2164 {
2165         MonoClass *klass = vtable->klass;
2166         void *data;
2167
2168         if (klass->has_static_refs && (data = mono_vtable_get_static_field_data (vtable)))
2169                 mono_gc_bzero (data, mono_class_data_size (klass));
2170 }
2171
2172 typedef struct unload_data {
2173         gboolean done;
2174         MonoDomain *domain;
2175         char *failure_reason;
2176         gint32 refcount;
2177 } unload_data;
2178
2179 static void
2180 unload_data_unref (unload_data *data)
2181 {
2182         gint32 count;
2183         do {
2184                 count = mono_atomic_load_acquire (&data->refcount);
2185                 g_assert (count >= 1 && count <= 2);
2186                 if (count == 1) {
2187                         g_free (data);
2188                         return;
2189                 }
2190         } while (InterlockedCompareExchange (&data->refcount, count, count - 1) != count);
2191 }
2192
2193 static void
2194 deregister_reflection_info_roots_nspace_table (gpointer key, gpointer value, gpointer image)
2195 {
2196         guint32 index = GPOINTER_TO_UINT (value);
2197         MonoClass *class = mono_class_get (image, MONO_TOKEN_TYPE_DEF | index);
2198
2199         g_assert (class);
2200
2201         mono_class_free_ref_info (class);
2202 }
2203
2204 static void
2205 deregister_reflection_info_roots_name_space (gpointer key, gpointer value, gpointer user_data)
2206 {
2207         g_hash_table_foreach (value, deregister_reflection_info_roots_nspace_table, user_data);
2208 }
2209
2210 static void
2211 deregister_reflection_info_roots_from_list (MonoImage *image)
2212 {
2213         GSList *list = image->reflection_info_unregister_classes;
2214
2215         while (list) {
2216                 MonoClass *class = list->data;
2217
2218                 mono_class_free_ref_info (class);
2219
2220                 list = list->next;
2221         }
2222
2223         g_slist_free (image->reflection_info_unregister_classes);
2224         image->reflection_info_unregister_classes = NULL;
2225 }
2226
2227 static void
2228 deregister_reflection_info_roots (MonoDomain *domain)
2229 {
2230         GSList *list;
2231
2232         mono_loader_lock ();
2233         mono_domain_assemblies_lock (domain);
2234         for (list = domain->domain_assemblies; list; list = list->next) {
2235                 MonoAssembly *assembly = list->data;
2236                 MonoImage *image = assembly->image;
2237                 int i;
2238                 /*No need to take the image lock here since dynamic images are appdomain bound and at this point the mutator is gone.*/
2239                 if (image->dynamic && image->name_cache)
2240                         g_hash_table_foreach (image->name_cache, deregister_reflection_info_roots_name_space, image);
2241                 deregister_reflection_info_roots_from_list (image);
2242                 for (i = 0; i < image->module_count; ++i) {
2243                         MonoImage *module = image->modules [i];
2244                         if (module) {
2245                                 if (module->dynamic && module->name_cache) {
2246                                         g_hash_table_foreach (module->name_cache,
2247                                                         deregister_reflection_info_roots_name_space, module);
2248                                 }
2249                                 deregister_reflection_info_roots_from_list (module);
2250                         }
2251                 }
2252         }
2253         mono_domain_assemblies_unlock (domain);
2254         mono_loader_unlock ();
2255 }
2256
2257 static guint32 WINAPI
2258 unload_thread_main (void *arg)
2259 {
2260         unload_data *data = (unload_data*)arg;
2261         MonoDomain *domain = data->domain;
2262         MonoThread *thread;
2263         int i;
2264
2265         /* Have to attach to the runtime so shutdown can wait for this thread */
2266         /* Force it to be attached to avoid racing during shutdown. */
2267         thread = mono_thread_attach_full (mono_get_root_domain (), TRUE);
2268
2269         /* 
2270          * FIXME: Abort our parent thread last, so we can return a failure 
2271          * indication if aborting times out.
2272          */
2273         if (!mono_threads_abort_appdomain_threads (domain, -1)) {
2274                 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
2275                 goto failure;
2276         }
2277
2278         if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
2279                 data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
2280                 goto failure;
2281         }
2282
2283         /* Finalize all finalizable objects in the doomed appdomain */
2284         if (!mono_domain_finalize (domain, -1)) {
2285                 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
2286                 goto failure;
2287         }
2288
2289         /* Clear references to our vtables in class->runtime_info.
2290          * We also hold the loader lock because we're going to change
2291          * class->runtime_info.
2292          */
2293
2294         mono_loader_lock ();
2295         mono_domain_lock (domain);
2296 #ifdef HAVE_SGEN_GC
2297         /*
2298          * We need to make sure that we don't have any remsets
2299          * pointing into static data of the to-be-freed domain because
2300          * at the next collections they would be invalid.  So what we
2301          * do is we first zero all static data and then do a minor
2302          * collection.  Because all references in the static data will
2303          * now be null we won't do any unnecessary copies and after
2304          * the collection there won't be any more remsets.
2305          */
2306         for (i = 0; i < domain->class_vtable_array->len; ++i)
2307                 zero_static_data (g_ptr_array_index (domain->class_vtable_array, i));
2308         mono_gc_collect (0);
2309 #endif
2310         for (i = 0; i < domain->class_vtable_array->len; ++i)
2311                 clear_cached_vtable (g_ptr_array_index (domain->class_vtable_array, i));
2312         deregister_reflection_info_roots (domain);
2313
2314         mono_assembly_cleanup_domain_bindings (domain->domain_id);
2315
2316         mono_domain_unlock (domain);
2317         mono_loader_unlock ();
2318
2319         mono_threads_clear_cached_culture (domain);
2320
2321         domain->state = MONO_APPDOMAIN_UNLOADED;
2322
2323         /* printf ("UNLOADED %s.\n", domain->friendly_name); */
2324
2325         /* remove from the handle table the items related to this domain */
2326         mono_gchandle_free_domain (domain);
2327
2328         mono_domain_free (domain, FALSE);
2329
2330         mono_gc_collect (mono_gc_max_generation ());
2331
2332         mono_atomic_store_release (&data->done, TRUE);
2333         unload_data_unref (data);
2334         mono_thread_detach (thread);
2335         return 0;
2336
2337 failure:
2338         mono_atomic_store_release (&data->done, TRUE);
2339         unload_data_unref (data);
2340         mono_thread_detach (thread);
2341         return 1;
2342 }
2343
2344 /*
2345  * mono_domain_unload:
2346  * @domain: The domain to unload
2347  *
2348  *  Unloads an appdomain. Follows the process outlined in the comment
2349  *  for mono_domain_try_unload.
2350  */
2351 void
2352 mono_domain_unload (MonoDomain *domain)
2353 {
2354         MonoObject *exc = NULL;
2355         mono_domain_try_unload (domain, &exc);
2356         if (exc)
2357                 mono_raise_exception ((MonoException*)exc);
2358 }
2359
2360 /*
2361  * mono_domain_unload:
2362  * @domain: The domain to unload
2363  * @exc: Exception information
2364  *
2365  *  Unloads an appdomain. Follows the process outlined in:
2366  *  http://blogs.gotdotnet.com/cbrumme
2367  *
2368  *  If doing things the 'right' way is too hard or complex, we do it the 
2369  *  'simple' way, which means do everything needed to avoid crashes and
2370  *  memory leaks, but not much else.
2371  *
2372  *  It is required to pass a valid reference to the exc argument, upon return
2373  *  from this function *exc will be set to the exception thrown, if any.
2374  *
2375  *  If this method is not called from an icall (embedded scenario for instance),
2376  *  it must not be called with any managed frames on the stack, since the unload
2377  *  process could end up trying to abort the current thread.
2378  */
2379 void
2380 mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
2381 {
2382         HANDLE thread_handle;
2383         gsize tid;
2384         MonoAppDomainState prev_state;
2385         MonoMethod *method;
2386         unload_data *thread_data;
2387         MonoDomain *caller_domain = mono_domain_get ();
2388
2389         /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2390
2391         /* Atomically change our state to UNLOADING */
2392         prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
2393                                                                                          MONO_APPDOMAIN_UNLOADING_START,
2394                                                                                          MONO_APPDOMAIN_CREATED);
2395         if (prev_state != MONO_APPDOMAIN_CREATED) {
2396                 switch (prev_state) {
2397                 case MONO_APPDOMAIN_UNLOADING_START:
2398                 case MONO_APPDOMAIN_UNLOADING:
2399                         *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded.");
2400                         return;
2401                 case MONO_APPDOMAIN_UNLOADED:
2402                         *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded.");
2403                         return;
2404                 default:
2405                         g_warning ("Invalid appdomain state %d", prev_state);
2406                         g_assert_not_reached ();
2407                 }
2408         }
2409
2410         mono_debugger_event_unload_appdomain (domain);
2411
2412         mono_domain_set (domain, FALSE);
2413         /* Notify OnDomainUnload listeners */
2414         method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1); 
2415         g_assert (method);
2416
2417         mono_runtime_invoke (method, domain->domain, NULL, exc);
2418         if (*exc) {
2419                 /* Roll back the state change */
2420                 domain->state = MONO_APPDOMAIN_CREATED;
2421                 mono_domain_set (caller_domain, FALSE);
2422                 return;
2423         }
2424         mono_domain_set (caller_domain, FALSE);
2425
2426         thread_data = g_new0 (unload_data, 1);
2427         thread_data->domain = domain;
2428         thread_data->failure_reason = NULL;
2429         thread_data->done = FALSE;
2430         thread_data->refcount = 2; /*Must be 2: unload thread + initiator */
2431
2432         /*The managed callback finished successfully, now we start tearing down the appdomain*/
2433         domain->state = MONO_APPDOMAIN_UNLOADING;
2434         /* 
2435          * First we create a separate thread for unloading, since
2436          * we might have to abort some threads, including the current one.
2437          */
2438         /*
2439          * If we create a non-suspended thread, the runtime will hang.
2440          * See:
2441          * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2442          */ 
2443 #if 0
2444         thread_handle = mono_create_thread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2445 #else
2446         thread_handle = mono_create_thread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, thread_data, CREATE_SUSPENDED, &tid);
2447         if (thread_handle == NULL) {
2448                 return;
2449         }
2450         ResumeThread (thread_handle);
2451 #endif
2452
2453         /* Wait for the thread */       
2454         while (!thread_data->done && WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION) {
2455                 if (mono_thread_internal_has_appdomain_ref (mono_thread_internal_current (), domain) && (mono_thread_interruption_requested ())) {
2456                         /* The unload thread tries to abort us */
2457                         /* The icall wrapper will execute the abort */
2458                         CloseHandle (thread_handle);
2459                         unload_data_unref (thread_data);
2460                         return;
2461                 }
2462         }
2463         CloseHandle (thread_handle);
2464
2465         if (thread_data->failure_reason) {
2466                 /* Roll back the state change */
2467                 domain->state = MONO_APPDOMAIN_CREATED;
2468
2469                 g_warning ("%s", thread_data->failure_reason);
2470
2471                 *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain (thread_data->failure_reason);
2472
2473                 g_free (thread_data->failure_reason);
2474                 thread_data->failure_reason = NULL;
2475         }
2476
2477         unload_data_unref (thread_data);
2478 }