2002-08-16 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mono / metadata / assembly.c
index 38aff042bf007ff6837f36abaf71581d6ce9d590..4a36e9ede8d806203c81225f6619994499399cb4 100644 (file)
@@ -1,6 +1,5 @@
 /*
- * assembly.c: Routines for manipulating and assembly stored in an
- * extended PE/COFF file.
+ * assembly.c: Routines for loading assemblies.
  * 
  * Author:
  *   Miguel de Icaza (miguel@ximian.com)
  * (C) 2001 Ximian, Inc.  http://www.ximian.com
  *
  * TODO:
- *   Do byteswaps for big-endian systems on the various headers.
+ *   Implement big-endian versions of the reading routines.
  */
 #include <config.h>
 #include <stdio.h>
 #include <glib.h>
 #include <errno.h>
 #include <string.h>
+#include <stdlib.h>
 #include "assembly.h"
+#include "image.h"
 #include "cil-coff.h"
 #include "rawbuffer.h"
 
-#define INVALID_ADDRESS 0xffffffff
+/* the default search path is just MONO_ASSEMBLIES */
+static const char*
+default_path [] = {
+       MONO_ASSEMBLIES,
+       NULL
+};
 
-/* FIXME: implement big endian versions */
-#define le64_to_cpu(x) (x)
-#define le32_to_cpu(x) (x)
-#define le16_to_cpu(x) (x)
-#define read32(x) le32_to_cpu (*((guint32 *) (x)))
-#define read16(x) le16_to_cpu (*((guint16 *) (x)))
-#define read64(x) le64_to_cpu (*((guint64 *) (x)))
+static char **assemblies_path = NULL;
+static int env_checked = 0;
 
-static guint32
-coff_map (dotnet_image_info_t *iinfo, guint32 addr)
-{
-       const int top = iinfo->dn_section_count;
-       section_table_t *tables = iinfo->dn_section_tables;
-       int i;
+static void
+check_env (void) {
+       const char *path;
+       char **splitted;
        
-       for (i = 0; i < top; i++){
-               if ((addr >= tables->st_virtual_address) &&
-                   (addr < tables->st_virtual_address + tables->st_raw_data_size)){
-                       return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
-               }
-               tables++;
-       }
-       return INVALID_ADDRESS;
+       if (env_checked)
+               return;
+       env_checked = 1;
+
+       path = getenv ("MONO_PATH");
+       if (!path)
+               return;
+       splitted = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 1000);
+       if (assemblies_path)
+               g_strfreev (assemblies_path);
+       assemblies_path = splitted;
 }
 
-static int
-load_section_tables (MonoAssembly *assembly, dotnet_image_info_t *iinfo)
-{
-       const int top = iinfo->dn_header.coff.coff_sections;
-       int i;
-
-       iinfo->dn_section_count = top;
-       iinfo->dn_section_tables = g_new (section_table_t, top);
+/*
+ * keeps track of loaded assemblies
+ */
+static GList *loaded_assemblies = NULL;
+static MonoAssembly *corlib;
 
-       for (i = 0; i < top; i++){
-               section_table_t *t = &iinfo->dn_section_tables [i];
-               
-               if (fread (t, sizeof (section_table_t), 1, assembly->f) != 1)
-                       return FALSE;
-
-               t->st_virtual_size = le32_to_cpu (t->st_virtual_size);
-               t->st_virtual_address = le32_to_cpu (t->st_virtual_address);
-               t->st_raw_data_size = le32_to_cpu (t->st_raw_data_size);
-               t->st_raw_data_ptr = le32_to_cpu (t->st_raw_data_ptr);
-               t->st_reloc_ptr = le32_to_cpu (t->st_reloc_ptr);
-               t->st_lineno_ptr = le32_to_cpu (t->st_lineno_ptr);
-               t->st_reloc_count = le16_to_cpu (t->st_reloc_count);
-               t->st_line_count = le16_to_cpu (t->st_line_count);
+static MonoAssembly*
+search_loaded (MonoAssemblyName* aname)
+{
+       GList *tmp;
+       MonoAssembly *ass;
+       
+       for (tmp = loaded_assemblies; tmp; tmp = tmp->next) {
+               ass = tmp->data;
+               /* we just compare the name, but later we'll do all the checks */
+               /* g_print ("compare %s %s\n", aname->name, ass->aname.name); */
+               if (strcmp (aname->name, ass->aname.name))
+                       continue;
+               /* g_print ("success\n"); */
+               return ass;
        }
-
-       return TRUE;
+       return NULL;
 }
 
-static gboolean
-load_cli_header (MonoAssembly *assembly, dotnet_image_info_t *iinfo)
+/**
+ * g_concat_dir_and_file:
+ * @dir:  directory name
+ * @file: filename.
+ *
+ * returns a new allocated string that is the concatenation of dir and file,
+ * takes care of the exact details for concatenating them.
+ */
+static char *
+g_concat_dir_and_file (const char *dir, const char *file)
 {
-       guint32 offset;
-       int n;
-       
-       offset = coff_map (iinfo, iinfo->dn_header.datadir.pe_cli_header.rva);
-       if (offset == INVALID_ADDRESS)
-               return FALSE;
+       g_return_val_if_fail (dir != NULL, NULL);
+       g_return_val_if_fail (file != NULL, NULL);
 
-       if (fseek (assembly->f, offset, 0) != 0)
-               return FALSE;
-       
-       if ((n = fread (&iinfo->dn_cli_header, sizeof (cli_header_t), 1, assembly->f)) != 1)
-               return FALSE;
-
-       /* Catch new uses of the fields that are supposed to be zero */
-
-       if ((iinfo->dn_cli_header.ch_eeinfo_table.rva != 0) ||
-           (iinfo->dn_cli_header.ch_helper_table.rva != 0) ||
-           (iinfo->dn_cli_header.ch_dynamic_info.rva != 0) ||
-           (iinfo->dn_cli_header.ch_delay_load_info.rva != 0) ||
-           (iinfo->dn_cli_header.ch_module_image.rva != 0) ||
-           (iinfo->dn_cli_header.ch_external_fixups.rva != 0) ||
-           (iinfo->dn_cli_header.ch_ridmap.rva != 0) ||
-           (iinfo->dn_cli_header.ch_debug_map.rva != 0) ||
-           (iinfo->dn_cli_header.ch_ip_map.rva != 0)){
-               g_message ("Some fields in the CLI header which should have been zero are not zero");
-       }
-           
-       return TRUE;
+        /*
+        * If the directory name doesn't have a / on the end, we need
+        * to add one so we get a proper path to the file
+        */
+       if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
+               return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
+       else
+               return g_strconcat (dir, file, NULL);
 }
 
-static gboolean
-load_metadata_ptrs (MonoAssembly *assembly, dotnet_image_info_t *iinfo)
+static MonoAssembly *
+load_in_path (const char *basename, const char** search_path, MonoImageOpenStatus *status)
 {
-       metadata_t *metadata = &iinfo->dn_metadata;
-       guint32 offset, size;
-       guint16 streams;
        int i;
-       char *ptr;
-       
-       offset = coff_map (iinfo, iinfo->dn_cli_header.ch_metadata.rva);
-       size = iinfo->dn_cli_header.ch_metadata.size;
-       
-       metadata->raw_metadata = raw_buffer_load (fileno (assembly->f), FALSE, offset, size);
-       if (metadata->raw_metadata == NULL)
-               return FALSE;
-
-       ptr = metadata->raw_metadata;
-
-       if (strncmp (ptr, "BSJB", 4) == 0){
-               guint32 version_string_len;
-
-               ptr += 12;
-               version_string_len = read32 (ptr);
-               ptr += 4;
-               ptr += version_string_len;
-               if (((guint32) ptr) % 4)
-                       ptr += 4 - (((guint32) ptr) %4);
-       } else
-               return FALSE;
-
-       /* skip over flags */
-       ptr += 2;
-       
-       streams = read16 (ptr);
-       ptr += 2;
-
-       for (i = 0; i < streams; i++){
-               if (strncmp (ptr + 8, "#~", 3) == 0){
-                       metadata->heap_tables.sh_offset = read32 (ptr);
-                       metadata->heap_tables.sh_size = read32 (ptr + 4);
-                       ptr += 8 + 3;
-               } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
-                       metadata->heap_strings.sh_offset = read32 (ptr);
-                       metadata->heap_strings.sh_size = read32 (ptr + 4);
-                       ptr += 8 + 9;
-               } else if (strncmp (ptr + 8, "#US", 4) == 0){
-                       metadata->heap_us.sh_offset = read32 (ptr);
-                       metadata->heap_us.sh_size = read32 (ptr + 4);
-                       ptr += 8 + 4;
-               } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
-                       metadata->heap_blob.sh_offset = read32 (ptr);
-                       metadata->heap_blob.sh_size = read32 (ptr + 4);
-                       ptr += 8 + 6;
-               } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
-                       metadata->heap_guid.sh_offset = read32 (ptr);
-                       metadata->heap_guid.sh_size = read32 (ptr + 4);
-                       ptr += 8 + 6;
-               } else
-                       g_message ("Unknown heap type: %s\n", ptr + 8);
-               if (((guint32)ptr) % 4){
-                       ptr += 4 - (((guint32)ptr) % 4);
-               }
+       char *fullpath;
+       MonoAssembly *result;
+
+       for (i = 0; search_path [i]; ++i) {
+               fullpath = g_concat_dir_and_file (search_path [i], basename);
+               result = mono_assembly_open (fullpath, status);
+               g_free (fullpath);
+               if (result)
+                       return result;
        }
-       return TRUE;
+       return NULL;
 }
 
-static gboolean
-load_tables (MonoAssembly *assembly, metadata_t *meta)
+/**
+ * mono_assembly_setrootdir:
+ * @root_dir: The pathname of the root directory where we will locate assemblies
+ *
+ * This routine sets the internal default root directory for looking up
+ * assemblies.  This is used by Windows installations to compute dynamically
+ * the place where the Mono assemblies are located.
+ *
+ */
+void
+mono_assembly_setrootdir (const char *root_dir)
 {
-       char *heap_tables = meta->raw_metadata + meta->heap_tables.sh_offset;
-       guint32 *rows;
-       guint64 valid_mask;
-       int valid = 0, table;
-       
-       valid_mask = read64 (heap_tables + 8);
-       rows = (guint32 *) (heap_tables + 24);
-       
-       for (table = 0; table < 64; table++){
-               if ((valid_mask & ((guint64) 1 << table)) == 0){
-                       meta->rows [table] = 0;
-                       continue;
+       /*
+        * Override the MONO_ASSEMBLIES directory configured at compile time.
+        */
+       default_path [0] = g_strdup (root_dir);
+}
+
+static void
+load_references (MonoImage *image, MonoImageOpenStatus *status) {
+       MonoTableInfo *t;
+       guint32 cols [MONO_ASSEMBLYREF_SIZE];
+       const char *hash;
+       int i;
+
+       if (image->references)
+               return;
+
+       t = &image->tables [MONO_TABLE_ASSEMBLYREF];
+
+       image->references = g_new0 (MonoAssembly *, t->rows + 1);
+
+       /*
+        * Load any assemblies this image references
+        */
+       for (i = 0; i < t->rows; i++) {
+               MonoAssemblyName aname;
+
+               mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
+               
+               hash = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_HASH_VALUE]);
+               aname.hash_len = mono_metadata_decode_blob_size (hash, &hash);
+               aname.hash_value = hash;
+               aname.name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME]);
+               aname.culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]);
+               aname.flags = cols [MONO_ASSEMBLYREF_FLAGS];
+               aname.major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
+               aname.minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
+               aname.build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
+               aname.revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
+
+               image->references [i] = mono_assembly_load (&aname, image->assembly->basedir, status);
+
+               if (image->references [i] == NULL){
+                       int j;
+                       
+                       for (j = 0; j < i; j++)
+                               mono_assembly_close (image->references [j]);
+                       g_free (image->references);
+                       image->references = NULL;
+
+                       g_warning ("Could not find assembly %s", aname.name);
+                       *status = MONO_IMAGE_MISSING_ASSEMBLYREF;
+                       return;
                }
-               meta->rows [table] = *rows;
-               rows++;
-               valid++;
        }
+       image->references [i] = NULL;
 
-       return TRUE;
 }
 
-static gboolean
-load_metadata (MonoAssembly *assembly, dotnet_image_info_t *iinfo)
+/**
+ * mono_assembly_open:
+ * @filename: Opens the assembly pointed out by this name
+ * @status: where a status code can be returned
+ *
+ * mono_assembly_open opens the PE-image pointed by @filename, and
+ * loads any external assemblies referenced by it.
+ *
+ * NOTE: we could do lazy loading of the assemblies.  Or maybe not worth
+ * it. 
+ */
+MonoAssembly *
+mono_assembly_open (const char *filename, MonoImageOpenStatus *status)
 {
-       if (!load_metadata_ptrs (assembly, iinfo))
-               return FALSE;
+       MonoAssembly *ass, *ass2;
+       MonoImage *image;
+       MonoTableInfo *t;
+       guint32 cols [MONO_ASSEMBLY_SIZE];
+       int i;
+       char *base_dir;
+       MonoImageOpenStatus def_status;
+       
+       g_return_val_if_fail (filename != NULL, NULL);
 
-       return load_tables (assembly, &iinfo->dn_metadata);
-}
+       if (!status)
+               status = &def_status;
+       *status = MONO_IMAGE_OK;
 
-MonoAssembly *
-mono_assembly_open (const char *fname, enum MonoAssemblyOpenStatus *status)
-{
-       dotnet_image_info_t *iinfo;
-       dotnet_header_t *header;
-       msdos_header_t msdos;
-       MonoAssembly *assembly;
-       int n;
-
-       assembly = g_new (MonoAssembly, 1);
-       assembly->f = fopen (fname, "r");
-       iinfo = g_new (dotnet_image_info_t, 1);
-       assembly->image_info = iinfo;
-
-       header = &iinfo->dn_header;
-               
-       if (assembly->f == NULL){
-               if (status)
-                       *status = MONO_ASSEMBLY_ERROR_ERRNO;
-               mono_assembly_close (assembly);
+       /* g_print ("file loading %s\n", filename); */
+       image = mono_image_open (filename, status);
+
+       if (!image){
+               *status = MONO_IMAGE_ERROR_ERRNO;
                return NULL;
        }
 
-       if (status)
-               *status = MONO_ASSEMBLY_IMAGE_INVALID;
+       base_dir = g_path_get_dirname (filename);
        
-       if (fread (&msdos, sizeof (msdos), 1, assembly->f) != 1)
-               goto invalid_image;
-       
-       if (!(msdos.msdos_header [0] == 0x4d && msdos.msdos_header [1] == 0x5a))
-               goto invalid_image;
-       
-       if ((n = fread (header, sizeof (dotnet_header_t), 1, assembly->f)) != 1)
-               goto invalid_image;
-
        /*
-        * FIXME: byte swap all addresses here for header.
+        * Create assembly struct, and enter it into the assembly cache
         */
-       
-       if (!load_section_tables (assembly, iinfo))
-               goto invalid_image;
-       
-       /* Load the CLI header */
-       if (!load_cli_header (assembly, iinfo))
-               goto invalid_image;
+       ass = g_new0 (MonoAssembly, 1);
+       ass->basedir = base_dir;
+       ass->image = image;
 
-       if (!load_metadata (assembly, iinfo))
-               goto invalid_image;
-       
-       if (status)
-               *status = MONO_ASSEMBLY_OK;
+       t = &image->tables [MONO_TABLE_ASSEMBLY];
+       if (t->rows) {
+               mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
+               
+               ass->aname.hash_len = 0;
+               ass->aname.hash_value = NULL;
+               ass->aname.name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLY_NAME]);
+               ass->aname.culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLY_CULTURE]);
+               ass->aname.flags = cols [MONO_ASSEMBLY_FLAGS];
+               ass->aname.major = cols [MONO_ASSEMBLY_MAJOR_VERSION];
+               ass->aname.minor = cols [MONO_ASSEMBLY_MINOR_VERSION];
+               ass->aname.build = cols [MONO_ASSEMBLY_BUILD_NUMBER];
+               ass->aname.revision = cols [MONO_ASSEMBLY_REV_NUMBER];
+
+               /* avoid loading the same assembly twixe for now... */
+               if ((ass2 = search_loaded (&ass->aname))) {
+                       g_free (ass);
+                       g_free (base_dir);
+                       *status = MONO_IMAGE_OK;
+                       return ass2;
+               }
+       }
 
-       return assembly;
+       image->assembly = ass;
 
-invalid_image:
-       mono_assembly_close (assembly);
+       /* register right away to prevent loops */
+       loaded_assemblies = g_list_prepend (loaded_assemblies, ass);
+
+       load_references (image, status);
+       if (*status != MONO_IMAGE_OK) {
+               mono_assembly_close (ass);
                return NULL;
+       }
+       
+       t = &image->tables [MONO_TABLE_MODULEREF];
+       ass->modules = g_new0 (MonoImage *, t->rows);
+       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_concat_dir_and_file (base_dir, name);
+               ass->modules [i] = mono_image_open (module_ref, status);
+               if (ass->modules [i]) {
+                       ass->modules [i]->assembly = ass;
+                       load_references (ass->modules [i], status);
+               }
+               /* 
+                * FIXME: what do we do here? it could be a native dll...
+                * We should probably do lazy-loading of modules.
+                */
+               *status = MONO_IMAGE_OK;
+               g_free (module_ref);
+       }
+
+       return ass;
 }
 
-void
-mono_assembly_close (MonoAssembly *assembly)
+MonoAssembly*
+mono_assembly_load (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status)
 {
-       g_return_if_fail (assembly != NULL);
+       MonoAssembly *result;
+       char *fullpath, *filename;
 
-       if (assembly->f)
-               fclose (assembly->f);
+       check_env ();
 
-       if (assembly->image_info){
-               dotnet_image_info_t *ii = assembly->image_info;
+       /* g_print ("loading %s\n", aname->name); */
+       /* special case corlib */
+       if ((strcmp (aname->name, "mscorlib") == 0) || (strcmp (aname->name, "corlib") == 0)) {
+               if (corlib) {
+                       /* g_print ("corlib already loaded\n"); */
+                       return corlib;
+               }
+               /* g_print ("corlib load\n"); */
+               if (assemblies_path) {
+                       corlib = load_in_path (CORLIB_NAME, (const char**)assemblies_path, status);
+                       if (corlib)
+                               return corlib;
+               }
+               corlib = load_in_path (CORLIB_NAME, default_path, status);
+               return corlib;
+       }
+       result = search_loaded (aname);
+       if (result)
+               return result;
+       /* g_print ("%s not found in cache\n", aname->name); */
+       if (strstr (aname->name, ".dll"))
+               filename = g_strdup (aname->name);
+       else
+               filename = g_strconcat (aname->name, ".dll", NULL);
+       if (basedir) {
+               fullpath = g_concat_dir_and_file (basedir, filename);
+               result = mono_assembly_open (fullpath, status);
+               g_free (fullpath);
+               if (result) {
+                       g_free (filename);
+                       return result;
+               }
+       }
+       if (assemblies_path) {
+               result = load_in_path (filename, (const char**)assemblies_path, status);
+               if (result) {
+                       g_free (filename);
+                       return result;
+               }
+       }
+       result = load_in_path (filename, default_path, status);
+       g_free (filename);
+       return result;
+}
 
-               if (ii->dn_metadata.raw_metadata != NULL)
-                       raw_buffer_free (ii->dn_metadata.raw_metadata);
+void
+mono_assembly_close (MonoAssembly *assembly)
+{
+       MonoImage *image;
+       int i;
        
-               if (ii->dn_section_tables)
-                       g_free (ii->dn_section_tables);
+       g_return_if_fail (assembly != NULL);
 
-               g_free (assembly->image_info);
-       }
+       if (--assembly->ref_count != 0)
+               return;
        
+       loaded_assemblies = g_list_remove (loaded_assemblies, assembly);
+       image = assembly->image;
+       if (image->references) {
+               for (i = 0; image->references [i] != NULL; i++)
+                       mono_image_close (image->references [i]->image);
+               g_free (image->references);
+       }
+            
+       mono_image_close (assembly->image);
+
+       g_free (assembly->basedir);
        g_free (assembly);
 }
 
-const char *
-mono_assembly_strerror (enum MonoAssemblyOpenStatus status)
+void
+mono_assembly_foreach (GFunc func, gpointer user_data)
 {
-       switch (status){
-       case MONO_ASSEMBLY_OK:
-               return "succes";
-       case MONO_ASSEMBLY_ERROR_ERRNO:
-               return strerror (errno);
-       case MONO_ASSEMBLY_IMAGE_INVALID:
-               return "File does not contain a valid CIL image";
-       }
-       return "Internal error";
+       /* In the future this can do locking of loaded_assemblies */
+
+       g_list_foreach (loaded_assemblies, func, user_data);
+}
+
+/* Holds the assembly of the application, for
+ * System.Diagnostics.Process::MainModule
+ */
+static MonoAssembly *main_assembly=NULL;
+
+void
+mono_assembly_set_main (MonoAssembly *assembly)
+{
+       main_assembly=assembly;
+}
+
+MonoAssembly *
+mono_assembly_get_main (void)
+{
+       return(main_assembly);
 }