2009-01-14 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / image.c
index 5b7911f6894042bb94304741c12c204bbba61048..bcbfa92294d5d358d9e5aa888377f638f2210030 100644 (file)
 #include <string.h>
 #include "image.h"
 #include "cil-coff.h"
-#include "rawbuffer.h"
 #include "mono-endian.h"
 #include "tabledefs.h"
 #include "tokentype.h"
 #include "metadata-internals.h"
+#include "profiler-private.h"
 #include "loader.h"
+#include "marshal.h"
+#include "coree.h"
 #include <mono/io-layer/io-layer.h>
 #include <mono/utils/mono-logger.h>
 #include <mono/utils/mono-path.h>
+#include <mono/utils/mono-mmap.h>
+#include <mono/utils/mono-io-portability.h>
 #include <mono/metadata/class-internals.h>
+#include <mono/metadata/assembly.h>
+#include <mono/metadata/object-internals.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #ifdef HAVE_UNISTD_H
@@ -39,9 +45,7 @@
  * Keeps track of the various assemblies loaded
  */
 static GHashTable *loaded_images_hash;
-static GHashTable *loaded_images_guid_hash;
 static GHashTable *loaded_images_refonly_hash;
-static GHashTable *loaded_images_refonly_guid_hash;
 
 static gboolean debug_assembly_unload = FALSE;
 
@@ -49,9 +53,11 @@ static gboolean debug_assembly_unload = FALSE;
 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
 static CRITICAL_SECTION images_mutex;
 
+/* returns offset relative to image->raw_data */
 guint32
-mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
+mono_cli_rva_image_map (MonoImage *image, guint32 addr)
 {
+       MonoCLIImageInfo *iinfo = image->image_info;
        const int top = iinfo->cli_section_count;
        MonoSectionTable *tables = iinfo->cli_section_tables;
        int i;
@@ -59,6 +65,10 @@ mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
        for (i = 0; i < top; i++){
                if ((addr >= tables->st_virtual_address) &&
                    (addr < tables->st_virtual_address + tables->st_raw_data_size)){
+#ifdef PLATFORM_WIN32
+                       if (image->is_module_handle)
+                               return addr;
+#endif
                        return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
                }
                tables++;
@@ -92,6 +102,10 @@ mono_image_rva_map (MonoImage *image, guint32 addr)
                                if (!mono_image_ensure_section_idx (image, i))
                                        return NULL;
                        }
+#ifdef PLATFORM_WIN32
+                       if (image->is_module_handle)
+                               return image->raw_data + addr;
+#endif
                        return (char*)iinfo->cli_sections [i] +
                                (addr - tables->st_virtual_address);
                }
@@ -111,9 +125,7 @@ mono_images_init (void)
        InitializeCriticalSection (&images_mutex);
 
        loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
-       loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
        loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
-       loaded_images_refonly_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
 
        debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
 }
@@ -129,9 +141,7 @@ mono_images_cleanup (void)
        DeleteCriticalSection (&images_mutex);
 
        g_hash_table_destroy (loaded_images_hash);
-       g_hash_table_destroy (loaded_images_guid_hash);
        g_hash_table_destroy (loaded_images_refonly_hash);
-       g_hash_table_destroy (loaded_images_refonly_guid_hash);
 }
 
 /**
@@ -162,6 +172,11 @@ mono_image_ensure_section_idx (MonoImage *image, int section)
 
        if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
                return FALSE;
+#ifdef PLATFORM_WIN32
+       if (image->is_module_handle)
+               iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
+       else
+#endif
        /* FIXME: we ignore the writable flag since we don't patch the binary */
        iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
        return TRUE;
@@ -232,7 +247,7 @@ load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
 {
        guint32 offset;
        
-       offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
+       offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
        if (offset == INVALID_ADDRESS)
                return FALSE;
 
@@ -300,7 +315,7 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
        guint32 pad;
        char *ptr;
        
-       offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
+       offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
        if (offset == INVALID_ADDRESS)
                return FALSE;
 
@@ -445,7 +460,7 @@ mono_image_check_for_module_cctor (MonoImage *image)
        MonoTableInfo *t, *mt;
        t = &image->tables [MONO_TABLE_TYPEDEF];
        mt = &image->tables [MONO_TABLE_METHOD];
-       if (mono_get_runtime_info ()->framework_version [0] == '1') {
+       if (mono_framework_version () == 1) {
                image->checked_module_cctor = TRUE;
                return;
        }
@@ -548,6 +563,10 @@ mono_image_load_module (MonoImage *image, int idx)
                        if (image->modules [idx - 1]) {
                                mono_image_addref (image->modules [idx - 1]);
                                image->modules [idx - 1]->assembly = image->assembly;
+#ifdef PLATFORM_WIN32
+                               if (image->modules [idx - 1]->is_module_handle)
+                                       mono_image_fixup_vtable (image->modules [idx - 1]);
+#endif
                                /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
                        }
                        g_free (module_ref);
@@ -562,22 +581,6 @@ mono_image_load_module (MonoImage *image, int idx)
        return image->modules [idx - 1];
 }
 
-static void
-register_guid (gpointer key, gpointer value, gpointer user_data)
-{
-       MonoImage *image = (MonoImage*)value;
-
-       if (!g_hash_table_lookup (loaded_images_guid_hash, image))
-               g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
-}
-
-static void
-build_guid_table (gboolean refonly)
-{
-       GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
-       g_hash_table_foreach (loaded_images, register_guid, NULL);
-}
-
 static gpointer
 class_key_extract (gpointer value)
 {
@@ -597,87 +600,55 @@ class_next_value (gpointer value)
 void
 mono_image_init (MonoImage *image)
 {
-       image->mempool = mono_mempool_new ();
-       image->method_cache = g_hash_table_new (NULL, NULL);
+       image->mempool = mono_mempool_new_size (512);
        mono_internal_hash_table_init (&image->class_cache,
                                       g_direct_hash,
                                       class_key_extract,
                                       class_next_value);
        image->field_cache = g_hash_table_new (NULL, NULL);
 
-       image->delegate_begin_invoke_cache = 
-               g_hash_table_new ((GHashFunc)mono_signature_hash, 
-                                 (GCompareFunc)mono_metadata_signature_equal);
-       image->delegate_end_invoke_cache = 
-               g_hash_table_new ((GHashFunc)mono_signature_hash, 
-                                 (GCompareFunc)mono_metadata_signature_equal);
-       image->delegate_invoke_cache = 
-               g_hash_table_new ((GHashFunc)mono_signature_hash, 
-                                 (GCompareFunc)mono_metadata_signature_equal);
-       image->runtime_invoke_cache  = 
-               g_hash_table_new ((GHashFunc)mono_signature_hash, 
-                                 (GCompareFunc)mono_metadata_signature_equal);
-       
-       image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
        image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->cominterop_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->cominterop_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-
-       image->ldfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->ldflda_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->ldfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->stfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->stfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->castclass_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       image->proxy_isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
 
        image->typespec_cache = g_hash_table_new (NULL, NULL);
        image->memberref_signatures = g_hash_table_new (NULL, NULL);
        image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
        image->method_signatures = g_hash_table_new (NULL, NULL);
-}
 
-static MonoImage *
-do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
-                   gboolean care_about_cli)
-{
-       MonoCLIImageInfo *iinfo;
-       MonoDotNetHeader *header;
-       MonoMSDOSHeader msdos;
-       guint32 offset = 0;
-
-       mono_image_init (image);
+       image->property_hash = mono_property_hash_new ();
+}
 
-       iinfo = image->image_info;
-       header = &iinfo->cli_header;
-               
-       if (status)
-               *status = MONO_IMAGE_IMAGE_INVALID;
+#if G_BYTE_ORDER != G_LITTLE_ENDIAN
+#define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
+#define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
+#define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
+#define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
+#else
+#define SWAP64(x)
+#define SWAP32(x)
+#define SWAP16(x)
+#define SWAPPDE(x)
+#endif
 
-       if (offset + sizeof (msdos) > image->raw_data_len)
-               goto invalid_image;
-       memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
-       
-       if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
-               goto invalid_image;
-       
-       msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
+/*
+ * Returns < 0 to indicate an error.
+ */
+static int
+do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
+{
+       MonoDotNetHeader64 header64;
 
-       offset = msdos.pe_offset;
+#ifdef PLATFORM_WIN32
+       if (!image->is_module_handle)
+#endif
+       if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
+               return -1;
 
-       if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
-               goto invalid_image;
        memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
-       offset += sizeof (MonoDotNetHeader);
 
-#if G_BYTE_ORDER != G_LITTLE_ENDIAN
-#define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
-#define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
-#define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
+       if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
+               return -1;
+
+       /* endian swap the fields common between PE and PE+ */
        SWAP32 (header->coff.coff_time);
        SWAP32 (header->coff.coff_symptr);
        SWAP32 (header->coff.coff_symcount);
@@ -687,15 +658,71 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
        SWAP16 (header->coff.coff_attributes);
        /* MonoPEHeader */
        SWAP32 (header->pe.pe_code_size);
-       SWAP32 (header->pe.pe_data_size);
        SWAP32 (header->pe.pe_uninit_data_size);
        SWAP32 (header->pe.pe_rva_entry_point);
        SWAP32 (header->pe.pe_rva_code_base);
        SWAP32 (header->pe.pe_rva_data_base);
        SWAP16 (header->pe.pe_magic);
 
+       /* now we are ready for the basic tests */
+
+       if (header->pe.pe_magic == 0x10B) {
+               offset += sizeof (MonoDotNetHeader);
+               SWAP32 (header->pe.pe_data_size);
+               if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
+                       return -1;
+
+               SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
+               SWAP32  (header->nt.pe_stack_reserve);
+               SWAP32  (header->nt.pe_stack_commit);
+               SWAP32  (header->nt.pe_heap_reserve);
+               SWAP32  (header->nt.pe_heap_commit);
+       } else if (header->pe.pe_magic == 0x20B) {
+               /* PE32+ file format */
+               if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
+                       return -1;
+               memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
+               offset += sizeof (MonoDotNetHeader64);
+               /* copy the fields already swapped. the last field, pe_data_size, is missing */
+               memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
+               /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
+                * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
+                */
+               SWAP64  (header64.nt.pe_image_base);
+               header->nt.pe_image_base = header64.nt.pe_image_base;
+               SWAP64  (header64.nt.pe_stack_reserve);
+               header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
+               SWAP64  (header64.nt.pe_stack_commit);
+               header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
+               SWAP64  (header64.nt.pe_heap_reserve);
+               header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
+               SWAP64  (header64.nt.pe_heap_commit);
+               header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
+
+               header->nt.pe_section_align = header64.nt.pe_section_align;
+               header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
+               header->nt.pe_os_major = header64.nt.pe_os_major;
+               header->nt.pe_os_minor = header64.nt.pe_os_minor;
+               header->nt.pe_user_major = header64.nt.pe_user_major;
+               header->nt.pe_user_minor = header64.nt.pe_user_minor;
+               header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
+               header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
+               header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
+               header->nt.pe_image_size = header64.nt.pe_image_size;
+               header->nt.pe_header_size = header64.nt.pe_header_size;
+               header->nt.pe_checksum = header64.nt.pe_checksum;
+               header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
+               header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
+               header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
+               header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
+
+               /* copy the datadir */
+               memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
+       } else {
+               return -1;
+       }
+
        /* MonoPEHeaderNT: not used yet */
-       SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
        SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
        SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
        SWAP16  (header->nt.pe_os_major);            /* must be 4 */
@@ -710,10 +737,6 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
        SWAP32  (header->nt.pe_checksum);
        SWAP16  (header->nt.pe_subsys_required);
        SWAP16  (header->nt.pe_dll_flags);
-       SWAP32  (header->nt.pe_stack_reserve);
-       SWAP32  (header->nt.pe_stack_commit);
-       SWAP32  (header->nt.pe_heap_reserve);
-       SWAP32  (header->nt.pe_heap_commit);
        SWAP32  (header->nt.pe_loader_flags);
        SWAP32  (header->nt.pe_data_dir_count);
 
@@ -735,19 +758,57 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
        SWAPPDE (header->datadir.pe_cli_header);
        SWAPPDE (header->datadir.pe_reserved);
 
-#undef SWAP32
-#undef SWAP16
-#undef SWAPPDE
+#ifdef PLATFORM_WIN32
+       if (image->is_module_handle)
+               image->raw_data_len = header->nt.pe_image_size;
 #endif
 
-       if (header->coff.coff_machine != 0x14c)
+       return offset;
+}
+
+static MonoImage *
+do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
+                   gboolean care_about_cli)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoDotNetHeader *header;
+       MonoMSDOSHeader msdos;
+       gint32 offset = 0;
+
+       mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
+
+       mono_image_init (image);
+
+       iinfo = image->image_info;
+       header = &iinfo->cli_header;
+               
+       if (status)
+               *status = MONO_IMAGE_IMAGE_INVALID;
+
+#ifdef PLATFORM_WIN32
+       if (!image->is_module_handle)
+#endif
+       if (offset + sizeof (msdos) > image->raw_data_len)
+               goto invalid_image;
+       memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
+       
+       if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
                goto invalid_image;
+       
+       msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
+
+       offset = msdos.pe_offset;
 
-       if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
+       offset = do_load_header (image, header, offset);
+       if (offset < 0)
                goto invalid_image;
 
-       if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
+       /*
+        * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
+        * we skip this test.
+       if (header->coff.coff_machine != 0x14c)
                goto invalid_image;
+       */
 
 #if 0
        /*
@@ -784,10 +845,11 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
                goto invalid_image;
 
        /* modules don't have an assembly table row */
-       if (image->tables [MONO_TABLE_ASSEMBLY].rows)
+       if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
                image->assembly_name = mono_metadata_string_heap (image, 
                        mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
                                        0, MONO_ASSEMBLY_NAME));
+       }
 
        image->module_name = mono_metadata_string_heap (image, 
                        mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
@@ -796,12 +858,14 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
        load_modules (image);
 
 done:
+       mono_profiler_module_loaded (image, MONO_PROFILE_OK);
        if (status)
                *status = MONO_IMAGE_OK;
 
        return image;
 
 invalid_image:
+       mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
        mono_image_close (image);
                return NULL;
 }
@@ -816,9 +880,19 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
        struct stat stat_buf;
 
        if ((filed = fopen (fname, "rb")) == NULL){
-               if (status)
-                       *status = MONO_IMAGE_ERROR_ERRNO;
-               return NULL;
+               if (IS_PORTABILITY_SET) {
+                       gchar *ffname = mono_portability_find_file (fname, TRUE);
+                       if (ffname) {
+                               filed = fopen (ffname, "rb");
+                               g_free (ffname);
+                       }
+               }
+
+               if (filed == NULL) {
+                       if (status)
+                               *status = MONO_IMAGE_ERROR_ERRNO;
+                       return NULL;
+               }
        }
 
        if (fstat (fileno (filed), &stat_buf)) {
@@ -828,15 +902,24 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
                return NULL;
        }
        image = g_new0 (MonoImage, 1);
-       image->file_descr = filed;
+       image->raw_buffer_used = TRUE;
        image->raw_data_len = stat_buf.st_size;
-       image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
+       image->raw_data = mono_file_map (stat_buf.st_size, MONO_MMAP_READ|MONO_MMAP_PRIVATE, fileno (filed), 0, &image->raw_data_handle);
+       if (!image->raw_data) {
+               fclose (filed);
+               g_free (image);
+               if (status)
+                       *status = MONO_IMAGE_IMAGE_INVALID;
+               return NULL;
+       }
        iinfo = g_new0 (MonoCLIImageInfo, 1);
        image->image_info = iinfo;
        image->name = mono_path_resolve_symlinks (fname);
        image->ref_only = refonly;
        image->ref_count = 1;
 
+       fclose (filed);
+
        return do_mono_image_load (image, status, care_about_cli);
 }
 
@@ -866,16 +949,36 @@ mono_image_loaded (const char *name)
        return mono_image_loaded_full (name, FALSE);
 }
 
+typedef struct {
+       MonoImage *res;
+       const char* guid;
+} GuidData;
+
+static void
+find_by_guid (gpointer key, gpointer val, gpointer user_data)
+{
+       GuidData *data = user_data;
+       MonoImage *image;
+
+       if (data->res)
+               return;
+       image = val;
+       if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
+               data->res = image;
+}
+
 MonoImage *
 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
 {
-       MonoImage *res;
-       GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
+       GuidData data;
+       GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
+       data.res = NULL;
+       data.guid = guid;
 
        mono_images_lock ();
-       res = g_hash_table_lookup (loaded_images, guid);
+       g_hash_table_foreach (loaded_images, find_by_guid, &data);
        mono_images_unlock ();
-       return res;
+       return data.res;
 }
 
 MonoImage *
@@ -903,7 +1006,6 @@ register_image (MonoImage *image)
        g_hash_table_insert (loaded_images, image->name, image);
        if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
                g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
-       g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
        mono_images_unlock ();
 
        return image;
@@ -954,6 +1056,31 @@ mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, Mon
        return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
 }
 
+#ifdef PLATFORM_WIN32
+/* fname is not duplicated. */
+MonoImage*
+mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
+{
+       MonoImage* image;
+       MonoCLIImageInfo* iinfo;
+
+       image = g_new0 (MonoImage, 1);
+       image->raw_data = (char*) module_handle;
+       image->is_module_handle = TRUE;
+       iinfo = g_new0 (MonoCLIImageInfo, 1);
+       image->image_info = iinfo;
+       image->name = fname;
+       image->ref_count = has_entry_point ? 0 : 1;
+       image->has_entry_point = has_entry_point;
+
+       image = do_mono_image_load (image, status, TRUE);
+       if (image == NULL)
+               return NULL;
+
+       return register_image (image);
+}
+#endif
+
 MonoImage *
 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
 {
@@ -963,6 +1090,72 @@ mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean r
        
        g_return_val_if_fail (fname != NULL, NULL);
        
+#ifdef PLATFORM_WIN32
+       /* Load modules using LoadLibrary. */
+       if (!refonly && coree_module_handle) {
+               HMODULE module_handle;
+               guint16 *fname_utf16;
+               DWORD last_error;
+
+               absfname = mono_path_resolve_symlinks (fname);
+               fname_utf16 = NULL;
+
+               /* There is little overhead because the OS loader lock is held by LoadLibrary. */
+               mono_images_lock ();
+               image = g_hash_table_lookup (loaded_images_hash, absfname);
+               if (image) {
+                       g_assert (image->is_module_handle);
+                       if (image->has_entry_point && image->ref_count == 0) {
+                               /* Increment reference count on images loaded outside of the runtime. */
+                               fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
+                               /* The image is already loaded because _CorDllMain removes images from the hash. */
+                               module_handle = LoadLibrary (fname_utf16);
+                               g_assert (module_handle == (HMODULE) image->raw_data);
+                       }
+                       mono_image_addref (image);
+                       mono_images_unlock ();
+                       if (fname_utf16)
+                               g_free (fname_utf16);
+                       g_free (absfname);
+                       return image;
+               }
+
+               fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
+               module_handle = MonoLoadImage (fname_utf16);
+               if (status && module_handle == NULL)
+                       last_error = GetLastError ();
+
+               /* mono_image_open_from_module_handle is called by _CorDllMain. */
+               image = g_hash_table_lookup (loaded_images_hash, absfname);
+               if (image)
+                       mono_image_addref (image);
+               mono_images_unlock ();
+
+               g_free (fname_utf16);
+
+               if (module_handle == NULL) {
+                       g_assert (!image);
+                       g_free (absfname);
+                       if (status) {
+                               if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
+                                       *status = MONO_IMAGE_IMAGE_INVALID;
+                               else
+                                       *status = MONO_IMAGE_ERROR_ERRNO;
+                       }
+                       return NULL;
+               }
+
+               if (image) {
+                       g_assert (image->is_module_handle);
+                       g_assert (image->has_entry_point);
+                       g_free (absfname);
+                       return image;
+               }
+
+               return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
+       }
+#endif
+
        absfname = mono_path_canonicalize (fname);
 
        /*
@@ -1025,6 +1218,57 @@ mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
        return(do_mono_image_open (fname, status, FALSE, FALSE));
 }
 
+void
+mono_image_fixup_vtable (MonoImage *image)
+{
+#ifdef PLATFORM_WIN32
+       MonoCLIImageInfo *iinfo;
+       MonoPEDirEntry *de;
+       MonoVTableFixup *vtfixup;
+       int count;
+       gpointer slot;
+       guint16 slot_type;
+       int slot_count;
+
+       g_assert (image->is_module_handle);
+
+       iinfo = image->image_info;
+       de = &iinfo->cli_cli_header.ch_vtable_fixups;
+       if (!de->rva || !de->size)
+               return;
+       vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
+       if (!vtfixup)
+               return;
+       
+       count = de->size / sizeof (MonoVTableFixup);
+       while (count--) {
+               if (!vtfixup->rva || !vtfixup->count)
+                       continue;
+
+               slot = mono_image_rva_map (image, vtfixup->rva);
+               g_assert (slot);
+               slot_type = vtfixup->type;
+               slot_count = vtfixup->count;
+               if (slot_type & VTFIXUP_TYPE_32BIT)
+                       while (slot_count--) {
+                               *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
+                               ((guint32*) slot)++;
+                       }
+               else if (slot_type & VTFIXUP_TYPE_64BIT)
+                       while (slot_count--) {
+                               *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
+                               ((guint64*) slot)++;
+                       }
+               else
+                       g_assert_not_reached();
+
+               vtfixup++;
+       }
+#else
+       g_assert_not_reached();
+#endif
+}
+
 static void
 free_hash_table (gpointer key, gpointer val, gpointer user_data)
 {
@@ -1039,12 +1283,6 @@ free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
 }
 */
 
-static void
-free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
-{
-       g_free (key);
-}
-
 static void
 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
 {
@@ -1081,6 +1319,13 @@ mono_dynamic_stream_reset (MonoDynamicStream* stream)
        }
 }
 
+static inline void
+free_hash (GHashTable *hash)
+{
+       if (hash)
+               g_hash_table_destroy (hash);
+}
+
 /**
  * mono_image_close:
  * @image: The image file we wish to close
@@ -1092,7 +1337,7 @@ void
 mono_image_close (MonoImage *image)
 {
        MonoImage *image2;
-       GHashTable *loaded_images, *loaded_images_guid;
+       GHashTable *loaded_images;
        int i;
 
        g_return_if_fail (image != NULL);
@@ -1100,35 +1345,66 @@ mono_image_close (MonoImage *image)
        if (InterlockedDecrement (&image->ref_count) > 0)
                return;
 
+#ifdef PLATFORM_WIN32
+       if (image->is_module_handle && image->has_entry_point) {
+               mono_images_lock ();
+               if (image->ref_count == 0) {
+                       /* Image will be closed by _CorDllMain. */
+                       FreeLibrary ((HMODULE) image->raw_data);
+                       mono_images_unlock ();
+                       return;
+               }
+               mono_images_unlock ();
+       }
+#endif
+
+       mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
+
        mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
 
        mono_metadata_clean_for_image (image);
 
+       /*
+        * The caches inside a MonoImage might refer to metadata which is stored in referenced 
+        * assemblies, so we can't release these references in mono_assembly_close () since the
+        * MonoImage might outlive its associated MonoAssembly.
+        */
+       if (image->references) {
+               int i;
+
+               for (i = 0; image->references [i]; i++) {
+                       if (image->references [i])
+                               mono_assembly_close (image->references [i]);
+               }
+
+               g_free (image->references);
+               image->references = NULL;
+       }
+
        mono_images_lock ();
        loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
-       loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
        image2 = g_hash_table_lookup (loaded_images, image->name);
        if (image == image2) {
                /* This is not true if we are called from mono_image_open () */
                g_hash_table_remove (loaded_images, image->name);
-               g_hash_table_remove (loaded_images_guid, image->guid);
        }
        if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
                g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
 
-       /* Multiple images might have the same guid */
-       build_guid_table (image->ref_only);
+#ifdef PLATFORM_WIN32
+       if (image->is_module_handle && !image->has_entry_point)
+               FreeLibrary ((HMODULE) image->raw_data);
+#endif
 
        mono_images_unlock ();
 
-       if (image->file_descr) {
-               fclose (image->file_descr);
-               image->file_descr = NULL;
+       if (image->raw_buffer_used) {
                if (image->raw_data != NULL)
-                       mono_raw_buffer_free (image->raw_data);
+                       mono_file_unmap (image->raw_data, image->raw_data_handle);
        }
        
        if (image->raw_data_allocated) {
+               /* FIXME: do we need this? (image is disposed anyway) */
                /* image->raw_metadata and cli_sections might lie inside image->raw_data */
                MonoCLIImageInfo *ii = image->image_info;
 
@@ -1153,7 +1429,10 @@ mono_image_close (MonoImage *image)
                g_free (image->files);
        }
 
-       g_hash_table_destroy (image->method_cache);
+       if (image->method_cache)
+               mono_value_hash_table_destroy (image->method_cache);
+       if (image->methodref_cache)
+               g_hash_table_destroy (image->methodref_cache);
        mono_internal_hash_table_destroy (&image->class_cache);
        g_hash_table_destroy (image->field_cache);
        if (image->array_cache) {
@@ -1166,27 +1445,31 @@ mono_image_close (MonoImage *image)
                g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
                g_hash_table_destroy (image->name_cache);
        }
-       g_hash_table_destroy (image->native_wrapper_cache);
-       g_hash_table_destroy (image->managed_wrapper_cache);
-       g_hash_table_destroy (image->delegate_begin_invoke_cache);
-       g_hash_table_destroy (image->delegate_end_invoke_cache);
-       g_hash_table_destroy (image->delegate_invoke_cache);
-       g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
-       g_hash_table_destroy (image->remoting_invoke_cache);
-       g_hash_table_destroy (image->runtime_invoke_cache);
-       g_hash_table_destroy (image->synchronized_cache);
-       g_hash_table_destroy (image->unbox_wrapper_cache);
-       g_hash_table_destroy (image->cominterop_invoke_cache);
-       g_hash_table_destroy (image->cominterop_wrapper_cache);
-       g_hash_table_destroy (image->typespec_cache);
-       g_hash_table_destroy (image->ldfld_wrapper_cache);
-       g_hash_table_destroy (image->ldflda_wrapper_cache);
-       g_hash_table_destroy (image->ldfld_remote_wrapper_cache);
-       g_hash_table_destroy (image->stfld_wrapper_cache);
-       g_hash_table_destroy (image->stfld_remote_wrapper_cache);
-       g_hash_table_destroy (image->isinst_cache);
-       g_hash_table_destroy (image->castclass_cache);
-       g_hash_table_destroy (image->proxy_isinst_cache);
+
+       free_hash (image->native_wrapper_cache);
+       free_hash (image->managed_wrapper_cache);
+       free_hash (image->delegate_begin_invoke_cache);
+       free_hash (image->delegate_end_invoke_cache);
+       free_hash (image->delegate_invoke_cache);
+       free_hash (image->delegate_abstract_invoke_cache);
+       if (image->remoting_invoke_cache)
+               g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
+       free_hash (image->remoting_invoke_cache);
+       free_hash (image->runtime_invoke_cache);
+       free_hash (image->runtime_invoke_direct_cache);
+       free_hash (image->synchronized_cache);
+       free_hash (image->unbox_wrapper_cache);
+       free_hash (image->cominterop_invoke_cache);
+       free_hash (image->cominterop_wrapper_cache);
+       free_hash (image->typespec_cache);
+       free_hash (image->ldfld_wrapper_cache);
+       free_hash (image->ldflda_wrapper_cache);
+       free_hash (image->stfld_wrapper_cache);
+       free_hash (image->isinst_cache);
+       free_hash (image->castclass_cache);
+       free_hash (image->proxy_isinst_cache);
+       free_hash (image->thunk_invoke_cache);
+       free_hash (image->static_rgctx_invoke_cache);
 
        /* The ownership of signatures is not well defined */
        //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
@@ -1195,6 +1478,15 @@ mono_image_close (MonoImage *image)
        g_hash_table_destroy (image->helper_signatures);
        g_hash_table_destroy (image->method_signatures);
 
+       if (image->generic_class_cache)
+               g_hash_table_destroy (image->generic_class_cache);
+
+       if (image->rgctx_template_hash)
+               g_hash_table_destroy (image->rgctx_template_hash);
+
+       if (image->property_hash)
+               mono_property_hash_destroy (image->property_hash);
+
        if (image->interface_bitset) {
                mono_unload_interface_ids (image->interface_bitset);
                mono_bitset_free (image->interface_bitset);
@@ -1219,6 +1511,7 @@ mono_image_close (MonoImage *image)
                g_free (image->modules_loaded);
        if (image->references)
                g_free (image->references);
+       mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
        /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
        if (!image->dynamic) {
                if (debug_assembly_unload)
@@ -1229,47 +1522,12 @@ mono_image_close (MonoImage *image)
                }
        } else {
                /* Dynamic images are GC_MALLOCed */
-               struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
-               int i;
                g_free ((char*)image->module_name);
-               if (di->typespec)
-                       g_hash_table_destroy (di->typespec);
-               if (di->typeref)
-                       g_hash_table_destroy (di->typeref);
-               if (di->handleref)
-                       g_hash_table_destroy (di->handleref);
-               if (di->tokens)
-                       mono_g_hash_table_destroy (di->tokens);
-               if (di->blob_cache) {
-                       g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
-                       g_hash_table_destroy (di->blob_cache);
-               }
-               g_list_free (di->array_methods);
-               if (di->gen_params)
-                       g_ptr_array_free (di->gen_params, TRUE);
-               if (di->token_fixups)
-                       mono_g_hash_table_destroy (di->token_fixups);
-               if (di->method_to_table_idx)
-                       g_hash_table_destroy (di->method_to_table_idx);
-               if (di->field_to_table_idx)
-                       g_hash_table_destroy (di->field_to_table_idx);
-               if (di->method_aux_hash)
-                       g_hash_table_destroy (di->method_aux_hash);
-               g_free (di->strong_name);
-               g_free (di->win32_res);
-               /*g_print ("string heap destroy for image %p\n", di);*/
-               mono_dynamic_stream_reset (&di->sheap);
-               mono_dynamic_stream_reset (&di->code);
-               mono_dynamic_stream_reset (&di->resources);
-               mono_dynamic_stream_reset (&di->us);
-               mono_dynamic_stream_reset (&di->blob);
-               mono_dynamic_stream_reset (&di->tstream);
-               mono_dynamic_stream_reset (&di->guid);
-               for (i = 0; i < MONO_TABLE_NUM; ++i) {
-                       g_free (di->tables [i].values);
-               }
+               mono_dynamic_image_free ((MonoDynamicImage*)image);
                mono_mempool_destroy (image->mempool);
        }
+
+       mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
 }
 
 /** 
@@ -1313,16 +1571,11 @@ mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
         * Level 2 holds a directory entry for each language pointing to
         * the actual data.
         */
-       name_offset = GUINT32_FROM_LE (entry->name_offset) & 0x7fffffff;
-       dir_offset = GUINT32_FROM_LE (entry->dir_offset) & 0x7fffffff;
+       is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
+       name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
 
-#if G_BYTE_ORDER != G_LITTLE_ENDIAN
-       is_string = (GUINT32_FROM_LE (entry->name_offset) & 0x80000000) != 0;
-       is_dir = (GUINT32_FROM_LE (entry->dir_offset) & 0x80000000) != 0;
-#else
-       is_string = entry->name_is_string;
-       is_dir = entry->is_dir;
-#endif
+       is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
+       dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
 
        if(level==0) {
                if((is_string==FALSE && name_offset!=res_id) ||
@@ -1511,8 +1764,11 @@ mono_image_load_file_for_image (MonoImage *image, int fileidx)
        if (fileidx < 1 || fileidx > t->rows)
                return NULL;
 
-       if (image->files && image->files [fileidx - 1])
+       mono_loader_lock ();
+       if (image->files && image->files [fileidx - 1]) {
+               mono_loader_unlock ();
                return image->files [fileidx - 1];
+       }
 
        if (!image->files)
                image->files = g_new0 (MonoImage*, t->rows);
@@ -1532,7 +1788,12 @@ mono_image_load_file_for_image (MonoImage *image, int fileidx)
                }
 
                image->files [fileidx - 1] = res;
+#ifdef PLATFORM_WIN32
+               if (res->is_module_handle)
+                       mono_image_fixup_vtable (res);
+#endif
        }
+       mono_loader_unlock ();
        g_free (name);
        g_free (base_dir);
        return res;
@@ -1582,25 +1843,14 @@ mono_image_strong_name_position (MonoImage *image, guint32 *size)
 {
        MonoCLIImageInfo *iinfo = image->image_info;
        MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
-       const int top = iinfo->cli_section_count;
-       MonoSectionTable *tables = iinfo->cli_section_tables;
-       int i;
-       guint32 addr = de->rva;
-       
+       guint32 pos;
+
        if (size)
                *size = de->size;
        if (!de->size || !de->rva)
                return 0;
-       for (i = 0; i < top; i++){
-               if ((addr >= tables->st_virtual_address) &&
-                   (addr < tables->st_virtual_address + tables->st_raw_data_size)){
-                       return tables->st_raw_data_ptr +
-                               (addr - tables->st_virtual_address);
-               }
-               tables++;
-       }
-
-       return 0;
+       pos = mono_cli_rva_image_map (image, de->rva);
+       return pos == INVALID_ADDRESS ? 0 : pos;
 }
 
 /**
@@ -1621,6 +1871,12 @@ mono_image_get_public_key (MonoImage *image, guint32 *size)
 {
        const char *pubkey;
        guint32 len, tok;
+
+       if (image->dynamic) {
+               if (size)
+                       *size = ((MonoDynamicImage*)image)->public_key_len;
+               return (char*)((MonoDynamicImage*)image)->public_key;
+       }
        if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
                return NULL;
        tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
@@ -1735,3 +1991,25 @@ mono_image_has_authenticode_entry (MonoImage *image)
        // the Authenticode "pre" (non ASN.1) header is 8 bytes long
        return ((de->rva != 0) && (de->size > 8));
 }
+
+gpointer
+mono_image_alloc (MonoImage *image, guint size)
+{
+       mono_perfcounters->loader_bytes += size;
+       return mono_mempool_alloc (image->mempool, size);
+}
+
+gpointer
+mono_image_alloc0 (MonoImage *image, guint size)
+{
+       mono_perfcounters->loader_bytes += size;
+       return mono_mempool_alloc0 (image->mempool, size);
+}
+
+char*
+mono_image_strdup (MonoImage *image, const char *s)
+{
+       mono_perfcounters->loader_bytes += strlen (s);
+       return mono_mempool_strdup (image->mempool, s);
+}
+