9ea2bcf0ee5c5252c362d8b8106a623db82faa87
[mono.git] / mono / metadata / dynamic-image.c
1 /**
2  * \file
3  * Images created at runtime.
4  *   
5  * 
6  * Author:
7  *   Paolo Molaro (lupus@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 2011 Rodrigo Kumpera
12  * Copyright 2016 Microsoft
13  *
14  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15  */
16
17 #include <config.h>
18 #include <glib.h>
19 #include "mono/metadata/object.h"
20 #include "mono/metadata/dynamic-image-internals.h"
21 #include "mono/metadata/dynamic-stream-internals.h"
22 #include "mono/metadata/gc-internals.h"
23 #include "mono/metadata/metadata-internals.h"
24 #include "mono/metadata/profiler-private.h"
25 #include "mono/metadata/reflection-internals.h"
26 #include "mono/metadata/sre-internals.h"
27 #include "mono/utils/checked-build.h"
28 #include "mono/utils/mono-error-internals.h"
29 #include "mono/utils/mono-os-mutex.h"
30
31 const unsigned char table_sizes [MONO_TABLE_NUM] = {
32         MONO_MODULE_SIZE,
33         MONO_TYPEREF_SIZE,
34         MONO_TYPEDEF_SIZE,
35         0,
36         MONO_FIELD_SIZE,
37         0,
38         MONO_METHOD_SIZE,
39         0,
40         MONO_PARAM_SIZE,
41         MONO_INTERFACEIMPL_SIZE,
42         MONO_MEMBERREF_SIZE,    /* 0x0A */
43         MONO_CONSTANT_SIZE,
44         MONO_CUSTOM_ATTR_SIZE,
45         MONO_FIELD_MARSHAL_SIZE,
46         MONO_DECL_SECURITY_SIZE,
47         MONO_CLASS_LAYOUT_SIZE,
48         MONO_FIELD_LAYOUT_SIZE, /* 0x10 */
49         MONO_STAND_ALONE_SIGNATURE_SIZE,
50         MONO_EVENT_MAP_SIZE,
51         0,
52         MONO_EVENT_SIZE,
53         MONO_PROPERTY_MAP_SIZE,
54         0,
55         MONO_PROPERTY_SIZE,
56         MONO_METHOD_SEMA_SIZE,
57         MONO_METHODIMPL_SIZE,
58         MONO_MODULEREF_SIZE,    /* 0x1A */
59         MONO_TYPESPEC_SIZE,
60         MONO_IMPLMAP_SIZE,      
61         MONO_FIELD_RVA_SIZE,
62         0,
63         0,
64         MONO_ASSEMBLY_SIZE,     /* 0x20 */
65         MONO_ASSEMBLY_PROCESSOR_SIZE,
66         MONO_ASSEMBLYOS_SIZE,
67         MONO_ASSEMBLYREF_SIZE,
68         MONO_ASSEMBLYREFPROC_SIZE,
69         MONO_ASSEMBLYREFOS_SIZE,
70         MONO_FILE_SIZE,
71         MONO_EXP_TYPE_SIZE,
72         MONO_MANIFEST_SIZE,
73         MONO_NESTED_CLASS_SIZE,
74
75         MONO_GENERICPARAM_SIZE, /* 0x2A */
76         MONO_METHODSPEC_SIZE,
77         MONO_GENPARCONSTRAINT_SIZE
78
79 };
80
81 // The dynamic images list is only needed to support the mempool reference tracking feature in checked-build.
82 static GPtrArray *dynamic_images;
83 static mono_mutex_t dynamic_images_mutex;
84
85 static inline void
86 dynamic_images_lock (void)
87 {
88         mono_os_mutex_lock (&dynamic_images_mutex);
89 }
90
91 static inline void
92 dynamic_images_unlock (void)
93 {
94         mono_os_mutex_unlock (&dynamic_images_mutex);
95 }
96
97 void
98 mono_dynamic_images_init (void)
99 {
100         mono_os_mutex_init (&dynamic_images_mutex);
101 }
102
103 #ifndef DISABLE_REFLECTION_EMIT
104 static void
105 string_heap_init (MonoDynamicStream *sh)
106 {
107         mono_dynstream_init (sh);
108 }
109 #endif
110
111 #ifndef DISABLE_REFLECTION_EMIT
112 static int
113 mono_blob_entry_hash (const char* str)
114 {
115         MONO_REQ_GC_NEUTRAL_MODE;
116
117         guint len, h;
118         const char *end;
119         len = mono_metadata_decode_blob_size (str, &str);
120         if (len > 0) {
121                 end = str + len;
122                 h = *str;
123                 for (str += 1; str < end; str++)
124                         h = (h << 5) - h + *str;
125                 return h;
126         } else {
127                 return 0;
128         }
129 }
130
131 static gboolean
132 mono_blob_entry_equal (const char *str1, const char *str2) {
133         MONO_REQ_GC_NEUTRAL_MODE;
134
135         int len, len2;
136         const char *end1;
137         const char *end2;
138         len = mono_metadata_decode_blob_size (str1, &end1);
139         len2 = mono_metadata_decode_blob_size (str2, &end2);
140         if (len != len2)
141                 return 0;
142         return memcmp (end1, end2, len) == 0;
143 }
144 #endif
145
146
147 /**
148  * mono_find_dynamic_image_owner:
149  *
150  * Find the dynamic image, if any, which a given pointer is located in the memory of.
151  */
152 MonoImage *
153 mono_find_dynamic_image_owner (void *ptr)
154 {
155         MonoImage *owner = NULL;
156         int i;
157
158         dynamic_images_lock ();
159
160         if (dynamic_images)
161         {
162                 for (i = 0; !owner && i < dynamic_images->len; ++i) {
163                         MonoImage *image = (MonoImage *)g_ptr_array_index (dynamic_images, i);
164                         if (mono_mempool_contains_addr (image->mempool, ptr))
165                                 owner = image;
166                 }
167         }
168
169         dynamic_images_unlock ();
170
171         return owner;
172 }
173
174 static inline void
175 dynamic_image_lock (MonoDynamicImage *image)
176 {
177         MONO_ENTER_GC_SAFE;
178         mono_image_lock ((MonoImage*)image);
179         MONO_EXIT_GC_SAFE;
180 }
181
182 static inline void
183 dynamic_image_unlock (MonoDynamicImage *image)
184 {
185         mono_image_unlock ((MonoImage*)image);
186 }
187
188 #ifndef DISABLE_REFLECTION_EMIT
189 /*
190  * mono_dynamic_image_register_token:
191  *
192  *   Register the TOKEN->OBJ mapping in the mapping table in ASSEMBLY. This is required for
193  * the Module.ResolveXXXToken () methods to work.
194  */
195 void
196 mono_dynamic_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObjectHandle obj)
197 {
198         MONO_REQ_GC_UNSAFE_MODE;
199
200         dynamic_image_lock (assembly);
201         mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), MONO_HANDLE_RAW (obj));
202         dynamic_image_unlock (assembly);
203 }
204 #else
205 void
206 mono_dynamic_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObjectHandle obj)
207 {
208 }
209 #endif
210
211 static MonoObject*
212 lookup_dyn_token (MonoDynamicImage *assembly, guint32 token)
213 {
214         MONO_REQ_GC_UNSAFE_MODE;
215
216         MonoObject *obj;
217
218         dynamic_image_lock (assembly);
219         obj = (MonoObject *)mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
220         dynamic_image_unlock (assembly);
221
222         return obj;
223 }
224
225 #ifndef DISABLE_REFLECTION_EMIT
226 MonoObjectHandle
227 mono_dynamic_image_get_registered_token (MonoDynamicImage *dynimage, guint32 token, MonoError *error)
228 {
229         error_init (error);
230         return MONO_HANDLE_NEW (MonoObject, lookup_dyn_token (dynimage, token));
231 }
232 #else /* DISABLE_REFLECTION_EMIT */
233 MonoObjectHandle
234 mono_dynamic_image_get_registered_token (MonoDynamicImage *dynimage, guint32 token, MonoError *error)
235 {
236         g_assert_not_reached ();
237         return NULL_HANDLE;
238 }
239 #endif
240
241 /**
242  * 
243  * mono_dynamic_image_is_valid_token:
244  * 
245  * Returns TRUE if token is valid in the given image.
246  * 
247  */
248 gboolean
249 mono_dynamic_image_is_valid_token (MonoDynamicImage *image, guint32 token)
250 {
251         return lookup_dyn_token (image, token) != NULL;
252 }
253
254 #ifndef DISABLE_REFLECTION_EMIT
255
256 #endif /* DISABLE_REFLECTION_EMIT */
257
258 #ifndef DISABLE_REFLECTION_EMIT
259 /**
260  * mono_reflection_lookup_dynamic_token:
261  *
262  * Finish the Builder object pointed to by TOKEN and return the corresponding
263  * runtime structure. If HANDLE_CLASS is not NULL, it is set to the class required by 
264  * mono_ldtoken. If valid_token is TRUE, assert if it is not found in the token->object
265  * mapping table.
266  *
267  * LOCKING: Take the loader lock
268  */
269 gpointer
270 mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context, MonoError *error)
271 {
272         MonoDynamicImage *assembly = (MonoDynamicImage*)image;
273         MonoObject *obj;
274         MonoClass *klass;
275
276         error_init (error);
277         
278         obj = lookup_dyn_token (assembly, token);
279         if (!obj) {
280                 if (valid_token)
281                         g_error ("Could not find required dynamic token 0x%08x", token);
282                 else {
283                         mono_error_set_execution_engine (error, "Could not find dynamic token 0x%08x", token);
284                         return NULL;
285                 }
286         }
287
288         if (!handle_class)
289                 handle_class = &klass;
290         gpointer result = mono_reflection_resolve_object (image, obj, handle_class, context, error);
291         return result;
292 }
293 #else /* DISABLE_REFLECTION_EMIT */
294 gpointer
295 mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context, MonoError *error)
296 {
297         error_init (error);
298         return NULL;
299 }
300 #endif /* DISABLE_REFLECTION_EMIT */
301
302 #ifndef DISABLE_REFLECTION_EMIT
303 MonoDynamicImage*
304 mono_dynamic_image_create (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name)
305 {
306         static const guchar entrycode [16] = {0xff, 0x25, 0};
307         MonoDynamicImage *image;
308         int i;
309
310         const char *version;
311
312         if (!strcmp (mono_get_runtime_info ()->framework_version, "2.1"))
313                 version = "v2.0.50727"; /* HACK: SL 2 enforces the .net 2 metadata version */
314         else
315                 version = mono_get_runtime_info ()->runtime_version;
316
317         image = g_new0 (MonoDynamicImage, 1);
318
319         mono_profiler_module_event (&image->image, MONO_PROFILE_START_LOAD);
320         
321         /*g_print ("created image %p\n", image);*/
322         /* keep in sync with image.c */
323         image->image.name = assembly_name;
324         image->image.assembly_name = image->image.name; /* they may be different */
325         image->image.module_name = module_name;
326         image->image.version = g_strdup (version);
327         image->image.md_version_major = 1;
328         image->image.md_version_minor = 1;
329         image->image.dynamic = TRUE;
330
331         image->image.references = g_new0 (MonoAssembly*, 1);
332         image->image.references [0] = NULL;
333
334         mono_image_init (&image->image);
335
336         image->token_fixups = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module token fixups table");
337         image->method_to_table_idx = g_hash_table_new (NULL, NULL);
338         image->field_to_table_idx = g_hash_table_new (NULL, NULL);
339         image->method_aux_hash = g_hash_table_new (NULL, NULL);
340         image->vararg_aux_hash = g_hash_table_new (NULL, NULL);
341         image->handleref = g_hash_table_new (NULL, NULL);
342         image->handleref_managed = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module reference-to-token table");
343         image->tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module tokens table");
344         image->generic_def_objects = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module generic definitions table");
345         image->typespec = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
346         image->typeref = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
347         image->blob_cache = g_hash_table_new ((GHashFunc)mono_blob_entry_hash, (GCompareFunc)mono_blob_entry_equal);
348         image->gen_params = g_ptr_array_new ();
349         image->remapped_tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module remapped tokens table");
350
351         /*g_print ("string heap create for image %p (%s)\n", image, module_name);*/
352         string_heap_init (&image->sheap);
353         mono_dynstream_add_data (&image->us, "", 1);
354         mono_dynamic_image_add_to_blob_cached (image, (char*) "", 1, NULL, 0);
355         /* import tables... */
356         mono_dynstream_add_data (&image->code, (char*)entrycode, sizeof (entrycode));
357         image->iat_offset = mono_dynstream_add_zero (&image->code, 8); /* two IAT entries */
358         image->idt_offset = mono_dynstream_add_zero (&image->code, 2 * sizeof (MonoIDT)); /* two IDT entries */
359         image->imp_names_offset = mono_dynstream_add_zero (&image->code, 2); /* flags for name entry */
360         mono_dynstream_add_data (&image->code, "_CorExeMain", 12);
361         mono_dynstream_add_data (&image->code, "mscoree.dll", 12);
362         image->ilt_offset = mono_dynstream_add_zero (&image->code, 8); /* two ILT entries */
363         mono_dynstream_data_align (&image->code);
364
365         image->cli_header_offset = mono_dynstream_add_zero (&image->code, sizeof (MonoCLIHeader));
366
367         for (i=0; i < MONO_TABLE_NUM; ++i) {
368                 image->tables [i].next_idx = 1;
369                 image->tables [i].columns = table_sizes [i];
370         }
371
372         image->image.assembly = (MonoAssembly*)assembly;
373         image->run = assembly->run;
374         image->save = assembly->save;
375         image->pe_kind = 0x1; /* ILOnly */
376         image->machine = 0x14c; /* I386 */
377         
378         mono_profiler_module_loaded (&image->image, MONO_PROFILE_OK);
379
380         dynamic_images_lock ();
381
382         if (!dynamic_images)
383                 dynamic_images = g_ptr_array_new ();
384
385         g_ptr_array_add (dynamic_images, image);
386
387         dynamic_images_unlock ();
388
389         return image;
390 }
391 #else /* DISABLE_REFLECTION_EMIT */
392 MonoDynamicImage*
393 mono_dynamic_image_create (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name)
394 {
395         g_assert_not_reached ();
396         return NULL;
397 }
398 #endif /* DISABLE_REFLECTION_EMIT */
399
400 guint32
401 mono_dynamic_image_add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2)
402 {
403         MONO_REQ_GC_NEUTRAL_MODE;
404
405         guint32 idx;
406         char *copy;
407         gpointer oldkey, oldval;
408
409         copy = (char *)g_malloc (s1+s2);
410         memcpy (copy, b1, s1);
411         memcpy (copy + s1, b2, s2);
412         if (g_hash_table_lookup_extended (assembly->blob_cache, copy, &oldkey, &oldval)) {
413                 g_free (copy);
414                 idx = GPOINTER_TO_UINT (oldval);
415         } else {
416                 idx = mono_dynstream_add_data (&assembly->blob, b1, s1);
417                 mono_dynstream_add_data (&assembly->blob, b2, s2);
418                 g_hash_table_insert (assembly->blob_cache, copy, GUINT_TO_POINTER (idx));
419         }
420         return idx;
421 }
422
423 void
424 mono_dynimage_alloc_table (MonoDynamicTable *table, guint nrows)
425 {
426         MONO_REQ_GC_NEUTRAL_MODE;
427
428         table->rows = nrows;
429         g_assert (table->columns);
430         if (nrows + 1 >= table->alloc_rows) {
431                 while (nrows + 1 >= table->alloc_rows) {
432                         if (table->alloc_rows == 0)
433                                 table->alloc_rows = 16;
434                         else
435                                 table->alloc_rows *= 2;
436                 }
437
438                 table->values = (guint32 *)g_renew (guint32, table->values, (table->alloc_rows) * table->columns);
439         }
440 }
441
442
443 static void
444 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
445 {
446         g_free (key);
447 }
448
449 static void
450 release_hashtable (MonoGHashTable **hash)
451 {
452         if (*hash) {
453                 mono_g_hash_table_destroy (*hash);
454                 *hash = NULL;
455         }
456 }
457
458 void
459 mono_dynamic_image_release_gc_roots (MonoDynamicImage *image)
460 {
461         release_hashtable (&image->token_fixups);
462         release_hashtable (&image->handleref_managed);
463         release_hashtable (&image->tokens);
464         release_hashtable (&image->remapped_tokens);
465         release_hashtable (&image->generic_def_objects);
466 }
467
468 // Free dynamic image pass one: Free resources but not image itself
469 void
470 mono_dynamic_image_free (MonoDynamicImage *image)
471 {
472         MonoDynamicImage *di = image;
473         GList *list;
474         int i;
475
476         if (di->typespec)
477                 g_hash_table_destroy (di->typespec);
478         if (di->typeref)
479                 g_hash_table_destroy (di->typeref);
480         if (di->handleref)
481                 g_hash_table_destroy (di->handleref);
482         if (di->handleref_managed)
483                 mono_g_hash_table_destroy (di->handleref_managed);
484         if (di->tokens)
485                 mono_g_hash_table_destroy (di->tokens);
486         if (di->remapped_tokens)
487                 mono_g_hash_table_destroy (di->remapped_tokens);
488         if (di->generic_def_objects)
489                 mono_g_hash_table_destroy (di->generic_def_objects);
490         if (di->blob_cache) {
491                 g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
492                 g_hash_table_destroy (di->blob_cache);
493         }
494         if (di->standalonesig_cache)
495                 g_hash_table_destroy (di->standalonesig_cache);
496         for (list = di->array_methods; list; list = list->next) {
497                 ArrayMethod *am = (ArrayMethod *)list->data;
498                 mono_sre_array_method_free (am);
499         }
500         g_list_free (di->array_methods);
501         if (di->gen_params) {
502                 for (i = 0; i < di->gen_params->len; i++) {
503                         GenericParamTableEntry *entry = (GenericParamTableEntry *)g_ptr_array_index (di->gen_params, i);
504                         mono_sre_generic_param_table_entry_free (entry);
505                 }
506                 g_ptr_array_free (di->gen_params, TRUE);
507         }
508         if (di->token_fixups)
509                 mono_g_hash_table_destroy (di->token_fixups);
510         if (di->method_to_table_idx)
511                 g_hash_table_destroy (di->method_to_table_idx);
512         if (di->field_to_table_idx)
513                 g_hash_table_destroy (di->field_to_table_idx);
514         if (di->method_aux_hash)
515                 g_hash_table_destroy (di->method_aux_hash);
516         if (di->vararg_aux_hash)
517                 g_hash_table_destroy (di->vararg_aux_hash);
518         g_free (di->strong_name);
519         g_free (di->win32_res);
520         if (di->public_key)
521                 g_free (di->public_key);
522
523         /*g_print ("string heap destroy for image %p\n", di);*/
524         mono_dynamic_stream_reset (&di->sheap);
525         mono_dynamic_stream_reset (&di->code);
526         mono_dynamic_stream_reset (&di->resources);
527         mono_dynamic_stream_reset (&di->us);
528         mono_dynamic_stream_reset (&di->blob);
529         mono_dynamic_stream_reset (&di->tstream);
530         mono_dynamic_stream_reset (&di->guid);
531         for (i = 0; i < MONO_TABLE_NUM; ++i) {
532                 g_free (di->tables [i].values);
533         }
534
535         dynamic_images_lock ();
536
537         if (dynamic_images)
538                 g_ptr_array_remove (dynamic_images, di);
539
540         dynamic_images_unlock ();
541 }
542
543 // Free dynamic image pass two: Free image itself (might never get called in some debug modes)
544 void
545 mono_dynamic_image_free_image (MonoDynamicImage *image)
546 {
547         g_free (image);
548 }