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