[Facades] Use Open.snk for netstandard.dll
[mono.git] / mono / metadata / domain-internals.h
1 /**
2  * \file
3  * Appdomain-related internal data structures and functions.
4  * Copyright 2012 Xamarin Inc (http://www.xamarin.com)
5  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
6  */
7 #ifndef __MONO_METADATA_DOMAIN_INTERNALS_H__
8 #define __MONO_METADATA_DOMAIN_INTERNALS_H__
9
10 #include <mono/metadata/appdomain.h>
11 #include <mono/metadata/mempool.h>
12 #include <mono/metadata/lock-tracer.h>
13 #include <mono/utils/mono-codeman.h>
14 #include <mono/metadata/mono-hash.h>
15 #include <mono/utils/mono-compiler.h>
16 #include <mono/utils/mono-internal-hash.h>
17 #include <mono/metadata/mempool-internals.h>
18
19 /*
20  * If this is set, the memory belonging to appdomains is not freed when a domain is
21  * unloaded, and assemblies loaded by the appdomain are not unloaded either. This
22  * allows us to use typed gc in non-default appdomains too, leading to increased
23  * performance.
24  */ 
25 extern gboolean mono_dont_free_domains;
26
27 /* This is a copy of System.AppDomainSetup */
28 typedef struct {
29         MonoObject object;
30         MonoString *application_base;
31         MonoString *application_name;
32         MonoString *cache_path;
33         MonoString *configuration_file;
34         MonoString *dynamic_base;
35         MonoString *license_file;
36         MonoString *private_bin_path;
37         MonoString *private_bin_path_probe;
38         MonoString *shadow_copy_directories;
39         MonoString *shadow_copy_files;
40         MonoBoolean publisher_policy;
41         MonoBoolean path_changed;
42         int loader_optimization;
43         MonoBoolean disallow_binding_redirects;
44         MonoBoolean disallow_code_downloads;
45         MonoObject *activation_arguments; /* it is System.Object in 1.x, ActivationArguments in 2.0 */
46         MonoObject *domain_initializer;
47         MonoObject *application_trust; /* it is System.Object in 1.x, ApplicationTrust in 2.0 */
48         MonoArray *domain_initializer_args;
49         MonoBoolean disallow_appbase_probe;
50         MonoArray *configuration_bytes;
51         MonoArray *serialized_non_primitives;
52 } MonoAppDomainSetup;
53
54 typedef struct _MonoJitInfoTable MonoJitInfoTable;
55 typedef struct _MonoJitInfoTableChunk MonoJitInfoTableChunk;
56
57 #define MONO_JIT_INFO_TABLE_CHUNK_SIZE          64
58
59 struct _MonoJitInfoTableChunk
60 {
61         int                    refcount;
62         volatile int           num_elements;
63         volatile gint8        *last_code_end;
64         MonoJitInfo *next_tombstone;
65         MonoJitInfo * volatile data [MONO_JIT_INFO_TABLE_CHUNK_SIZE];
66 };
67
68 struct _MonoJitInfoTable
69 {
70         MonoDomain             *domain;
71         int                     num_chunks;
72         MonoJitInfoTableChunk  *chunks [MONO_ZERO_LEN_ARRAY];
73 };
74
75 #define MONO_SIZEOF_JIT_INFO_TABLE (sizeof (struct _MonoJitInfoTable) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P)
76
77 typedef GArray MonoAotModuleInfoTable;
78
79 typedef struct {
80         guint32  flags;
81         gint32   exvar_offset;
82         gpointer try_start;
83         gpointer try_end;
84         gpointer handler_start;
85         /*
86          * For LLVM compiled code, this is the index of the il clause
87          * associated with this handler.
88          */
89         int clause_index;
90         uint32_t try_offset;
91         uint32_t try_len;
92         uint32_t handler_offset;
93         uint32_t handler_len;
94         union {
95                 MonoClass *catch_class;
96                 gpointer filter;
97                 gpointer handler_end;
98         } data;
99 } MonoJitExceptionInfo;
100
101 /*
102  * Contains information about the type arguments for generic shared methods.
103  */
104 typedef struct {
105         gboolean is_gsharedvt;
106 } MonoGenericSharingContext;
107
108 /* Simplified DWARF location list entry */
109 typedef struct {
110         /* Whenever the value is in a register */
111         gboolean is_reg;
112         /*
113          * If is_reg is TRUE, the register which contains the value. Otherwise
114          * the base register.
115          */
116         int reg;
117         /*
118          * If is_reg is FALSE, the offset of the stack location relative to 'reg'.
119          * Otherwise, 0.
120          */
121         int offset;
122         /*
123          * Offsets of the PC interval where the value is in this location.
124          */
125         int from, to;
126 } MonoDwarfLocListEntry;
127
128 typedef struct
129 {
130         MonoGenericSharingContext *generic_sharing_context;
131         int nlocs;
132         MonoDwarfLocListEntry *locations;
133         gint32 this_offset;
134         guint8 this_reg;
135         gboolean has_this:1;
136         gboolean this_in_reg:1;
137 } MonoGenericJitInfo;
138
139 /*
140 A try block hole is used to represent a non-contiguous part of
141 of a segment of native code protected by a given .try block.
142 Usually, a try block is defined as a contiguous segment of code.
143 But in some cases it's needed to have some parts of it to not be protected.
144 For example, given "try {} finally {}", the code in the .try block to call
145 the finally part looks like:
146
147 try {
148     ...
149         call finally_block
150         adjust stack
151         jump outside try block
152         ...
153 } finally {
154         ...
155 }
156
157 The instructions between the call and the jump should not be under the try block since they happen
158 after the finally block executes, which means if an async exceptions happens at that point we would
159 execute the finally clause twice. So, to avoid this, we introduce a hole in the try block to signal
160 that those instructions are not protected.
161 */
162 typedef struct
163 {
164         guint32 offset;
165         guint16 clause;
166         guint16 length;
167 } MonoTryBlockHoleJitInfo;
168
169 typedef struct
170 {
171         guint16 num_holes;
172         MonoTryBlockHoleJitInfo holes [MONO_ZERO_LEN_ARRAY];
173 } MonoTryBlockHoleTableJitInfo;
174
175 typedef struct
176 {
177         guint32 stack_size;
178         guint32 epilog_size;
179 } MonoArchEHJitInfo;
180
181 typedef struct {
182         /* Relative to code_start */
183         int thunks_offset;
184         int thunks_size;
185 } MonoThunkJitInfo;
186
187 typedef struct {
188         guint8 *unw_info;
189         int unw_info_len;
190 } MonoUnwindJitInfo;
191
192 typedef enum {
193         JIT_INFO_NONE = 0,
194         JIT_INFO_HAS_GENERIC_JIT_INFO = (1 << 0),
195         JIT_INFO_HAS_TRY_BLOCK_HOLES = (1 << 1),
196         JIT_INFO_HAS_ARCH_EH_INFO = (1 << 2),
197         JIT_INFO_HAS_THUNK_INFO = (1 << 3),
198         /*
199          * If this is set, the unwind info is stored in the structure, instead of being pointed to by the
200          * 'unwind_info' field.
201          */
202         JIT_INFO_HAS_UNWIND_INFO = (1 << 4)
203 } MonoJitInfoFlags;
204
205 struct _MonoJitInfo {
206         /* NOTE: These first two elements (method and
207            next_jit_code_hash) must be in the same order and at the
208            same offset as in RuntimeMethod, because of the jit_code_hash
209            internal hash table in MonoDomain. */
210         union {
211                 MonoMethod *method;
212                 MonoImage *image;
213                 gpointer aot_info;
214                 gpointer tramp_info;
215         } d;
216         union {
217                 struct _MonoJitInfo *next_jit_code_hash;
218                 struct _MonoJitInfo *next_tombstone;
219         } n;
220         gpointer    code_start;
221         guint32     unwind_info;
222         int         code_size;
223         guint32     num_clauses:15;
224         /* Whenever the code is domain neutral or 'shared' */
225         gboolean    domain_neutral:1;
226         gboolean    has_generic_jit_info:1;
227         gboolean    has_try_block_holes:1;
228         gboolean    has_arch_eh_info:1;
229         gboolean    has_thunk_info:1;
230         gboolean    has_unwind_info:1;
231         gboolean    from_aot:1;
232         gboolean    from_llvm:1;
233         gboolean    dbg_attrs_inited:1;
234         gboolean    dbg_hidden:1;
235         /* Whenever this jit info was loaded in async context */
236         gboolean    async:1;
237         gboolean    dbg_step_through:1;
238         gboolean    dbg_non_user_code:1;
239         /*
240          * Whenever this jit info refers to a trampoline.
241          * d.tramp_info contains additional data in this case.
242          */
243         gboolean    is_trampoline:1;
244
245         /* FIXME: Embed this after the structure later*/
246         gpointer    gc_info; /* Currently only used by SGen */
247         
248         MonoJitExceptionInfo clauses [MONO_ZERO_LEN_ARRAY];
249         /* There is an optional MonoGenericJitInfo after the clauses */
250         /* There is an optional MonoTryBlockHoleTableJitInfo after MonoGenericJitInfo clauses*/
251         /* There is an optional MonoArchEHJitInfo after MonoTryBlockHoleTableJitInfo */
252         /* There is an optional MonoThunkJitInfo after MonoArchEHJitInfo */
253 };
254
255 #define MONO_SIZEOF_JIT_INFO (offsetof (struct _MonoJitInfo, clauses))
256
257 typedef struct {
258         gpointer *static_data; /* Used to free the static data without going through the MonoAppContext object itself. */
259         uint32_t gc_handle;
260 } ContextStaticData;
261
262 struct _MonoAppContext {
263         MonoObject obj;
264         gint32 domain_id;
265         gint32 context_id;
266         gpointer *static_data;
267         ContextStaticData *data;
268 };
269
270 /* Lock-free allocator */
271 typedef struct {
272         guint8 *mem;
273         gpointer prev;
274         int size, pos;
275 } LockFreeMempoolChunk;
276
277 typedef struct {
278         LockFreeMempoolChunk *current, *chunks;
279 } LockFreeMempool;
280
281 /*
282  * We have two unloading states because the domain
283  * must remain fully functional while AppDomain::DomainUnload is
284  * processed.
285  * After that unloading began and all domain facilities are teared down
286  * such as execution of new threadpool jobs.  
287  */
288 typedef enum {
289         MONO_APPDOMAIN_CREATED,
290         MONO_APPDOMAIN_UNLOADING_START,
291         MONO_APPDOMAIN_UNLOADING,
292         MONO_APPDOMAIN_UNLOADED
293 } MonoAppDomainState;
294
295 typedef struct _MonoThunkFreeList {
296         guint32 size;
297         int length;             /* only valid for the wait list */
298         struct _MonoThunkFreeList *next;
299 } MonoThunkFreeList;
300
301 typedef struct _MonoJitCodeHash MonoJitCodeHash;
302
303 struct _MonoDomain {
304         /*
305          * This lock must never be taken before the loader lock,
306          * i.e. if both are taken by the same thread, the loader lock
307          * must taken first.
308          */
309         MonoCoopMutex    lock;
310         MonoMemPool        *mp;
311         MonoCodeManager    *code_mp;
312         /*
313          * keep all the managed objects close to each other for the precise GC
314          * For the Boehm GC we additionally keep close also other GC-tracked pointers.
315          */
316 #define MONO_DOMAIN_FIRST_OBJECT setup
317         MonoAppDomainSetup *setup;
318         MonoAppDomain      *domain;
319         MonoAppContext     *default_context;
320         MonoException      *out_of_memory_ex;
321         MonoException      *null_reference_ex;
322         MonoException      *stack_overflow_ex;
323         /* typeof (void) */
324         MonoObject         *typeof_void;
325         /* Ephemeron Tombstone*/
326         MonoObject         *ephemeron_tombstone;
327         /* new MonoType [0] */
328         MonoArray          *empty_types;
329         MonoString         *empty_string;
330         /* 
331          * The fields between FIRST_GC_TRACKED and LAST_GC_TRACKED are roots, but
332          * not object references.
333          */
334 #define MONO_DOMAIN_FIRST_GC_TRACKED env
335         MonoGHashTable     *env;
336         MonoGHashTable     *ldstr_table;
337         /* hashtables for Reflection handles */
338         MonoGHashTable     *type_hash;
339         MonoGHashTable     *refobject_hash;
340         /*
341          * A GC-tracked array to keep references to the static fields of types.
342          * See note [Domain Static Data Array].
343          */
344         gpointer           *static_data_array;
345         /* maps class -> type initialization exception object */
346         MonoGHashTable    *type_init_exception_hash;
347         /* maps delegate trampoline addr -> delegate object */
348         MonoGHashTable     *delegate_hash_table;
349 #define MONO_DOMAIN_LAST_GC_TRACKED delegate_hash_table
350         guint32            state;
351         /* Needed by Thread:GetDomainID() */
352         gint32             domain_id;
353         gint32             shadow_serial;
354         GSList             *domain_assemblies;
355         MonoAssembly       *entry_assembly;
356         char               *friendly_name;
357         GPtrArray          *class_vtable_array;
358         /* maps remote class key -> MonoRemoteClass */
359         GHashTable         *proxy_vtable_hash;
360         /* Protected by 'jit_code_hash_lock' */
361         MonoInternalHashTable jit_code_hash;
362         mono_mutex_t    jit_code_hash_lock;
363         int                 num_jit_info_tables;
364         MonoJitInfoTable * 
365           volatile          jit_info_table;
366         /*
367          * Contains information about AOT loaded code.
368          * Only used in the root domain.
369          */
370         MonoJitInfoTable *
371           volatile          aot_modules;
372         GSList             *jit_info_free_queue;
373         /* Used when loading assemblies */
374         gchar **search_path;
375         gchar *private_bin_path;
376         LockFreeMempool *lock_free_mp;
377         
378         /* Used by remoting proxies */
379         MonoMethod         *create_proxy_for_type_method;
380         MonoMethod         *private_invoke_method;
381         /* Used to store offsets of thread and context static fields */
382         GHashTable         *special_static_fields;
383         /* 
384          * This must be a GHashTable, since these objects can't be finalized
385          * if the hashtable contains a GC visible reference to them.
386          */
387         GHashTable         *finalizable_objects_hash;
388
389         /* Protects the three hashes above */
390         mono_mutex_t   finalizable_objects_hash_lock;
391         /* Used when accessing 'domain_assemblies' */
392         mono_mutex_t    assemblies_lock;
393
394         GHashTable         *method_rgctx_hash;
395
396         GHashTable         *generic_virtual_cases;
397
398         /* Information maintained by the JIT engine */
399         gpointer runtime_info;
400         
401         /* Contains the compiled runtime invoke wrapper used by finalizers */
402         gpointer            finalize_runtime_invoke;
403
404         /* Contains the compiled runtime invoke wrapper used by async resylt creation to capture thread context*/
405         gpointer            capture_context_runtime_invoke;
406
407         /* Contains the compiled method used by async resylt creation to capture thread context*/
408         gpointer            capture_context_method;
409
410         /* Assembly bindings, the per-domain part */
411         GSList *assembly_bindings;
412         gboolean assembly_bindings_parsed;
413
414         /* Used by socket-io.c */
415         /* These are domain specific, since the assembly can be unloaded */
416         MonoImage *socket_assembly;
417         MonoClass *sockaddr_class;
418         MonoClassField *sockaddr_data_field;
419         MonoClassField *sockaddr_data_length_field;
420
421         /* Cache function pointers for architectures  */
422         /* that require wrappers */
423         GHashTable *ftnptrs_hash;
424
425         /* Maps MonoMethod* to weak links to DynamicMethod objects */
426         GHashTable *method_to_dyn_method;
427
428         /* <ThrowUnobservedTaskExceptions /> support */
429         gboolean throw_unobserved_task_exceptions;
430
431         guint32 execution_context_field_offset;
432 };
433
434 typedef struct  {
435         guint16 major, minor, build, revision;
436 } AssemblyVersionSet;
437
438 /* MonoRuntimeInfo: Contains information about versions supported by this runtime */
439 typedef struct  {
440         const char runtime_version [12];
441         const char framework_version [4];
442         const AssemblyVersionSet version_sets [5];
443 } MonoRuntimeInfo;
444
445 #define mono_domain_assemblies_lock(domain) mono_locks_os_acquire(&(domain)->assemblies_lock, DomainAssembliesLock)
446 #define mono_domain_assemblies_unlock(domain) mono_locks_os_release(&(domain)->assemblies_lock, DomainAssembliesLock)
447 #define mono_domain_jit_code_hash_lock(domain) mono_locks_os_acquire(&(domain)->jit_code_hash_lock, DomainJitCodeHashLock)
448 #define mono_domain_jit_code_hash_unlock(domain) mono_locks_os_release(&(domain)->jit_code_hash_lock, DomainJitCodeHashLock)
449
450 typedef MonoDomain* (*MonoLoadFunc) (const char *filename, const char *runtime_version);
451
452 void mono_domain_lock (MonoDomain *domain) MONO_LLVM_INTERNAL;
453 void mono_domain_unlock (MonoDomain *domain) MONO_LLVM_INTERNAL;
454
455 void
456 mono_install_runtime_load  (MonoLoadFunc func);
457
458 MonoDomain*
459 mono_runtime_load (const char *filename, const char *runtime_version);
460
461 typedef void (*MonoCreateDomainFunc) (MonoDomain *domain);
462
463 void
464 mono_install_create_domain_hook (MonoCreateDomainFunc func);
465
466 typedef void (*MonoFreeDomainFunc) (MonoDomain *domain);
467
468 void
469 mono_install_free_domain_hook (MonoFreeDomainFunc func);
470
471 void 
472 mono_cleanup (void);
473
474 void
475 mono_close_exe_image (void);
476
477 int
478 mono_jit_info_size (MonoJitInfoFlags flags, int num_clauses, int num_holes);
479
480 void
481 mono_jit_info_init (MonoJitInfo *ji, MonoMethod *method, guint8 *code, int code_size,
482                                         MonoJitInfoFlags flags, int num_clauses, int num_holes);
483
484 MonoJitInfoTable *
485 mono_jit_info_table_new (MonoDomain *domain);
486
487 void
488 mono_jit_info_table_free (MonoJitInfoTable *table);
489
490 void
491 mono_jit_info_table_add    (MonoDomain *domain, MonoJitInfo *ji);
492
493 void
494 mono_jit_info_table_remove (MonoDomain *domain, MonoJitInfo *ji);
495
496 void
497 mono_jit_info_add_aot_module (MonoImage *image, gpointer start, gpointer end);
498
499 MonoGenericJitInfo*
500 mono_jit_info_get_generic_jit_info (MonoJitInfo *ji);
501
502 MonoGenericSharingContext*
503 mono_jit_info_get_generic_sharing_context (MonoJitInfo *ji);
504
505 void
506 mono_jit_info_set_generic_sharing_context (MonoJitInfo *ji, MonoGenericSharingContext *gsctx);
507
508 char *
509 mono_make_shadow_copy (const char *filename, MonoError *error);
510
511 gboolean
512 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name);
513
514 gpointer
515 mono_domain_alloc  (MonoDomain *domain, guint size);
516
517 gpointer
518 mono_domain_alloc0 (MonoDomain *domain, guint size);
519
520 gpointer
521 mono_domain_alloc0_lock_free (MonoDomain *domain, guint size);
522
523 void*
524 mono_domain_code_reserve (MonoDomain *domain, int size) MONO_LLVM_INTERNAL;
525
526 void*
527 mono_domain_code_reserve_align (MonoDomain *domain, int size, int alignment);
528
529 void
530 mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize);
531
532 void
533 mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data);
534
535 void
536 mono_domain_unset (void);
537
538 void
539 mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception);
540
541 MonoTryBlockHoleTableJitInfo*
542 mono_jit_info_get_try_block_hole_table_info (MonoJitInfo *ji);
543
544 MonoArchEHJitInfo*
545 mono_jit_info_get_arch_eh_info (MonoJitInfo *ji);
546
547 MonoThunkJitInfo*
548 mono_jit_info_get_thunk_info (MonoJitInfo *ji);
549
550 MonoUnwindJitInfo*
551 mono_jit_info_get_unwind_info (MonoJitInfo *ji);
552
553 /* 
554  * Installs a new function which is used to return a MonoJitInfo for a method inside
555  * an AOT module.
556  */
557 typedef MonoJitInfo *(*MonoJitInfoFindInAot)         (MonoDomain *domain, MonoImage *image, gpointer addr);
558 void          mono_install_jit_info_find_in_aot (MonoJitInfoFindInAot func);
559
560 void
561 mono_jit_code_hash_init (MonoInternalHashTable *jit_code_hash);
562
563 MonoAssembly *
564 mono_assembly_load_corlib (const MonoRuntimeInfo *runtime, MonoImageOpenStatus *status);
565
566 const MonoRuntimeInfo*
567 mono_get_runtime_info (void);
568
569 void
570 mono_runtime_set_no_exec (gboolean val);
571
572 gboolean
573 mono_runtime_get_no_exec (void);
574
575 gboolean
576 mono_assembly_name_parse (const char *name, MonoAssemblyName *aname);
577
578 MonoImage *mono_assembly_open_from_bundle (const char *filename,
579                                            MonoImageOpenStatus *status,
580                                            gboolean refonly);
581
582 MONO_API void
583 mono_domain_add_class_static_data (MonoDomain *domain, MonoClass *klass, gpointer data, guint32 *bitmap);
584
585 MonoAssembly *
586 mono_try_assembly_resolve (MonoDomain *domain, const char *fname, MonoAssembly *requesting, gboolean refonly, MonoError *error);
587
588 MonoAssembly *
589 mono_domain_assembly_postload_search (MonoAssemblyName *aname, MonoAssembly *requesting, gboolean refonly);
590
591 MonoAssembly* mono_assembly_load_full_nosearch (MonoAssemblyName *aname, 
592                                                 const char       *basedir, 
593                                                 MonoImageOpenStatus *status,
594                                                 gboolean refonly);
595
596 void mono_domain_set_options_from_config (MonoDomain *domain);
597
598 int mono_framework_version (void);
599
600 void mono_reflection_cleanup_domain (MonoDomain *domain);
601
602 void mono_assembly_cleanup_domain_bindings (guint32 domain_id);
603
604 MonoJitInfo* mono_jit_info_table_find_internal (MonoDomain *domain, char *addr, gboolean try_aot, gboolean allow_trampolines);
605
606 void mono_enable_debug_domain_unload (gboolean enable);
607
608 MonoReflectionAssembly *
609 mono_domain_try_type_resolve_checked (MonoDomain *domain, char *name, MonoObject *tb, MonoError *error);
610
611 void
612 mono_runtime_init_checked (MonoDomain *domain, MonoThreadStartCB start_cb, MonoThreadAttachCB attach_cb, MonoError *error);
613
614 void
615 mono_context_init_checked (MonoDomain *domain, MonoError *error);
616
617 gboolean
618 mono_assembly_has_reference_assembly_attribute (MonoAssembly *assembly, MonoError *error);
619
620 GPtrArray*
621 mono_domain_get_assemblies (MonoDomain *domain, gboolean refonly);
622
623 #endif /* __MONO_METADATA_DOMAIN_INTERNALS_H__ */