2005-06-27 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mono / metadata / image.c
index 7885a174c1d11090d52d280c33366e65df7f10ac..9d0369296ac1c8fd94a403d6d09256d2a918281b 100644 (file)
@@ -2,13 +2,12 @@
  * image.c: Routines for manipulating an image stored in an
  * extended PE/COFF file.
  * 
- * Author:
+ * Authors:
  *   Miguel de Icaza (miguel@ximian.com)
+ *   Paolo Molaro (lupus@ximian.com)
  *
- * (C) 2001 Ximian, Inc.  http://www.ximian.com
+ * (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
  *
- * TODO:
- *   Implement big-endian versions of the reading routines.
  */
 #include <config.h>
 #include <stdio.h>
 #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 <mono/io-layer/io-layer.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
 
 #define INVALID_ADDRESS 0xffffffff
 
@@ -31,6 +35,8 @@
 static GHashTable *loaded_images_hash;
 static GHashTable *loaded_images_guid_hash;
 
+static CRITICAL_SECTION images_mutex;
+
 guint32
 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
 {
@@ -49,8 +55,9 @@ mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
 }
 
 char *
-mono_cli_rva_map (MonoCLIImageInfo *iinfo, guint32 addr)
+mono_image_rva_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;
@@ -58,6 +65,10 @@ mono_cli_rva_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)){
+                       if (!iinfo->cli_sections [i]) {
+                               if (!mono_image_ensure_section_idx (image, i))
+                                       return NULL;
+                       }
                        return (char*)iinfo->cli_sections [i] +
                                (addr - tables->st_virtual_address);
                }
@@ -66,6 +77,62 @@ mono_cli_rva_map (MonoCLIImageInfo *iinfo, 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:
+ *
+ *  Initialize the global variables used by this module.
+ */
+void
+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);
+}
+
 /**
  * mono_image_ensure_section_idx:
  * @image: The image we are operating on
@@ -92,13 +159,10 @@ mono_image_ensure_section_idx (MonoImage *image, int section)
        
        writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
 
-       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;
 }
 
@@ -128,7 +192,7 @@ mono_image_ensure_section (MonoImage *image, const char *section)
 }
 
 static int
-load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo)
+load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
 {
        const int top = iinfo->cli_header.coff.coff_sections;
        int i;
@@ -139,9 +203,11 @@ load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo)
        
        for (i = 0; i < top; i++){
                MonoSectionTable *t = &iinfo->cli_section_tables [i];
-               
-               if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
+
+               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);
@@ -157,10 +223,6 @@ load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo)
                /* consistency checks here */
        }
 
-       for (i = 0; i < top; i++)
-               if (!mono_image_ensure_section_idx (image, i))
-                       return FALSE;
-       
        return TRUE;
 }
 
@@ -168,17 +230,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 (fseek (image->f, offset, SEEK_SET) != 0)
-               return FALSE;
-       
-       if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
+       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))
@@ -237,14 +296,18 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
        guint32 offset, size;
        guint16 streams;
        int i;
+       guint32 pad;
        char *ptr;
        
        offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
+       if (offset == INVALID_ADDRESS)
+               return FALSE;
+
        size = iinfo->cli_cli_header.ch_metadata.size;
-       
-       image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
-       if (image->raw_metadata == NULL)
+
+       if (offset + size > image->raw_data_len)
                return FALSE;
+       image->raw_metadata = image->raw_data + offset;
 
        ptr = image->raw_metadata;
 
@@ -254,9 +317,11 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
                ptr += 12;
                version_string_len = read32 (ptr);
                ptr += 4;
+               image->version = g_strndup (ptr, version_string_len);
                ptr += version_string_len;
-               if (((guint32) ptr) % 4)
-                       ptr += 4 - (((guint32) ptr) %4);
+               pad = ptr - image->raw_metadata;
+               if (pad % 4)
+                       ptr += 4 - (pad % 4);
        } else
                return FALSE;
 
@@ -287,13 +352,16 @@ load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
                        image->heap_guid.data = image->raw_metadata + read32 (ptr);
                        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;
                } else {
                        g_message ("Unknown heap type: %s\n", ptr + 8);
-                       ptr += 8 + strlen (ptr) + 1;
-               }
-               if (((guint32)ptr) % 4){
-                       ptr += 4 - (((guint32)ptr) % 4);
+                       ptr += 8 + strlen (ptr + 8) + 1;
                }
+               pad = ptr - image->raw_metadata;
+               if (pad % 4)
+                       ptr += 4 - (pad % 4);
        }
 
        g_assert (image->heap_guid.data);
@@ -327,16 +395,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 > 0x2b) {
-                       g_warning("bits in valid must be zero above 0x2b (II - 23.1.6)");
+               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++;
        }
@@ -359,6 +430,58 @@ load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
        return load_tables (image);
 }
 
+void
+mono_image_add_to_name_cache (MonoImage *image, const char *nspace, 
+                                                         const char *name, guint32 index)
+{
+       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);
+       }
+       g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
+}
+
+static void
+load_modules (MonoImage *image, MonoImageOpenStatus *status)
+{
+       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->module_count = t->rows;
+       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];
+
+               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);
+               if (image->modules [i]) {
+                       /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
+               }
+               /* 
+                * 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)
 {
@@ -366,9 +489,11 @@ load_class_names (MonoImage *image)
        guint32 cols [MONO_TYPEDEF_SIZE];
        const char *name;
        const char *nspace;
-       GHashTable *nspace_table;
-       GHashTable *name_cache = image->name_cache;
-       guint32 i, visib;
+       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);
@@ -378,35 +503,68 @@ load_class_names (MonoImage *image)
                        continue;
                name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
                nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
-               if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
+
+               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 (name_cache, (char *)nspace, (char *)nspace_table);
+                       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 (i));
        }
+
+       /* Load type names from EXPORTEDTYPES table */
+       {
+               MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
+               guint32 cols [MONO_EXP_TYPE_SIZE];
+               int i;
+
+               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_hash_table_destroy (name_cache2);
 }
 
-static MonoImage *
-do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
+static void
+register_guid (gpointer key, gpointer value, gpointer user_data)
 {
-       MonoCLIImageInfo *iinfo;
-       MonoDotNetHeader *header;
-       MonoMSDOSHeader msdos;
-       MonoImage *image;
-       int n;
+       MonoImage *image = (MonoImage*)value;
 
-       image = g_new0 (MonoImage, 1);
-       image->ref_count = 1;
-       image->f = fopen (fname, "rb");
-       image->name = g_strdup (fname);
-       iinfo = g_new0 (MonoCLIImageInfo, 1);
-       image->image_info = iinfo;
+       if (!g_hash_table_lookup (loaded_images_guid_hash, image))
+               g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
+}
+
+static void
+build_guid_table (void)
+{
+       g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
+}
 
-       image->method_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
-       image->class_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
+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 ((GHashFunc)mono_metadata_type_hash, 
-                                              (GCompareFunc)mono_metadata_type_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, 
@@ -417,37 +575,53 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
        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);
+}
 
-       image->runtime_invoke_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
-       image->managed_wrapper_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
-       image->native_wrapper_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
-       image->remoting_invoke_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
+static MonoImage *
+do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
+                   gboolean care_about_cli)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoDotNetHeader *header;
+       MonoMSDOSHeader msdos;
+       guint32 offset = 0;
+
+       mono_image_init (image);
 
+       iinfo = image->image_info;
        header = &iinfo->cli_header;
                
-       if (image->f == NULL){
-               if (status)
-                       *status = MONO_IMAGE_ERROR_ERRNO;
-               mono_image_close (image);
-               return NULL;
-       }
-
        if (status)
                *status = MONO_IMAGE_IMAGE_INVALID;
-       
-       if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
+
+       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))
-               fseek (image->f, msdos.pe_offset, SEEK_SET);
-       
-       if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
+       offset = msdos.pe_offset;
+
+       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))
@@ -544,9 +718,13 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
         * FIXME: byte swap all addresses here for header.
         */
        
-       if (!load_section_tables (image, iinfo))
+       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;
@@ -566,6 +744,9 @@ do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
                        mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
                                        0, MONO_MODULE_NAME));
 
+       load_modules (image, status);
+
+done:
        if (status)
                *status = MONO_IMAGE_OK;
 
@@ -578,20 +759,122 @@ invalid_image:
                return NULL;
 }
 
+static MonoImage *
+do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
+                   gboolean care_about_cli)
+{
+       MonoCLIImageInfo *iinfo;
+       MonoImage *image;
+       FILE *filed;
+       struct stat stat_buf;
+
+       if ((filed = fopen (fname, "rb")) == NULL){
+               if (status)
+                       *status = MONO_IMAGE_ERROR_ERRNO;
+               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->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);
+
+       return do_mono_image_load (image, status, care_about_cli);
+}
+
 MonoImage *
-mono_image_loaded (const char *name) {
-       if (strcmp (name, "mscorlib") == 0)
-               name = "corlib";
-       if (loaded_images_hash)
-               return g_hash_table_lookup (loaded_images_hash, name);
-       return NULL;
+mono_image_loaded (const char *name)
+{
+       MonoImage *res;
+        
+       EnterCriticalSection (&images_mutex);
+       res = g_hash_table_lookup (loaded_images_hash, name);
+       LeaveCriticalSection (&images_mutex);
+       return res;
 }
 
 MonoImage *
-mono_image_loaded_by_guid (const char *guid) {
-       if (loaded_images_guid_hash)
-               return g_hash_table_lookup (loaded_images_guid_hash, guid);
-       return NULL;
+mono_image_loaded_by_guid (const char *guid)
+{
+       MonoImage *res;
+
+       EnterCriticalSection (&images_mutex);
+       res = g_hash_table_lookup (loaded_images_guid_hash, guid);
+       LeaveCriticalSection (&images_mutex);
+       return res;
+}
+
+static MonoImage *
+register_image (MonoImage *image)
+{
+       MonoImage *image2;
+
+       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 image;
+}
+
+MonoImage *
+mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
+{
+       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 = do_mono_image_load (image, status, TRUE);
+       if (image == NULL)
+               return NULL;
+
+       return register_image (image);
 }
 
 /**
@@ -599,47 +882,104 @@ mono_image_loaded_by_guid (const char *guid) {
  * @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.
+ * 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)
 {
        MonoImage *image;
+       char *absfname;
        
        g_return_val_if_fail (fname != NULL, NULL);
+       
+       absfname = canonicalize_path (fname);
 
-       if (loaded_images_hash){
-               image = g_hash_table_lookup (loaded_images_hash, fname);
-               if (image){
-                       image->ref_count++;
-                       return image;
-               }
+       /*
+        * The easiest solution would be to do all the loading inside the mutex,
+        * but that would lead to scalability problems. So we let the loading
+        * 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);
+       g_free (absfname);
+       
+       if (image){
+               mono_image_addref (image);
+               LeaveCriticalSection (&images_mutex);
+               return image;
        }
+       LeaveCriticalSection (&images_mutex);
 
-       image = do_mono_image_open (fname, status);
+       image = do_mono_image_open (fname, status, TRUE);
        if (image == NULL)
                return NULL;
 
-       if (!loaded_images_hash)
-               loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
-       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);
-       
-       if (!loaded_images_guid_hash)
-               loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
-       g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
+       return register_image (image);
+}
 
-       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));
 }
 
 static void
-free_hash_table(gpointer key, gpointer val, gpointer user_data)
+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)
+{
+       g_free (val);
+}
+
+/**
+ * mono_image_addref:
+ * @image: The image file we wish to add a reference to
+ *
+ *  Increases the reference count of an image.
+ */
+void
+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
@@ -650,22 +990,59 @@ free_hash_table(gpointer key, gpointer val, gpointer user_data)
 void
 mono_image_close (MonoImage *image)
 {
+       MonoImage *image2;
+       int i;
+
        g_return_if_fail (image != NULL);
 
-       if (--image->ref_count)
+       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);
                return;
-
-       if (!loaded_images_hash)
-               loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
-       g_hash_table_remove (loaded_images_hash, image->name);
+       }
+       image2 = g_hash_table_lookup (loaded_images_hash, 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 ();
+       }
+       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->file_descr) {
+               fclose (image->file_descr);
+               image->file_descr = NULL;
+               if (image->raw_data != NULL)
+                       mono_raw_buffer_free (image->raw_data);
+       }
        
-       if (image->f)
-               fclose (image->f);
+       if (image->raw_data_allocated) {
+               /* image->raw_metadata and cli_sections might lie inside image->raw_data */
+               MonoCLIImageInfo *ii = image->image_info;
+
+               if ((image->raw_metadata > image->raw_data) &&
+                       (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
+                       image->raw_metadata = NULL;
+
+               for (i = 0; i < ii->cli_section_count; i++)
+                       if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
+                               ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
+                               ii->cli_sections [i] = NULL;
 
+               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);
+       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);
@@ -674,29 +1051,76 @@ 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);
-       
-       if (image->raw_metadata != NULL)
-               mono_raw_buffer_free (image->raw_metadata);
+       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);
+       g_hash_table_destroy (image->memberref_signatures);
+       g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
+       g_hash_table_destroy (image->helper_signatures);
        
        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)
                        g_free (ii->cli_sections);
                g_free (image->image_info);
        }
-       
-       g_free (image);
+
+       for (i = 0; i < image->module_count; ++i) {
+               if (image->modules [i])
+                       mono_image_close (image->modules [i]);
+       }
+       /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
+       if (!image->dynamic) {
+               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_mempool_destroy (image->mempool);
+       }
 }
 
 /** 
@@ -753,8 +1177,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 {
@@ -824,7 +1250,7 @@ mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, g
                return(NULL);
        }
 
-       resource_dir=(MonoPEResourceDir *)mono_cli_rva_map (info, rsrc->rva);
+       resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
        if(resource_dir==NULL) {
                return(NULL);
        }
@@ -863,7 +1289,7 @@ mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
        if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
                return NULL;
        
-       data = mono_cli_rva_map (iinfo, ch->ch_resources.rva);
+       data = mono_image_rva_map (image, ch->ch_resources.rva);
        if (!data)
                return NULL;
        data += offset;
@@ -873,6 +1299,45 @@ mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
        return data;
 }
 
+MonoImage*
+mono_image_load_file_for_image (MonoImage *image, int fileidx)
+{
+       char *base_dir, *name;
+       MonoImage *res;
+       MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
+       const char *fname;
+       guint32 fname_id;
+
+       if (fileidx < 1 || fileidx > t->rows)
+               return NULL;
+
+       if (image->files && image->files [fileidx - 1])
+               return image->files [fileidx - 1];
+
+       if (!image->files)
+               image->files = g_new0 (MonoImage*, t->rows);
+
+       fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
+       fname = mono_metadata_string_heap (image, fname_id);
+       base_dir = g_path_get_dirname (image->name);
+       name = g_build_filename (base_dir, fname, NULL);
+       res = mono_image_open (name, NULL);
+       if (res) {
+               int i;
+               /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
+               res->assembly = image->assembly;
+               for (i = 0; i < res->module_count; ++i) {
+                       if (res->modules [i] && !res->modules [i]->assembly)
+                               res->modules [i]->assembly = image->assembly;
+               }
+
+               image->files [fileidx - 1] = res;
+       }
+       g_free (name);
+       g_free (base_dir);
+       return res;
+}
+
 const char*
 mono_image_get_strong_name (MonoImage *image, guint32 *size)
 {
@@ -882,7 +1347,7 @@ mono_image_get_strong_name (MonoImage *image, guint32 *size)
 
        if (!de->size || !de->rva)
                return NULL;
-       data = mono_cli_rva_map (iinfo, de->rva);
+       data = mono_image_rva_map (image, de->rva);
        if (!data)
                return NULL;
        if (size)
@@ -933,3 +1398,58 @@ mono_image_get_public_key (MonoImage *image, guint32 *size)
        return pubkey;
 }
 
+const char*
+mono_image_get_name (MonoImage *image)
+{
+       return image->assembly_name;
+}
+
+const char*
+mono_image_get_filename (MonoImage *image)
+{
+       return image->name;
+}
+
+const MonoTableInfo*
+mono_image_get_table_info (MonoImage *image, int table_id)
+{
+       if (table_id < 0 || table_id >= MONO_TABLE_NUM)
+               return NULL;
+       return &image->tables [table_id];
+}
+
+int
+mono_image_get_table_rows (MonoImage *image, int table_id)
+{
+       if (table_id < 0 || table_id >= MONO_TABLE_NUM)
+               return 0;
+       return image->tables [table_id].rows;
+}
+
+int
+mono_table_info_get_rows (const MonoTableInfo *table)
+{
+       return table->rows;
+}
+
+MonoAssembly* 
+mono_image_get_assembly (MonoImage *image)
+{
+       return image->assembly;
+}
+
+gboolean
+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));
+}