2009-04-28 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mono / metadata / image.c
index 75e86135727936606e957b7e01ed1a92e72d4e3a..d99b71531531a6508cc6b0e33c15b9ac214f8676 100644 (file)
@@ -6,7 +6,8 @@
  *   Miguel de Icaza (miguel@ximian.com)
  *   Paolo Molaro (lupus@ximian.com)
  *
- * (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
+ * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+ * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
  *
  */
 #include <config.h>
 #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 <mono/metadata/security-core-clr.h>
+#include <mono/metadata/verify-internals.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 
 #define INVALID_ADDRESS 0xffffffff
 
  * 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 gboolean debug_assembly_unload = FALSE;
 
+#define mono_images_lock() EnterCriticalSection (&images_mutex)
+#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;
@@ -47,6 +68,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++;
@@ -54,6 +79,17 @@ mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
        return INVALID_ADDRESS;
 }
 
+/**
+ * mono_images_rva_map:
+ * @image: a MonoImage
+ * @addr: relative virtual address (RVA)
+ *
+ * This is a low-level routine used by the runtime to map relative
+ * virtual address (RVA) into their location in memory. 
+ *
+ * Returns: the address in memory for the given RVA, or NULL if the
+ * RVA is not valid for this image. 
+ */
 char *
 mono_image_rva_map (MonoImage *image, guint32 addr)
 {
@@ -69,6 +105,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);
                }
@@ -77,48 +117,6 @@ mono_image_rva_map (MonoImage *image, guint32 addr)
        return NULL;
 }
 
-static gchar *
-canonicalize_path (const char *path)
-{
-       gchar *abspath, *pos, *lastpos, *dest;
-       int backc;
-
-       if (g_path_is_absolute (path)) {
-               abspath = g_strdup (path);
-       } else {
-               gchar *tmpdir = g_get_current_dir ();
-               abspath = g_build_filename (tmpdir, path, NULL);
-               g_free (tmpdir);
-       }
-
-       abspath = g_strreverse (abspath);
-
-       backc = 0;
-       dest = lastpos = abspath;
-       pos = strchr (lastpos, G_DIR_SEPARATOR);
-
-       while (pos != NULL) {
-               int len = pos - lastpos;
-               if (len == 1 && lastpos [0] == '.') {
-                       // nop
-               } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
-                       backc++;
-               } else if (len > 0) {
-                       if (backc > 0) {
-                               backc--;
-                       } else {
-                               if (dest != lastpos) strncpy (dest, lastpos, len + 1);
-                               dest += len + 1;
-                       }
-               }
-               lastpos = pos + 1;
-               pos = strchr (lastpos, G_DIR_SEPARATOR);
-       }
-       
-       if (dest != lastpos) strcpy (dest, lastpos);
-       return g_strreverse (abspath);
-}
-
 /**
  * mono_images_init:
  *
@@ -130,7 +128,23 @@ 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);
+
+       debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
+}
+
+/**
+ * mono_images_cleanup:
+ *
+ *  Free all resources used by this module.
+ */
+void
+mono_images_cleanup (void)
+{
+       DeleteCriticalSection (&images_mutex);
+
+       g_hash_table_destroy (loaded_images_hash);
+       g_hash_table_destroy (loaded_images_refonly_hash);
 }
 
 /**
@@ -161,6 +175,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;
@@ -231,7 +250,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;
 
@@ -299,7 +318,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;
 
@@ -314,7 +333,12 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
        if (strncmp (ptr, "BSJB", 4) == 0){
                guint32 version_string_len;
 
-               ptr += 12;
+               ptr += 4;
+               image->md_version_major = read16 (ptr);
+               ptr += 2;
+               image->md_version_minor = read16 (ptr);
+               ptr += 6;
+
                version_string_len = read32 (ptr);
                ptr += 4;
                image->version = g_strndup (ptr, version_string_len);
@@ -353,8 +377,11 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
                        image->heap_guid.size = read32 (ptr + 4);
                        ptr += 8 + 6;
                } else if (strncmp (ptr + 8, "#-", 3) == 0) {
-                       g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
-                       return FALSE;
+                       image->heap_tables.data = image->raw_metadata + read32 (ptr);
+                       image->heap_tables.size = read32 (ptr + 4);
+                       ptr += 8 + 3;
+                       image->uncompressed_metadata = TRUE;
+                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).\n", image->name);
                } else {
                        g_message ("Unknown heap type: %s\n", ptr + 8);
                        ptr += 8 + strlen (ptr + 8) + 1;
@@ -367,7 +394,7 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
        g_assert (image->heap_guid.data);
        g_assert (image->heap_guid.size >= 16);
 
-       image->guid = mono_guid_to_string (image->heap_guid.data);
+       image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
 
        return TRUE;
 }
@@ -431,202 +458,200 @@ load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
 }
 
 void
-mono_image_add_to_name_cache (MonoImage *image, const char *nspace, 
-                                                         const char *name, guint32 index)
+mono_image_check_for_module_cctor (MonoImage *image)
 {
-       GHashTable *nspace_table;
-       GHashTable *name_cache = image->name_cache;
-
-       if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
-               nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
-               g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
+       MonoTableInfo *t, *mt;
+       t = &image->tables [MONO_TABLE_TYPEDEF];
+       mt = &image->tables [MONO_TABLE_METHOD];
+       if (mono_framework_version () == 1) {
+               image->checked_module_cctor = TRUE;
+               return;
+       }
+       if (image->dynamic) {
+               /* FIXME: */
+               image->checked_module_cctor = TRUE;
+               return;
        }
-       g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
+       if (t->rows >= 1) {
+               guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
+               const char *name = mono_metadata_string_heap (image, nameidx);
+               if (strcmp (name, "<Module>") == 0) {
+                       guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
+                       guint32 last_method;
+                       if (t->rows > 1)
+                               last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
+                       else 
+                               last_method = mt->rows;
+                       for (; first_method < last_method; first_method++) {
+                               nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
+                               name = mono_metadata_string_heap (image, nameidx);
+                               if (strcmp (name, ".cctor") == 0) {
+                                       image->has_module_cctor = TRUE;
+                                       image->checked_module_cctor = TRUE;
+                                       return;
+                               }
+                       }
+               }
+       }
+       image->has_module_cctor = FALSE;
+       image->checked_module_cctor = TRUE;
 }
 
 static void
-load_modules (MonoImage *image, MonoImageOpenStatus *status)
+load_modules (MonoImage *image)
 {
        MonoTableInfo *t;
-       int i;
-       char *base_dir;
 
        if (image->modules)
                return;
 
        t = &image->tables [MONO_TABLE_MODULEREF];
        image->modules = g_new0 (MonoImage *, t->rows);
+       image->modules_loaded = g_new0 (gboolean, t->rows);
        image->module_count = t->rows;
+}
+
+/**
+ * mono_image_load_module:
+ *
+ *   Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
+ * it cannot be loaded.
+ */
+MonoImage*
+mono_image_load_module (MonoImage *image, int idx)
+{
+       MonoTableInfo *t;
+       MonoTableInfo *file_table;
+       int i;
+       char *base_dir;
+       gboolean refonly = image->ref_only;
+       GList *list_iter, *valid_modules = NULL;
+       MonoImageOpenStatus status;
+
+       g_assert (idx <= image->module_count);
+       if (image->modules_loaded [idx - 1])
+               return image->modules [idx - 1];
+
+       file_table = &image->tables [MONO_TABLE_FILE];
+       for (i = 0; i < file_table->rows; i++) {
+               guint32 cols [MONO_FILE_SIZE];
+               mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
+               if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
+                       continue;
+               valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
+       }
+
+       t = &image->tables [MONO_TABLE_MODULEREF];
        base_dir = g_path_get_dirname (image->name);
-       for (i = 0; i < t->rows; i++){
+
+       {
                char *module_ref;
                const char *name;
                guint32 cols [MONO_MODULEREF_SIZE];
+               /* if there is no file table, we try to load the module... */
+               int valid = file_table->rows == 0;
 
-               mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
+               mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
                name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
-               module_ref = g_build_filename (base_dir, name, NULL);
-               image->modules [i] = mono_image_open (module_ref, status);
-               if (image->modules [i]) {
-                       /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
+               for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
+                       /* be safe with string dups, but we could just compare string indexes  */
+                       if (strcmp (list_iter->data, name) == 0) {
+                               valid = TRUE;
+                               break;
+                       }
                }
-               /* 
-                * FIXME: what do we do here? it could be a native dll...
-                * We should probably do lazy-loading of modules.
-                */
-               if (status)
-                       *status = MONO_IMAGE_OK;
-               g_free (module_ref);
-       }
-
-       g_free (base_dir);
-}
-
-static void
-load_class_names (MonoImage *image)
-{
-       MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
-       guint32 cols [MONO_TYPEDEF_SIZE];
-       const char *name;
-       const char *nspace;
-       guint32 i, visib, nspace_index;
-       GHashTable *name_cache2, *nspace_table;
-
-       /* Temporary hash table to avoid lookups in the nspace_table */
-       name_cache2 = g_hash_table_new (NULL, NULL);
-
-       for (i = 1; i <= t->rows; ++i) {
-               mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
-               /* nested types are accessed from the nesting name */
-               visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
-               if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
-                       continue;
-               name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
-               nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
-
-               nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
-               nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
-               if (!nspace_table) {
-                       nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
-                       g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
-                       g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
-                                                                nspace_table);
+               if (valid) {
+                       module_ref = g_build_filename (base_dir, name, NULL);
+                       image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
+                       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);
                }
-               g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
        }
 
-       /* Load type names from EXPORTEDTYPES table */
-       {
-               MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
-               guint32 cols [MONO_EXP_TYPE_SIZE];
-               int i;
+       image->modules_loaded [idx - 1] = TRUE;
 
-               for (i = 0; i < t->rows; ++i) {
-                       mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
-                       name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
-                       nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
-
-                       nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
-                       nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
-                       if (!nspace_table) {
-                               nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
-                               g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
-                               g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
-                                                                        nspace_table);
-                       }
-                       g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
-               }
-       }
+       g_free (base_dir);
+       g_list_free (valid_modules);
 
-       g_hash_table_destroy (name_cache2);
+       return image->modules [idx - 1];
 }
 
-static void
-register_guid (gpointer key, gpointer value, gpointer user_data)
+static gpointer
+class_key_extract (gpointer value)
 {
-       MonoImage *image = (MonoImage*)value;
+       MonoClass *class = value;
 
-       if (!g_hash_table_lookup (loaded_images_guid_hash, image))
-               g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
+       return GUINT_TO_POINTER (class->type_token);
 }
 
-static void
-build_guid_table (void)
+static gpointer*
+class_next_value (gpointer value)
 {
-       g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
+       MonoClass *class = value;
+
+       return (gpointer*)&class->next_class_cache;
 }
 
 void
 mono_image_init (MonoImage *image)
 {
-       image->mempool = mono_mempool_new ();
-       image->method_cache = g_hash_table_new (NULL, NULL);
-       image->class_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->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
-       image->array_cache = g_hash_table_new (mono_aligned_addr_hash, 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->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->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);
-}
-
-static MonoImage *
-do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
-                   gboolean care_about_cli)
-{
-       MonoCLIImageInfo *iinfo;
-       MonoDotNetHeader *header;
-       MonoMSDOSHeader msdos;
-       guint32 offset = 0;
+       image->method_signatures = g_hash_table_new (NULL, NULL);
 
-       mono_image_init (image);
+       image->property_hash = mono_property_hash_new ();
+       InitializeCriticalSection (&image->lock);
+       InitializeCriticalSection (&image->szarray_cache_lock);
+}
 
-       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);
@@ -636,15 +661,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 */
@@ -659,10 +740,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);
 
@@ -684,19 +761,49 @@ 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;
+}
+
+gboolean
+mono_image_load_pe_data (MonoImage *image)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoDotNetHeader *header;
+       MonoMSDOSHeader msdos;
+       gint32 offset = 0;
+
+       iinfo = image->image_info;
+       header = &iinfo->cli_header;
+
+#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
        /*
@@ -720,152 +827,375 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
        
        if (!load_section_tables (image, iinfo, offset))
                goto invalid_image;
+
+       return TRUE;
+
+invalid_image:
+       return FALSE;
+}
+
+gboolean
+mono_image_load_cli_data (MonoImage *image)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoDotNetHeader *header;
+
+       iinfo = image->image_info;
+       header = &iinfo->cli_header;
+
+       /* Load the CLI header */
+       if (!load_cli_header (image, iinfo))
+               return FALSE;
+
+       if (!load_metadata (image, iinfo))
+               return FALSE;
+
+       return TRUE;
+}
+
+static MonoImage *
+do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
+                   gboolean care_about_cli, gboolean care_about_pecoff)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoDotNetHeader *header;
+
+       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;
+
+       if (care_about_pecoff == FALSE)
+               goto done;
+
+       if (!mono_verifier_verify_pe_data (image, NULL))
+               goto invalid_image;
+
+       if (!mono_image_load_pe_data (image))
+               goto invalid_image;
        
        if (care_about_cli == FALSE) {
                goto done;
        }
-       
-       /* Load the CLI header */
-       if (!load_cli_header (image, iinfo))
-               goto invalid_image;
 
-       if (!load_metadata (image, iinfo))
+       if (!mono_verifier_verify_cli_data (image, NULL))
                goto invalid_image;
 
-       load_class_names (image);
+       if (!mono_image_load_cli_data (image))
+               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],
                                        0, MONO_MODULE_NAME));
 
-       load_modules (image, status);
+       load_modules (image);
 
 done:
+       mono_profiler_module_loaded (image, MONO_PROFILE_OK);
        if (status)
                *status = MONO_IMAGE_OK;
 
-       image->ref_count=1;
-
        return image;
 
 invalid_image:
+       mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
        mono_image_close (image);
                return NULL;
 }
 
 static MonoImage *
 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
-                   gboolean care_about_cli)
+                   gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
 {
        MonoCLIImageInfo *iinfo;
        MonoImage *image;
-       FILE *filed;
-       struct stat stat_buf;
+       MonoFileMap *filed;
+
+       if ((filed = mono_file_map_open (fname)) == NULL){
+               if (IS_PORTABILITY_SET) {
+                       gchar *ffname = mono_portability_find_file (fname, TRUE);
+                       if (ffname) {
+                               filed = mono_file_map_open (ffname);
+                               g_free (ffname);
+                       }
+               }
 
-       if ((filed = fopen (fname, "rb")) == NULL){
-               if (status)
-                       *status = MONO_IMAGE_ERROR_ERRNO;
-               return NULL;
+               if (filed == NULL) {
+                       if (status)
+                               *status = MONO_IMAGE_ERROR_ERRNO;
+                       return NULL;
+               }
        }
 
-       if (fstat (fileno (filed), &stat_buf)) {
-               fclose (filed);
+       image = g_new0 (MonoImage, 1);
+       image->raw_buffer_used = TRUE;
+       image->raw_data_len = mono_file_map_size (filed);
+       image->raw_data = mono_file_map (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
+       if (!image->raw_data) {
+               mono_file_map_close (filed);
+               g_free (image);
                if (status)
-                       *status = MONO_IMAGE_ERROR_ERRNO;
+                       *status = MONO_IMAGE_IMAGE_INVALID;
                return NULL;
        }
-       image = g_new0 (MonoImage, 1);
-       image->ref_count = 1;
-       image->file_descr = filed;
-       image->raw_data_len = stat_buf.st_size;
-       image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
        iinfo = g_new0 (MonoCLIImageInfo, 1);
        image->image_info = iinfo;
-       image->name = canonicalize_path (fname);
+       image->name = mono_path_resolve_symlinks (fname);
+       image->ref_only = refonly;
+       image->ref_count = 1;
+       /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
+       image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
 
-       return do_mono_image_load (image, status, care_about_cli);
+       mono_file_map_close (filed);
+       return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
 }
 
 MonoImage *
-mono_image_loaded (const char *name)
+mono_image_loaded_full (const char *name, gboolean refonly)
 {
        MonoImage *res;
+       GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
         
-       EnterCriticalSection (&images_mutex);
-       res = g_hash_table_lookup (loaded_images_hash, name);
-       LeaveCriticalSection (&images_mutex);
+       mono_images_lock ();
+       res = g_hash_table_lookup (loaded_images, name);
+       mono_images_unlock ();
        return res;
 }
 
+/**
+ * mono_image_loaded:
+ * @name: name of the image to load
+ *
+ * This routine ensures that the given image is loaded.
+ *
+ * Returns: the loaded MonoImage, or NULL on failure.
+ */
 MonoImage *
-mono_image_loaded_by_guid (const char *guid)
+mono_image_loaded (const char *name)
 {
+       return mono_image_loaded_full (name, FALSE);
+}
+
+typedef struct {
        MonoImage *res;
+       const char* guid;
+} GuidData;
 
-       EnterCriticalSection (&images_mutex);
-       res = g_hash_table_lookup (loaded_images_guid_hash, guid);
-       LeaveCriticalSection (&images_mutex);
-       return res;
+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_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
+mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
 {
-       MonoCLIImageInfo *iinfo;
-       MonoImage *image;
-       char *datac;
+       GuidData data;
+       GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
+       data.res = NULL;
+       data.guid = guid;
+
+       mono_images_lock ();
+       g_hash_table_foreach (loaded_images, find_by_guid, &data);
+       mono_images_unlock ();
+       return data.res;
+}
 
-       if (!data || !data_len) {
-               if (status)
-                       *status = MONO_IMAGE_IMAGE_INVALID;
-               return NULL;
-       }
-       datac = data;
-       if (need_copy) {
-               datac = g_try_malloc (data_len);
-               if (!datac) {
-                       if (status)
-                               *status = MONO_IMAGE_ERROR_ERRNO;
-                       return NULL;
-               }
-               memcpy (datac, data, data_len);
+MonoImage *
+mono_image_loaded_by_guid (const char *guid)
+{
+       return mono_image_loaded_by_guid_full (guid, FALSE);
+}
+
+static MonoImage *
+register_image (MonoImage *image)
+{
+       MonoImage *image2;
+       GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
+
+       mono_images_lock ();
+       image2 = g_hash_table_lookup (loaded_images, image->name);
+
+       if (image2) {
+               /* Somebody else beat us to it */
+               mono_image_addref (image2);
+               mono_images_unlock ();
+               mono_image_close (image);
+               return image2;
+       }
+       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);      
+       mono_images_unlock ();
+
+       return image;
+}
+
+MonoImage *
+mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoImage *image;
+       char *datac;
+
+       if (!data || !data_len) {
+               if (status)
+                       *status = MONO_IMAGE_IMAGE_INVALID;
+               return NULL;
+       }
+       datac = data;
+       if (need_copy) {
+               datac = g_try_malloc (data_len);
+               if (!datac) {
+                       if (status)
+                               *status = MONO_IMAGE_ERROR_ERRNO;
+                       return NULL;
+               }
+               memcpy (datac, data, data_len);
        }
 
        image = g_new0 (MonoImage, 1);
-       image->ref_count = 1;
        image->raw_data = datac;
        image->raw_data_len = data_len;
        image->raw_data_allocated = need_copy;
        image->name = g_strdup_printf ("data-%p", datac);
        iinfo = g_new0 (MonoCLIImageInfo, 1);
        image->image_info = iinfo;
+       image->ref_only = refonly;
 
-       return do_mono_image_load (image, status, TRUE);
+       image = do_mono_image_load (image, status, TRUE, TRUE);
+       if (image == NULL)
+               return NULL;
+
+       return register_image (image);
 }
 
-/**
- * mono_image_open:
- * @fname: filename that points to the module we want to open
- * @status: An error condition is returned in this field
- *
- * Returns: An open image of type %MonoImage or NULL on error.
- * if NULL, then check the value of @status for details on the error
- */
 MonoImage *
-mono_image_open (const char *fname, MonoImageOpenStatus *status)
+mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
+{
+       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, *image2;
+       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, TRUE);
+       if (image == NULL)
+               return NULL;
+
+       return register_image (image);
+}
+#endif
+
+MonoImage *
+mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
+{
+       MonoImage *image;
+       GHashTable *loaded_images;
        char *absfname;
        
        g_return_val_if_fail (fname != NULL, NULL);
        
-       absfname = canonicalize_path (fname);
+#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);
 
        /*
         * The easiest solution would be to do all the loading inside the mutex,
@@ -873,38 +1203,39 @@ mono_image_open (const char *fname, MonoImageOpenStatus *status)
         * happen outside the mutex, and if multiple threads happen to load
         * the same image, we discard all but the first copy.
         */
-       EnterCriticalSection (&images_mutex);
-       image = g_hash_table_lookup (loaded_images_hash, absfname);
+       mono_images_lock ();
+       loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
+       image = g_hash_table_lookup (loaded_images, absfname);
        g_free (absfname);
        
        if (image){
                mono_image_addref (image);
-               LeaveCriticalSection (&images_mutex);
+               mono_images_unlock ();
                return image;
        }
-       LeaveCriticalSection (&images_mutex);
+       mono_images_unlock ();
 
-       image = do_mono_image_open (fname, status, TRUE);
+       image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
        if (image == NULL)
                return NULL;
 
-       EnterCriticalSection (&images_mutex);
-       image2 = g_hash_table_lookup (loaded_images_hash, image->name);
-
-       if (image2) {
-               /* Somebody else beat us to it */
-               mono_image_addref (image2);
-               LeaveCriticalSection (&images_mutex);
-               mono_image_close (image);
-               return image2;
-       }
-       g_hash_table_insert (loaded_images_hash, image->name, image);
-       if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == NULL))
-               g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image); 
-       g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
-       LeaveCriticalSection (&images_mutex);
+       return register_image (image);
+}
 
-       return image;
+/**
+ * mono_image_open:
+ * @fname: filename that points to the module we want to open
+ * @status: An error condition is returned in this field
+ *
+ * Returns: An open image of type %MonoImage or NULL on error. 
+ * The caller holds a temporary reference to the returned image which should be cleared 
+ * when no longer needed by calling mono_image_close ().
+ * if NULL, then check the value of @status for details on the error
+ */
+MonoImage *
+mono_image_open (const char *fname, MonoImageOpenStatus *status)
+{
+       return mono_image_open_full (fname, status, FALSE);
 }
 
 /**
@@ -923,7 +1254,75 @@ mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
 {
        g_return_val_if_fail (fname != NULL, NULL);
        
-       return(do_mono_image_open (fname, status, FALSE));
+       return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
+}
+
+/**
+ * mono_image_open_raw
+ * @fname: filename that points to the module we want to open
+ * @status: An error condition is returned in this field
+ * 
+ * Returns an image without loading neither pe or cli data.
+ * 
+ * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.  
+ */
+MonoImage *
+mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
+{
+       g_return_val_if_fail (fname != NULL, NULL);
+       
+       return(do_mono_image_open (fname, status, FALSE, 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
@@ -932,11 +1331,13 @@ free_hash_table (gpointer key, gpointer val, gpointer user_data)
        g_hash_table_destroy ((GHashTable*)val);
 }
 
+/*
 static void
 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
 {
        mono_metadata_free_method_signature ((MonoMethodSignature*)val);
 }
+*/
 
 static void
 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
@@ -944,6 +1345,12 @@ free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
        g_free (val);
 }
 
+static void
+free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
+{
+       g_slist_free ((GSList*)val);
+}
+
 /**
  * mono_image_addref:
  * @image: The image file we wish to add a reference to
@@ -968,6 +1375,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
@@ -979,37 +1393,75 @@ void
 mono_image_close (MonoImage *image)
 {
        MonoImage *image2;
+       GHashTable *loaded_images;
        int i;
 
        g_return_if_fail (image != NULL);
 
-       EnterCriticalSection (&images_mutex);
-       /*g_print ("destroy image '%s' %p (dynamic: %d) refcount: %d\n", image->name, image, image->dynamic, image->ref_count);*/
-       g_assert (image->ref_count > 0);
-       if (--image->ref_count) {
-               LeaveCriticalSection (&images_mutex);
+       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 && !image->dynamic) {
+               MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
+               int i;
+
+               for (i = 0; i < t->rows; i++) {
+                       if (image->references [i])
+                               mono_assembly_close (image->references [i]);
+               }
+
+               g_free (image->references);
+               image->references = NULL;
        }
-       image2 = g_hash_table_lookup (loaded_images_hash, image->name);
+
+       mono_images_lock ();
+       loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_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_hash, image->name);
-               g_hash_table_remove (loaded_images_guid_hash, image->guid);
-               /* Multiple images might have the same guid */
-               build_guid_table ();
+               g_hash_table_remove (loaded_images, image->name);
        }
-       if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == image))
-               g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);        
-       LeaveCriticalSection (&images_mutex);
+       if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
+               g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
+
+#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;
 
@@ -1024,32 +1476,81 @@ mono_image_close (MonoImage *image)
 
                g_free (image->raw_data);
        }
-       g_free (image->name);
-       g_free (image->guid);
-       g_free (image->files);
 
-       g_hash_table_destroy (image->method_cache);
-       g_hash_table_destroy (image->class_cache);
+       if (debug_assembly_unload) {
+               image->name = g_strdup_printf ("%s - UNLOADED", image->name);
+       } else {
+               g_free (image->name);
+               g_free (image->guid);
+               g_free (image->version);
+               g_free (image->files);
+       }
+
+       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);
-       g_hash_table_destroy (image->array_cache);
-       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->typespec_cache);
-       g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
+       if (image->array_cache) {
+               g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
+               g_hash_table_destroy (image->array_cache);
+       }
+       if (image->szarray_cache)
+               g_hash_table_destroy (image->szarray_cache);
+       if (image->ptr_cache)
+               g_hash_table_destroy (image->ptr_cache);
+       if (image->name_cache) {
+               g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
+               g_hash_table_destroy (image->name_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->runtime_invoke_vcall_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);
        g_hash_table_destroy (image->memberref_signatures);
-       g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
+       //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
        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);
+       }
        if (image->image_info){
                MonoCLIImageInfo *ii = image->image_info;
 
@@ -1064,51 +1565,33 @@ mono_image_close (MonoImage *image)
                if (image->modules [i])
                        mono_image_close (image->modules [i]);
        }
+       if (image->modules)
+               g_free (image->modules);
+       if (image->modules_loaded)
+               g_free (image->modules_loaded);
+       if (image->references)
+               g_free (image->references);
+       mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
+
+       DeleteCriticalSection (&image->szarray_cache_lock);
+       DeleteCriticalSection (&image->lock);
+
        /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
        if (!image->dynamic) {
-               mono_mempool_destroy (image->mempool);
-               g_free (image);
+               if (debug_assembly_unload)
+                       mono_mempool_invalidate (image->mempool);
+               else {
+                       mono_mempool_destroy (image->mempool);
+                       g_free (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_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);
 }
 
 /** 
@@ -1139,7 +1622,8 @@ mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
                               MonoPEResourceDirEntry *entry,
                               MonoPEResourceDir *root, guint32 level)
 {
-       gboolean is_string=entry->name_is_string;
+       gboolean is_string, is_dir;
+       guint32 name_offset, dir_offset;
 
        /* Level 0 holds a directory entry for each type of resource
         * (identified by ID or name).
@@ -1151,36 +1635,37 @@ mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
         * Level 2 holds a directory entry for each language pointing to
         * the actual data.
         */
+       is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
+       name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
+
+       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 && entry->name_offset!=res_id) ||
-                  (is_string==TRUE)) {
-                       return(NULL);
-               }
+               if (is_string)
+                       return NULL;
        } else if (level==1) {
+               if (res_id != name_offset)
+                       return NULL;
 #if 0
                if(name!=NULL &&
-                  is_string==TRUE && name!=lookup (entry->name_offset)) {
+                  is_string==TRUE && name!=lookup (name_offset)) {
                        return(NULL);
                }
 #endif
        } else if (level==2) {
-               if ((is_string == FALSE &&
-                   entry->name_offset != lang_id &&
-                   lang_id != 0) ||
-                  (is_string == TRUE)) {
-                       return(NULL);
-               }
+               if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
+                       return NULL;
        } else {
                g_assert_not_reached ();
        }
 
-       if(entry->is_dir==TRUE) {
-               MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
+       if(is_dir==TRUE) {
+               MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
                MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
                guint32 entries, i;
-               
-               entries=res_dir->res_named_entries + res_dir->res_id_entries;
+
+               entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
 
                for(i=0; i<entries; i++) {
                        MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
@@ -1197,12 +1682,31 @@ mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
 
                return(NULL);
        } else {
-               MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
-               
-               return(data_entry);
+               MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
+               MonoPEResourceDataEntry *res;
+
+               res = g_new0 (MonoPEResourceDataEntry, 1);
+
+               res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
+               res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
+               res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
+               res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
+
+               return (res);
        }
 }
 
+/**
+ * mono_image_lookup_resource:
+ * @image: the image to look up the resource in
+ * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
+ * @lang_id: The language id.
+ * @name: the resource name to lookup.
+ *
+ * Returns: NULL if not found, otherwise a pointer to the in-memory representation
+ * of the given resource. The caller should free it using g_free () when no longer
+ * needed.
+ */
 gpointer
 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
 {
@@ -1218,6 +1722,8 @@ mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, g
                return(NULL);
        }
 
+       mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
+
        info=image->image_info;
        if(info==NULL) {
                return(NULL);
@@ -1242,8 +1748,8 @@ mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, g
        if(resource_dir==NULL) {
                return(NULL);
        }
-       
-       entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
+
+       entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
        res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
        
        for(i=0; i<entries; i++) {
@@ -1261,12 +1767,33 @@ mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, g
        return(NULL);
 }
 
+/** 
+ * mono_image_get_entry_point:
+ * @image: the image where the entry point will be looked up.
+ *
+ * Use this routine to determine the metadata token for method that
+ * has been flagged as the entry point.
+ *
+ * Returns: the token for the entry point method in the image
+ */
 guint32
 mono_image_get_entry_point (MonoImage *image)
 {
        return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
 }
 
+/**
+ * mono_image_get_resource:
+ * @image: the image where the resource will be looked up.
+ * @offset: The offset to add to the resource
+ * @size: a pointer to an int where the size of the resource will be stored
+ *
+ * This is a low-level routine that fetches a resource from the
+ * metadata that starts at a given @offset.  The @size parameter is
+ * filled with the data field as encoded in the metadata.
+ *
+ * Returns: the pointer to the resource whose offset is @offset.
+ */
 const char*
 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
 {
@@ -1299,8 +1826,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);
@@ -1320,12 +1850,28 @@ 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;
 }
 
+/**
+ * mono_image_get_strong_name:
+ * @image: a MonoImage
+ * @size: a guint32 pointer, or NULL.
+ *
+ * If the image has a strong name, and @size is not NULL, the value
+ * pointed to by size will have the size of the strong name.
+ *
+ * Returns: NULL if the image does not have a strong name, or a
+ * pointer to the public key.
+ */
 const char*
 mono_image_get_strong_name (MonoImage *image, guint32 *size)
 {
@@ -1343,37 +1889,56 @@ mono_image_get_strong_name (MonoImage *image, guint32 *size)
        return data;
 }
 
+/**
+ * mono_image_strong_name_position:
+ * @image: a MonoImage
+ * @size: a guint32 pointer, or NULL.
+ *
+ * If the image has a strong name, and @size is not NULL, the value
+ * pointed to by size will have the size of the strong name.
+ *
+ * Returns: the position within the image file where the strong name
+ * is stored.
+ */
 guint32
 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;
 }
 
+/**
+ * mono_image_get_public_key:
+ * @image: a MonoImage
+ * @size: a guint32 pointer, or NULL.
+ *
+ * This is used to obtain the public key in the @image.
+ * 
+ * If the image has a public key, and @size is not NULL, the value
+ * pointed to by size will have the size of the public key.
+ * 
+ * Returns: NULL if the image does not have a public key, or a pointer
+ * to the public key.
+ */
 const char*
 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);
@@ -1386,18 +1951,38 @@ mono_image_get_public_key (MonoImage *image, guint32 *size)
        return pubkey;
 }
 
+/**
+ * mono_image_get_name:
+ * @name: a MonoImage
+ *
+ * Returns: the name of the assembly.
+ */
 const char*
 mono_image_get_name (MonoImage *image)
 {
        return image->assembly_name;
 }
 
+/**
+ * mono_image_get_filename:
+ * @image: a MonoImage
+ *
+ * Used to get the filename that hold the actual MonoImage
+ *
+ * Returns: the filename.
+ */
 const char*
 mono_image_get_filename (MonoImage *image)
 {
        return image->name;
 }
 
+const char*
+mono_image_get_guid (MonoImage *image)
+{
+       return image->guid;
+}
+
 const MonoTableInfo*
 mono_image_get_table_info (MonoImage *image, int table_id)
 {
@@ -1420,18 +2005,45 @@ mono_table_info_get_rows (const MonoTableInfo *table)
        return table->rows;
 }
 
+/**
+ * mono_image_get_assembly:
+ * @image: the MonoImage.
+ *
+ * Use this routine to get the assembly that owns this image.
+ *
+ * Returns: the assembly that holds this image.
+ */
 MonoAssembly* 
 mono_image_get_assembly (MonoImage *image)
 {
        return image->assembly;
 }
 
+/**
+ * mono_image_is_dynamic:
+ * @image: the MonoImage
+ *
+ * Determines if the given image was created dynamically through the
+ * System.Reflection.Emit API
+ *
+ * Returns: TRUE if the image was created dynamically, FALSE if not.
+ */
 gboolean
 mono_image_is_dynamic (MonoImage *image)
 {
        return image->dynamic;
 }
 
+/**
+ * mono_image_has_authenticode_entry:
+ * @image: the MonoImage
+ *
+ * Use this routine to determine if the image has a Authenticode
+ * Certificate Table.
+ *
+ * Returns: TRUE if the image contains an authenticode entry in the PE
+ * directory.
+ */
 gboolean
 mono_image_has_authenticode_entry (MonoImage *image)
 {
@@ -1441,3 +2053,134 @@ 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)
+{
+       gpointer res;
+
+       mono_perfcounters->loader_bytes += size;
+       mono_image_lock (image);
+       res = mono_mempool_alloc (image->mempool, size);
+       mono_image_unlock (image);
+
+       return res;
+}
+
+gpointer
+mono_image_alloc0 (MonoImage *image, guint size)
+{
+       gpointer res;
+
+       mono_perfcounters->loader_bytes += size;
+       mono_image_lock (image);
+       res = mono_mempool_alloc0 (image->mempool, size);
+       mono_image_unlock (image);
+
+       return res;
+}
+
+char*
+mono_image_strdup (MonoImage *image, const char *s)
+{
+       char *res;
+
+       mono_perfcounters->loader_bytes += strlen (s);
+       mono_image_lock (image);
+       res = mono_mempool_strdup (image->mempool, s);
+       mono_image_unlock (image);
+
+       return res;
+}
+
+GList*
+g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
+{
+       GList *new_list;
+       
+       new_list = mono_image_alloc (image, sizeof (GList));
+       new_list->data = data;
+       new_list->prev = list ? list->prev : NULL;
+    new_list->next = list;
+
+    if (new_list->prev)
+            new_list->prev->next = new_list;
+    if (list)
+            list->prev = new_list;
+
+       return new_list;
+}
+
+GSList*
+g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
+{
+       GSList *new_list;
+
+       new_list = mono_image_alloc (image, sizeof (GSList));
+       new_list->data = data;
+       new_list->next = NULL;
+
+       return g_slist_concat (list, new_list);
+}
+
+void
+mono_image_lock (MonoImage *image)
+{
+       mono_locks_acquire (&image->lock, ImageDataLock);
+}
+
+void
+mono_image_unlock (MonoImage *image)
+{
+       mono_locks_release (&image->lock, ImageDataLock);
+}
+
+
+/**
+ * mono_image_property_lookup:
+ *
+ * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
+ *
+ * LOCKING: Takes the image lock
+ */
+gpointer 
+mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
+{
+       gpointer res;
+
+       mono_image_lock (image);
+       res = mono_property_hash_lookup (image->property_hash, subject, property);
+       mono_image_unlock (image);
+
+       return res;
+}
+
+/**
+ * mono_image_property_insert:
+ *
+ * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
+ *
+ * LOCKING: Takes the image lock
+ */
+void
+mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
+{
+       mono_image_lock (image);
+       mono_property_hash_insert (image->property_hash, subject, property, value);
+       mono_image_unlock (image);
+}
+
+/**
+ * mono_image_property_remove:
+ *
+ * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
+ *
+ * LOCKING: Takes the image lock
+ */
+void
+mono_image_property_remove (MonoImage *image, gpointer subject)
+{
+       mono_image_lock (image);
+       mono_property_hash_remove_object (image->property_hash, subject);
+       mono_image_unlock (image);
+}