Fix for building mono in VS, and implement reading/writing USER/MACHINE level environ...
[mono.git] / mono / metadata / image.c
index 590f34a545043b6ee444212d8b479a7eb487bd5b..e7925f62fb48618739b925d37ba563dd30ec787c 100644 (file)
 #include "cil-coff.h"
 #include "rawbuffer.h"
 #include "mono-endian.h"
-#include "private.h"
 #include "tabledefs.h"
 #include "tokentype.h"
 #include "metadata-internals.h"
+#include "loader.h"
 #include <mono/io-layer/io-layer.h>
+#include <mono/utils/mono-logger.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
 
 #define INVALID_ADDRESS 0xffffffff
 
  */
 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;
+
+#define mono_images_lock() EnterCriticalSection (&images_mutex)
+#define mono_images_unlock() LeaveCriticalSection (&images_mutex)
 static CRITICAL_SECTION images_mutex;
 
 guint32
@@ -105,7 +115,9 @@ canonicalize_path (const char *path)
                        if (backc > 0) {
                                backc--;
                        } else {
-                               if (dest != lastpos) strncpy (dest, lastpos, len + 1);
+                               if (dest != lastpos) 
+                                       /* The two strings can overlap */
+                                       memmove (dest, lastpos, len + 1);
                                dest += len + 1;
                        }
                }
@@ -129,6 +141,26 @@ mono_images_init (void)
 
        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;
+}
+
+/**
+ * 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_guid_hash);
+       g_hash_table_destroy (loaded_images_refonly_hash);
+       g_hash_table_destroy (loaded_images_refonly_guid_hash);
 }
 
 /**
@@ -157,20 +189,10 @@ mono_image_ensure_section_idx (MonoImage *image, int section)
        
        writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
 
-       if (!image->f) {
-               if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
-                       return FALSE;
-               /* 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;
-       }
-       iinfo->cli_sections [section] = mono_raw_buffer_load (
-               fileno (image->f), writable,
-               sect->st_raw_data_ptr, sect->st_raw_data_size);
-
-       if (iinfo->cli_sections [section] == NULL)
+       if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
                return FALSE;
-
+       /* 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;
 }
 
@@ -212,15 +234,10 @@ load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
        for (i = 0; i < top; i++){
                MonoSectionTable *t = &iinfo->cli_section_tables [i];
 
-               if (!image->f) {
-                       if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
-                               return FALSE;
-                       memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
-                       offset += sizeof (MonoSectionTable);
-               } else {
-                       if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
-                               return FALSE;
-               }
+               if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
+                       return FALSE;
+               memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
+               offset += sizeof (MonoSectionTable);
 
 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
                t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
@@ -243,23 +260,14 @@ static gboolean
 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
 {
        guint32 offset;
-       int n;
        
        offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
        if (offset == INVALID_ADDRESS)
                return FALSE;
 
-       if (!image->f) {
-               if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
-                       return FALSE;
-               memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
-       } else {
-               if (fseek (image->f, offset, SEEK_SET) != 0)
-                       return FALSE;
-       
-               if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
-                       return FALSE;
-       }
+       if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
+               return FALSE;
+       memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
 
 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
@@ -327,22 +335,21 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
 
        size = iinfo->cli_cli_header.ch_metadata.size;
 
-       if (!image->f) {
-               if (offset + size > image->raw_data_len)
-                       return FALSE;
-               image->raw_metadata = image->raw_data + offset;
-       } else {
-               image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
-               if (image->raw_metadata == NULL)
-                       return FALSE;
-       }
+       if (offset + size > image->raw_data_len)
+               return FALSE;
+       image->raw_metadata = image->raw_data + offset;
 
        ptr = image->raw_metadata;
 
        if (strncmp (ptr, "BSJB", 4) == 0){
                guint32 version_string_len;
 
-               ptr += 12;
+               ptr += 4;
+               image->md_version_major = read16 (ptr);
+               ptr += 4;
+               image->md_version_minor = read16 (ptr);
+               ptr += 4;
+
                version_string_len = read32 (ptr);
                ptr += 4;
                image->version = g_strndup (ptr, version_string_len);
@@ -395,7 +402,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;
 }
@@ -423,16 +430,19 @@ load_tables (MonoImage *image)
        
        for (table = 0; table < 64; table++){
                if ((valid_mask & ((guint64) 1 << table)) == 0){
+                       if (table > MONO_TABLE_LAST)
+                               continue;
                        image->tables [table].rows = 0;
                        continue;
                }
                if (table > MONO_TABLE_LAST) {
                        g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
+               } else {
+                       image->tables [table].rows = read32 (rows);
                }
                /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
                        g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
                }*/
-               image->tables [table].rows = read32 (rows);
                rows++;
                valid++;
        }
@@ -475,6 +485,7 @@ load_modules (MonoImage *image, MonoImageOpenStatus *status)
        MonoTableInfo *t;
        int i;
        char *base_dir;
+       gboolean refonly = image->ref_only;
 
        if (image->modules)
                return;
@@ -491,8 +502,9 @@ load_modules (MonoImage *image, MonoImageOpenStatus *status)
                mono_metadata_decode_row (t, i, 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);
+               image->modules [i] = mono_image_open_full (module_ref, status, refonly);
                if (image->modules [i]) {
+                       mono_image_addref (image->modules [i]);
                        /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
                }
                /* 
@@ -576,19 +588,20 @@ register_guid (gpointer key, gpointer value, gpointer user_data)
 }
 
 static void
-build_guid_table (void)
+build_guid_table (gboolean refonly)
 {
-       g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
+       GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
+       g_hash_table_foreach (loaded_images, register_guid, NULL);
 }
 
 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->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 (NULL, NULL);
 
        image->delegate_begin_invoke_cache = 
                g_hash_table_new ((GHashFunc)mono_signature_hash, 
@@ -603,27 +616,34 @@ mono_image_init (MonoImage *image)
                g_hash_table_new ((GHashFunc)mono_signature_hash, 
                                  (GCompareFunc)mono_metadata_signature_equal);
        
-       image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
-       image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
-       image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
-       image->synchronized_cache = g_hash_table_new (NULL, NULL);
+       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->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->generic_inst_cache =
-               g_hash_table_new ((GHashFunc)mono_metadata_generic_inst_hash,
-                                 (GCompareFunc)mono_metadata_generic_inst_equal);
+       image->method_signatures = g_hash_table_new (NULL, NULL);
 }
 
 static MonoImage *
-do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
+do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
+                   gboolean care_about_cli)
 {
        MonoCLIImageInfo *iinfo;
        MonoDotNetHeader *header;
        MonoMSDOSHeader msdos;
-       int n;
        guint32 offset = 0;
 
        mono_image_init (image);
@@ -634,35 +654,21 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
        if (status)
                *status = MONO_IMAGE_IMAGE_INVALID;
 
-       if (!image->f) {
-               if (offset + sizeof (msdos) > image->raw_data_len)
-                       goto invalid_image;
-               memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
-       } else {
-               if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
-                       goto invalid_image;
-       }
+       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);
 
-       if (msdos.pe_offset != sizeof (msdos)) {
-               if (image->f)
-                       fseek (image->f, msdos.pe_offset, SEEK_SET);
-       }
        offset = msdos.pe_offset;
 
-       if (!image->f) {
-               if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
-                       goto invalid_image;
-               memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
-               offset += sizeof (MonoDotNetHeader);
-       } else {
-               if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
-                       goto invalid_image;
-       }
+       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))
@@ -762,6 +768,10 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
        if (!load_section_tables (image, iinfo, offset))
                goto invalid_image;
        
+       if (care_about_cli == FALSE) {
+               goto done;
+       }
+       
        /* Load the CLI header */
        if (!load_cli_header (image, iinfo))
                goto invalid_image;
@@ -783,11 +793,10 @@ do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
 
        load_modules (image, status);
 
+done:
        if (status)
                *status = MONO_IMAGE_OK;
 
-       image->ref_count=1;
-
        return image;
 
 invalid_image:
@@ -796,11 +805,13 @@ invalid_image:
 }
 
 static MonoImage *
-do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
+do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
+                   gboolean care_about_cli, gboolean refonly)
 {
        MonoCLIImageInfo *iinfo;
        MonoImage *image;
        FILE *filed;
+       struct stat stat_buf;
 
        if ((filed = fopen (fname, "rb")) == NULL){
                if (status)
@@ -808,40 +819,88 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
                return NULL;
        }
 
+       if (fstat (fileno (filed), &stat_buf)) {
+               fclose (filed);
+               if (status)
+                       *status = MONO_IMAGE_ERROR_ERRNO;
+               return NULL;
+       }
        image = g_new0 (MonoImage, 1);
-       image->ref_count = 1;
-       image->f = filed;
+       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->ref_only = refonly;
+       image->ref_count = 1;
 
-       return do_mono_image_load (image, status);
+       return do_mono_image_load (image, status, care_about_cli);
 }
 
 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;
 }
 
 MonoImage *
-mono_image_loaded_by_guid (const char *guid)
+mono_image_loaded (const char *name)
+{
+       return mono_image_loaded_full (name, FALSE);
+}
+
+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;
 
-       EnterCriticalSection (&images_mutex);
-       res = g_hash_table_lookup (loaded_images_guid_hash, guid);
-       LeaveCriticalSection (&images_mutex);
+       mono_images_lock ();
+       res = g_hash_table_lookup (loaded_images, guid);
+       mono_images_unlock ();
        return res;
 }
 
 MonoImage *
-mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
+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);      
+       g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, 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;
@@ -864,29 +923,32 @@ mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, Mon
        }
 
        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;
+
+       image = do_mono_image_load (image, status, TRUE);
+       if (image == NULL)
+               return NULL;
 
-       return do_mono_image_load (image, status);
+       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
- *
- * Retuns: 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);
+}
+
+MonoImage *
+mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
 {
-       MonoImage *image, *image2;
+       MonoImage *image;
+       GHashTable *loaded_images;
        char *absfname;
        
        g_return_val_if_fail (fname != NULL, NULL);
@@ -899,38 +961,58 @@ 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){
-               image->ref_count++;
-               LeaveCriticalSection (&images_mutex);
+               mono_image_addref (image);
+               mono_images_unlock ();
                return image;
        }
-       LeaveCriticalSection (&images_mutex);
+       mono_images_unlock ();
 
-       image = do_mono_image_open (fname, status);
+       image = do_mono_image_open (fname, status, TRUE, refonly);
        if (image == NULL)
                return NULL;
 
-       EnterCriticalSection (&images_mutex);
-       image2 = g_hash_table_lookup (loaded_images_hash, image->name);
+       return register_image (image);
+}
 
-       if (image2) {
-               /* Somebody else beat us to it */
-               image2->ref_count ++;
-               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_insert (loaded_images_hash, (char *) image->assembly_name, image); 
-       g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
-       LeaveCriticalSection (&images_mutex);
+/**
+ * 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);
+}
 
-       return image;
+/**
+ * mono_pe_file_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.
+ * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
+ * It's just a PE file loader, used for FileVersionInfo.  It also does
+ * not use the image cache.
+ */
+MonoImage *
+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, FALSE));
 }
 
 static void
@@ -939,11 +1021,31 @@ 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_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)
+{
+       g_free (val);
+}
+
+static void
+free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
+{
+       g_slist_free ((GSList*)val);
+}
 
 /**
  * mono_image_addref:
@@ -957,6 +1059,18 @@ mono_image_addref (MonoImage *image)
        InterlockedIncrement (&image->ref_count);
 }      
 
+void
+mono_dynamic_stream_reset (MonoDynamicStream* stream)
+{
+       stream->alloc_size = stream->index = stream->offset = 0;
+       g_free (stream->data);
+       stream->data = NULL;
+       if (stream->hash) {
+               g_hash_table_destroy (stream->hash);
+               stream->hash = NULL;
+       }
+}
+
 /**
  * mono_image_close:
  * @image: The image file we wish to close
@@ -968,32 +1082,43 @@ void
 mono_image_close (MonoImage *image)
 {
        MonoImage *image2;
+       GHashTable *loaded_images, *loaded_images_guid;
+       int i;
 
        g_return_if_fail (image != NULL);
 
-       EnterCriticalSection (&images_mutex);
-       if (--image->ref_count) {
-               LeaveCriticalSection (&images_mutex);
+       if (InterlockedDecrement (&image->ref_count) > 0)
                return;
-       }
-       image2 = g_hash_table_lookup (loaded_images_hash, image->name);
+
+       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
+       
+       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_hash, image->name);
-               if (image->assembly_name)
-                       g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);        
-               g_hash_table_remove (loaded_images_guid_hash, image->guid);
-               /* Multiple images might have the same guid */
-               build_guid_table ();
-       }       
-       LeaveCriticalSection (&images_mutex);
-
-       if (image->f)
-               fclose (image->f);
+               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);
+
+       mono_images_unlock ();
+
+       if (image->file_descr) {
+               fclose (image->file_descr);
+               image->file_descr = NULL;
+               if (image->raw_data != NULL)
+                       mono_raw_buffer_free (image->raw_data);
+       }
+       
        if (image->raw_data_allocated) {
                /* image->raw_metadata and cli_sections might lie inside image->raw_data */
                MonoCLIImageInfo *ii = image->image_info;
-               int i;
 
                if ((image->raw_metadata > image->raw_data) &&
                        (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
@@ -1006,13 +1131,25 @@ mono_image_close (MonoImage *image)
 
                g_free (image->raw_data);
        }
-       g_free (image->name);
-       g_free (image->files);
+
+       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);
+       }
 
        g_hash_table_destroy (image->method_cache);
        g_hash_table_destroy (image->class_cache);
        g_hash_table_destroy (image->field_cache);
-       g_hash_table_destroy (image->array_cache);
+       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->ptr_cache)
+               g_hash_table_destroy (image->ptr_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);
@@ -1020,27 +1157,35 @@ mono_image_close (MonoImage *image)
        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_destroy (image->generic_inst_cache);
-       g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
+       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);
+
+       /* 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);
-       
-       if (image->raw_metadata != NULL)
-               mono_raw_buffer_free (image->raw_metadata);
-       
+       g_hash_table_destroy (image->method_signatures);
+
+       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;
-               int i;
 
-               for (i = 0; i < ii->cli_section_count; i++){
-                       if (!ii->cli_sections [i])
-                               continue;
-                       mono_raw_buffer_free (ii->cli_sections [i]);
-               }
                if (ii->cli_section_tables)
                        g_free (ii->cli_section_tables);
                if (ii->cli_sections)
@@ -1048,9 +1193,65 @@ mono_image_close (MonoImage *image)
                g_free (image->image_info);
        }
 
-       if (!image->dynamic)
+       for (i = 0; i < image->module_count; ++i) {
+               if (image->modules [i])
+                       mono_image_close (image->modules [i]);
+       }
+       if (image->modules)
+               g_free (image->modules);
+       if (image->references)
+               g_free (image->references);
+       /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
+       if (!image->dynamic) {
+               if (debug_assembly_unload)
+                       mono_mempool_invalidate (image->mempool);
+               else {
+                       mono_mempool_destroy (image->mempool);
+                       g_free (image);
+               }
+       } else {
                /* Dynamic images are GC_MALLOCed */
-               g_free (image);
+               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_mempool_destroy (image->mempool);
+       }
 }
 
 /** 
@@ -1107,8 +1308,10 @@ mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
                }
 #endif
        } else if (level==2) {
-               if((is_string==FALSE && entry->name_offset!=lang_id) ||
-                  (is_string==TRUE)) {
+               if ((is_string == FALSE &&
+                   entry->name_offset != lang_id &&
+                   lang_id != 0) ||
+                  (is_string == TRUE)) {
                        return(NULL);
                }
        } else {
@@ -1143,6 +1346,16 @@ mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
        }
 }
 
+/**
+ * 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.
+ */
 gpointer
 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
 {
@@ -1201,12 +1414,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)
 {
@@ -1338,10 +1572,16 @@ 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)
 {
-       if (table_id < 0 || table_id >= 64)
+       if (table_id < 0 || table_id >= MONO_TABLE_NUM)
                return NULL;
        return &image->tables [table_id];
 }
@@ -1349,13 +1589,13 @@ mono_image_get_table_info (MonoImage *image, int table_id)
 int
 mono_image_get_table_rows (MonoImage *image, int table_id)
 {
-       if (table_id < 0 || table_id >= 64)
+       if (table_id < 0 || table_id >= MONO_TABLE_NUM)
                return 0;
        return image->tables [table_id].rows;
 }
 
 int
-mono_table_info_get_rows (MonoTableInfo *table)
+mono_table_info_get_rows (const MonoTableInfo *table)
 {
        return table->rows;
 }
@@ -1372,4 +1612,12 @@ mono_image_is_dynamic (MonoImage *image)
        return image->dynamic;
 }
 
-
+gboolean
+mono_image_has_authenticode_entry (MonoImage *image)
+{
+       MonoCLIImageInfo *iinfo = image->image_info;
+       MonoDotNetHeader *header = &iinfo->cli_header;
+       MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
+       // the Authenticode "pre" (non ASN.1) header is 8 bytes long
+       return ((de->rva != 0) && (de->size > 8));
+}