2009-09-23 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mono / metadata / mono-config.c
1 /*
2  * mono-config.c
3  *
4  * Runtime and assembly configuration file support routines.
5  *
6  * Author: Paolo Molaro (lupus@ximian.com)
7  *
8  * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
9  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
10  */
11 #include "config.h"
12 #include <glib.h>
13 #include <string.h>
14
15 #include "mono/metadata/assembly.h"
16 #include "mono/metadata/loader.h"
17 #include "mono/metadata/mono-config.h"
18 #include "mono/metadata/metadata-internals.h"
19 #include "mono/metadata/object-internals.h"
20 #include "mono/utils/mono-logger.h"
21
22 #if defined(__linux__)
23 #define CONFIG_OS "linux"
24 #elif defined(__APPLE__)
25 #define CONFIG_OS "osx"
26 #elif defined(sun)
27 #define CONFIG_OS "solaris"
28 #elif defined(__FreeBSD__)
29 #define CONFIG_OS "freebsd"
30 #elif defined(__NetBSD__)
31 #define CONFIG_OS "netbsd"
32 #elif defined(__OpenBSD__)
33 #define CONFIG_OS "openbsd"
34 #elif defined(__WIN32__)
35 #define CONFIG_OS "windows"
36 #elif defined(_IBMR2)
37 #define CONFIG_OS "aix"
38 #elif defined(__hpux)
39 #define CONFIG_OS "hpux"
40 #elif defined(SN_TARGET_PS3)
41 #define CONFIG_OS "CellOS"
42 #else
43 #warning Unknown operating system
44 #define CONFIG_OS "unknownOS"
45 #endif
46
47 #ifndef CONFIG_CPU
48 #if defined(__i386__)
49 #define CONFIG_CPU "x86"
50 #define CONFIG_WORDSIZE "32"
51 #elif defined(__x86_64__)
52 #define CONFIG_CPU "x86-64"
53 #define CONFIG_WORDSIZE "64"
54 #elif defined(sparc) || defined(__sparc__)
55 #define CONFIG_CPU "sparc"
56 #define CONFIG_WORDSIZE "32"
57 #elif defined(__ppc64__) || defined(__powerpc64__)
58 #define CONFIG_WORDSIZE "64"
59 #ifdef __mono_ppc_ilp32__
60 #   define CONFIG_CPU "ppc64ilp32"
61 #else
62 #   define CONFIG_CPU "ppc64"
63 #endif
64 #elif defined(__ppc__) || defined(__powerpc__)
65 #define CONFIG_CPU "ppc"
66 #define CONFIG_WORDSIZE "32"
67 #elif defined(__s390x__)
68 #define CONFIG_CPU "s390x"
69 #define CONFIG_WORDSIZE "64"
70 #elif defined(__s390__)
71 #define CONFIG_CPU "s390"
72 #define CONFIG_WORDSIZE "32"
73 #elif defined(__arm__)
74 #define CONFIG_CPU "arm"
75 #define CONFIG_WORDSIZE "32"
76 #elif defined(__ia64__)
77 #define CONFIG_CPU "ia64"
78 #define CONFIG_WORDSIZE "64"
79 #elif defined(__alpha__)
80 #define CONFIG_CPU "alpha"
81 #define CONFIG_WORDSIZE "64"
82 #elif defined(hppa) || defined(__hppa__)
83 #define CONFIG_CPU "hppa"
84 #define CONFIG_WORDSIZE "32"
85 #elif defined(mips) || defined(__mips) || defined(_mips)
86 #define CONFIG_CPU "mips"
87 #define CONFIG_WORDSIZE "32"
88 #else
89 #warning Unknown CPU
90 #define CONFIG_CPU "unknownCPU"
91 #endif
92 #endif
93
94 static void start_element (GMarkupParseContext *context, 
95                            const gchar         *element_name,
96                            const gchar        **attribute_names,
97                            const gchar        **attribute_values,
98                            gpointer             user_data,
99                            GError             **error);
100
101 static void end_element   (GMarkupParseContext *context,
102                            const gchar         *element_name,
103                            gpointer             user_data,
104                            GError             **error);
105
106 static void parse_text    (GMarkupParseContext *context,
107                            const gchar         *text,
108                            gsize                text_len,
109                            gpointer             user_data,
110                            GError             **error);
111
112 static void passthrough   (GMarkupParseContext *context,
113                            const gchar         *text,
114                            gsize                text_len,
115                            gpointer             user_data,
116                            GError             **error);
117
118 static void parse_error   (GMarkupParseContext *context,
119                            GError              *error,
120                            gpointer             user_data);
121
122 static const GMarkupParser 
123 mono_parser = {
124         start_element,
125         end_element,
126         parse_text,
127         passthrough,
128         parse_error
129 };
130
131 static GHashTable *config_handlers;
132
133 /* when this interface is stable, export it. */
134 typedef struct MonoParseHandler MonoParseHandler;
135
136 struct MonoParseHandler {
137         const char *element_name;
138         void*(*init)   (MonoImage *assembly);
139         void (*start)  (gpointer user_data, const gchar *name,
140                         const gchar **attributes,
141                         const gchar **values);
142         void (*text)   (gpointer user_data, const char *text, gsize test_len);
143         void (*end)    (gpointer user_data, const char *name);
144         void (*finish) (gpointer user_data);
145 };
146
147 typedef struct {
148         MonoParseHandler *current;
149         void *user_data;
150         MonoImage *assembly;
151         int inited;
152 } ParseState;
153
154 static void start_element (GMarkupParseContext *context, 
155                            const gchar         *element_name,
156                            const gchar        **attribute_names,
157                            const gchar        **attribute_values,
158                            gpointer             user_data,
159                            GError             **error)
160 {
161         ParseState *state = user_data;
162         if (!state->current) {
163                 state->current = g_hash_table_lookup (config_handlers, element_name);
164                 if (state->current && state->current->init)
165                         state->user_data = state->current->init (state->assembly);
166         }
167         if (state->current && state->current->start)
168                 state->current->start (state->user_data, element_name, attribute_names, attribute_values);
169 }
170
171 static void end_element   (GMarkupParseContext *context,
172                            const gchar         *element_name,
173                            gpointer             user_data,
174                            GError             **error)
175 {
176         ParseState *state = user_data;
177         if (state->current) {
178                 if (state->current->end)
179                         state->current->end (state->user_data, element_name);
180                 if (strcmp (state->current->element_name, element_name) == 0) {
181                         if (state->current->finish)
182                                 state->current->finish (state->user_data);
183                         state->current = NULL;
184                         state->user_data = NULL;
185                 }
186         }
187 }
188
189 static void parse_text    (GMarkupParseContext *context,
190                            const gchar         *text,
191                            gsize                text_len,
192                            gpointer             user_data,
193                            GError             **error)
194 {
195         ParseState *state = user_data;
196         if (state->current && state->current->text)
197                 state->current->text (state->user_data, text, text_len);
198 }
199
200 static void passthrough   (GMarkupParseContext *context,
201                            const gchar         *text,
202                            gsize                text_len,
203                            gpointer             user_data,
204                            GError             **error)
205 {
206         /* do nothing */
207 }
208
209 static void parse_error   (GMarkupParseContext *context,
210                            GError              *error,
211                            gpointer             user_data)
212 {
213 }
214
215 static int
216 arch_matches (const char* arch, const char *value)
217 {
218         char **splitted, **p;
219         int found = FALSE;
220         if (value [0] == '!')
221                 return !arch_matches (arch, value + 1);
222         p = splitted = g_strsplit (value, ",", 0);
223         while (*p) {
224                 if (strcmp (arch, *p) == 0) {
225                         found = TRUE;
226                         break;
227                 }
228                 p++;
229         }
230         g_strfreev (splitted);
231         return found;
232 }
233
234 typedef struct {
235         char *dll;
236         char *target;
237         int ignore;
238         MonoImage *assembly;
239 } DllInfo;
240
241 static void*
242 dllmap_init (MonoImage *assembly) {
243         DllInfo *info = g_new0 (DllInfo, 1);
244         info->assembly = assembly;
245         return info;
246 }
247
248 static void
249 dllmap_start (gpointer user_data, 
250               const gchar         *element_name,
251               const gchar        **attribute_names,
252               const gchar        **attribute_values)
253 {
254         int i;
255         DllInfo *info = user_data;
256         
257         if (strcmp (element_name, "dllmap") == 0) {
258                 g_free (info->dll);
259                 g_free (info->target);
260                 info->dll = info->target = NULL;
261                 info->ignore = FALSE;
262                 for (i = 0; attribute_names [i]; ++i) {
263                         if (strcmp (attribute_names [i], "dll") == 0)
264                                 info->dll = g_strdup (attribute_values [i]);
265                         else if (strcmp (attribute_names [i], "target") == 0)
266                                 info->target = g_strdup (attribute_values [i]);
267                         else if (strcmp (attribute_names [i], "os") == 0 && !arch_matches (CONFIG_OS, attribute_values [i]))
268                                 info->ignore = TRUE;
269                         else if (strcmp (attribute_names [i], "cpu") == 0 && !arch_matches (CONFIG_CPU, attribute_values [i]))
270                                 info->ignore = TRUE;
271                         else if (strcmp (attribute_names [i], "wordsize") == 0 && !arch_matches (CONFIG_WORDSIZE, attribute_values [i]))
272                                 info->ignore = TRUE;
273                 }
274                 if (!info->ignore)
275                         mono_dllmap_insert (info->assembly, info->dll, NULL, info->target, NULL);
276         } else if (strcmp (element_name, "dllentry") == 0) {
277                 const char *name = NULL, *target = NULL, *dll = NULL;
278                 int ignore = FALSE;
279                 for (i = 0; attribute_names [i]; ++i) {
280                         if (strcmp (attribute_names [i], "dll") == 0)
281                                 dll = attribute_values [i];
282                         else if (strcmp (attribute_names [i], "target") == 0)
283                                 target = attribute_values [i];
284                         else if (strcmp (attribute_names [i], "name") == 0)
285                                 name = attribute_values [i];
286                         else if (strcmp (attribute_names [i], "os") == 0 && !arch_matches (CONFIG_OS, attribute_values [i]))
287                                 ignore = TRUE;
288                         else if (strcmp (attribute_names [i], "cpu") == 0 && !arch_matches (CONFIG_CPU, attribute_values [i]))
289                                 ignore = TRUE;
290                         else if (strcmp (attribute_names [i], "wordsize") == 0 && !arch_matches (CONFIG_WORDSIZE, attribute_values [i]))
291                                 ignore = TRUE;
292                 }
293                 if (!dll)
294                         dll = info->dll;
295                 if (!info->ignore && !ignore)
296                         mono_dllmap_insert (info->assembly, info->dll, name, dll, target);
297         }
298 }
299
300 static void
301 dllmap_finish (gpointer user_data)
302 {
303         DllInfo *info = user_data;
304
305         g_free (info->dll);
306         g_free (info->target);
307         g_free (info);
308 }
309
310 static const MonoParseHandler
311 dllmap_handler = {
312         "dllmap",
313         dllmap_init,
314         dllmap_start,
315         NULL, /* text */
316         NULL, /* end */
317         dllmap_finish
318 };
319
320 static void
321 legacyUEP_start (gpointer user_data, 
322               const gchar         *element_name,
323               const gchar        **attribute_names,
324               const gchar        **attribute_values) {
325         if ((strcmp (element_name, "legacyUnhandledExceptionPolicy") == 0) &&
326                         (attribute_names [0] != NULL) &&
327                         (strcmp (attribute_names [0], "enabled") == 0)) {
328                 if ((strcmp (attribute_values [0], "1") == 0) ||
329                                 (g_ascii_strcasecmp (attribute_values [0], "true") == 0)) {
330                         mono_runtime_unhandled_exception_policy_set (MONO_UNHANDLED_POLICY_LEGACY);
331                 }
332         }
333 }
334
335 static const MonoParseHandler
336 legacyUEP_handler = {
337         "legacyUnhandledExceptionPolicy",
338         NULL, /* init */
339         legacyUEP_start,
340         NULL, /* text */
341         NULL, /* end */
342         NULL, /* finish */
343 };
344
345 static int inited = 0;
346
347 static void
348 mono_config_init (void)
349 {
350         inited = 1;
351         config_handlers = g_hash_table_new (g_str_hash, g_str_equal);
352         g_hash_table_insert (config_handlers, (gpointer) dllmap_handler.element_name, (gpointer) &dllmap_handler);
353         g_hash_table_insert (config_handlers, (gpointer) legacyUEP_handler.element_name, (gpointer) &legacyUEP_handler);
354 }
355
356 /* FIXME: error handling */
357
358 static void
359 mono_config_parse_xml_with_context (ParseState *state, const char *text, gsize len)
360 {
361         GMarkupParseContext *context;
362
363         if (!inited)
364                 mono_config_init ();
365
366         context = g_markup_parse_context_new (&mono_parser, 0, state, NULL);
367         if (g_markup_parse_context_parse (context, text, len, NULL)) {
368                 g_markup_parse_context_end_parse (context, NULL);
369         }
370         g_markup_parse_context_free (context);
371 }
372
373 /* If assembly is NULL, parse in the global context */
374 static int
375 mono_config_parse_file_with_context (ParseState *state, const char *filename)
376 {
377         char *text;
378         gsize len;
379
380         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_CONFIG,
381                         "Config attempting to parse: '%s'.", filename);
382
383         if (!g_file_get_contents (filename, &text, &len, NULL))
384                 return 0;
385         mono_config_parse_xml_with_context (state, text, len);
386         g_free (text);
387         return 1;
388 }
389
390 /**
391  * mono_config_parse_memory:
392  * @buffer: a pointer to an string XML representation of the configuration
393  *
394  * Parses the configuration from a buffer
395  */
396 void
397 mono_config_parse_memory (const char *buffer)
398 {
399         ParseState state = {NULL};
400         
401         mono_config_parse_xml_with_context (&state, buffer, strlen (buffer));
402 }
403
404 static void
405 mono_config_parse_file (const char *filename)
406 {
407         ParseState state = {NULL};
408         mono_config_parse_file_with_context (&state, filename);
409 }
410
411 /* 
412  * use the equivalent lookup code from the GAC when available.
413  * Depending on state, this should give something like:
414  *      aname/version-pubtoken/
415  *      aname/version/
416  *      aname
417  */
418 static char*
419 get_assembly_filename (MonoImage *image, int state)
420 {
421         switch (state) {
422         case 0:
423                 return g_strdup (mono_image_get_name (image));
424         default:
425                 return NULL;
426         }
427 }
428
429 typedef struct _BundledConfig BundledConfig;
430
431 struct _BundledConfig {
432         BundledConfig *next;
433         const char* aname;
434         const char* config_xml;
435 };
436
437 static BundledConfig *bundled_configs = NULL;
438
439 static const char *bundled_machine_config = NULL;
440
441 void
442 mono_register_config_for_assembly (const char* assembly_name, const char* config_xml)
443 {
444         BundledConfig *bconfig;
445
446         bconfig = g_new0 (BundledConfig, 1);
447         bconfig->aname = assembly_name;
448         bconfig->config_xml = config_xml;
449         bconfig->next = bundled_configs;
450         bundled_configs = bconfig;
451 }
452
453 const char *
454 mono_config_string_for_assembly_file (const char *filename)
455 {
456         BundledConfig *bconfig;
457         
458         for (bconfig = bundled_configs; bconfig; bconfig = bconfig->next) {
459                 if (bconfig->aname && strcmp (bconfig->aname, filename) == 0)
460                         return bconfig->config_xml;
461         }
462         return NULL;
463 }
464
465 void 
466 mono_config_for_assembly (MonoImage *assembly)
467 {
468         ParseState state = {NULL};
469         int got_it = 0, i;
470         char *aname, *cfg, *cfg_name;
471         const char *bundled_config;
472         const char *home;
473         
474         state.assembly = assembly;
475
476         bundled_config = mono_config_string_for_assembly_file (assembly->module_name);
477         if (bundled_config)
478                 mono_config_parse_xml_with_context (&state, bundled_config, strlen (bundled_config));
479
480         cfg_name = g_strdup_printf ("%s.config", mono_image_get_filename (assembly));
481         mono_config_parse_file_with_context (&state, cfg_name);
482         g_free (cfg_name);
483
484         cfg_name = g_strdup_printf ("%s.config", mono_image_get_name (assembly));
485
486         home = g_get_home_dir ();
487
488         for (i = 0; (aname = get_assembly_filename (assembly, i)) != NULL; ++i) {
489                 cfg = g_build_filename (mono_get_config_dir (), "mono", "assemblies", aname, cfg_name, NULL);
490                 got_it += mono_config_parse_file_with_context (&state, cfg);
491                 g_free (cfg);
492
493 #ifndef PLATFORM_WIN32
494                 cfg = g_build_filename (home, ".mono", "assemblies", aname, cfg_name, NULL);
495                 got_it += mono_config_parse_file_with_context (&state, cfg);
496                 g_free (cfg);
497 #endif
498                 g_free (aname);
499                 if (got_it)
500                         break;
501         }
502         g_free (cfg_name);
503 }
504
505 /**
506  * mono_config_parse:
507  * @filename: the filename to load the configuration variables from.
508  *
509  * Pass a NULL filename to parse the default config files
510  * (or the file in the MONO_CONFIG env var).
511  */
512 void
513 mono_config_parse (const char *filename) {
514         const char *home;
515         char *mono_cfg;
516 #ifndef PLATFORM_WIN32
517         char *user_cfg;
518 #endif
519
520         if (filename) {
521                 mono_config_parse_file (filename);
522                 return;
523         }
524
525         home = g_getenv ("MONO_CONFIG");
526         if (home) {
527                 mono_config_parse_file (home);
528                 return;
529         }
530
531         mono_cfg = g_build_filename (mono_get_config_dir (), "mono", "config", NULL);
532         mono_config_parse_file (mono_cfg);
533         g_free (mono_cfg);
534
535 #ifndef PLATFORM_WIN32
536         home = g_get_home_dir ();
537         user_cfg = g_strconcat (home, G_DIR_SEPARATOR_S, ".mono/config", NULL);
538         mono_config_parse_file (user_cfg);
539         g_free (user_cfg);
540 #endif
541 }
542
543 static const char *mono_cfg_dir = NULL;
544
545 /* Invoked during startup */
546 void
547 mono_set_config_dir (const char *dir)
548 {
549         /* If this variable is set, overrides the directory computed */
550         mono_cfg_dir = g_getenv ("MONO_CFG_DIR");
551         if (mono_cfg_dir == NULL)
552                 mono_cfg_dir = g_strdup (dir);
553 }
554
555 const char* 
556 mono_get_config_dir (void)
557 {
558         if (mono_cfg_dir == NULL)
559                 mono_set_dirs (NULL, NULL);
560
561         return mono_cfg_dir;
562 }
563
564 void
565 mono_register_machine_config (const char *config_xml)
566 {
567         bundled_machine_config = config_xml;
568 }
569
570 const char *
571 mono_get_machine_config (void)
572 {
573         return bundled_machine_config;
574 }
575
576 static void
577 publisher_policy_start (gpointer user_data,
578                 const gchar *element_name,
579                 const gchar **attribute_names,
580                 const gchar **attribute_values)
581 {
582         MonoAssemblyBindingInfo *info;
583         int n;
584
585         info = user_data;
586         if (!strcmp (element_name, "assemblyIdentity")) {
587                 for (n = 0; attribute_names [n]; n++) {
588                         const gchar *attribute_name = attribute_names [n];
589                         
590                         if (!strcmp (attribute_name, "name"))
591                                 info->name = g_strdup (attribute_values [n]);
592                         else if (!strcmp (attribute_name, "publicKeyToken")) {
593                                 if (strlen (attribute_values [n]) == MONO_PUBLIC_KEY_TOKEN_LENGTH - 1)
594                                         g_strlcpy ((char *) info->public_key_token, attribute_values [n], MONO_PUBLIC_KEY_TOKEN_LENGTH);
595                         } else if (!strcmp (attribute_name, "culture")) {
596                                 if (!strcmp (attribute_values [n], "neutral"))
597                                         info->culture = g_strdup ("");
598                                 else
599                                         info->culture = g_strdup (attribute_values [n]);
600                         }
601                 }
602         } else if (!strcmp (element_name, "bindingRedirect")) {
603                 for (n = 0; attribute_names [n]; n++) {
604                         const gchar *attribute_name = attribute_names [n];
605
606                         if (!strcmp (attribute_name, "oldVersion")) {
607                                 gchar **numbers, **version, **versions;
608                                 gint major, minor, build, revision;
609
610                                 /* Invalid value */
611                                 if (!strcmp (attribute_values [n], ""))
612                                         return;
613                                 
614                                 versions = g_strsplit (attribute_values [n], "-", 2);
615                                 version = g_strsplit (*versions, ".", 4);
616
617                                 /* We assign the values to gint vars to do the checks */
618                                 numbers = version;
619                                 major = *numbers ? atoi (*numbers++) : -1;
620                                 minor = *numbers ? atoi (*numbers++) : -1;
621                                 build = *numbers ? atoi (*numbers++) : -1;
622                                 revision = *numbers ? atoi (*numbers) : -1;
623                                 g_strfreev (version);
624                                 if (major < 0 || minor < 0 || build < 0 || revision < 0) {
625                                         g_strfreev (versions);
626                                         return;
627                                 }
628
629                                 info->old_version_bottom.major = major;
630                                 info->old_version_bottom.minor = minor;
631                                 info->old_version_bottom.build = build;
632                                 info->old_version_bottom.revision = revision;
633                                 info->has_old_version_bottom = TRUE;
634
635                                 if (!*(versions + 1)) {
636                                         g_strfreev (versions);
637                                         continue;
638                                 }
639                                 
640                                 numbers = version = g_strsplit (*(versions + 1), ".", 4);
641                                 major = *numbers ? atoi (*numbers++) : -1;
642                                 minor = *numbers ? atoi (*numbers++) : -1;
643                                 build = *numbers ? atoi (*numbers++) : -1;
644                                 revision = *numbers ? atoi (*numbers) : 1;
645                                 g_strfreev (version);
646                                 if (major < 0 || minor < 0 || build < 0 || revision < 0) {
647                                         g_strfreev (versions);
648                                         return;
649                                 }
650
651                                 info->old_version_top.major = major;
652                                 info->old_version_top.minor = minor;
653                                 info->old_version_top.build = build;
654                                 info->old_version_top.revision = revision;
655                                 info->has_old_version_top = TRUE;
656
657                                 g_strfreev (versions);
658                         } else if (!strcmp (attribute_name, "newVersion")) {
659                                 gchar **numbers, **version;
660
661                                 /* Invalid value */
662                                 if (!strcmp (attribute_values [n], ""))
663                                         return;
664
665                                 numbers = version = g_strsplit (attribute_values [n], ".", 4);
666                                 info->new_version.major = *numbers ? atoi (*numbers++) : -1;
667                                 info->new_version.minor = *numbers ? atoi (*numbers++) : -1;
668                                 info->new_version.build = *numbers ? atoi (*numbers++) : -1;
669                                 info->new_version.revision = *numbers ? atoi (*numbers) : -1;
670                                 info->has_new_version = TRUE;
671                                 g_strfreev (version);
672                         }
673                 }
674         }
675 }
676
677 static MonoParseHandler
678 publisher_policy_parser = {
679         "", /* We don't need to use declare an xml element */
680         NULL,
681         publisher_policy_start,
682         NULL,
683         NULL,
684         NULL
685 };
686
687 void
688 mono_config_parse_publisher_policy (const gchar *filename, MonoAssemblyBindingInfo *info)
689 {
690         ParseState state = {
691                 &publisher_policy_parser, /* MonoParseHandler */
692                 info, /* user_data */
693                 NULL, /* MonoImage (we don't need it right now)*/
694                 TRUE /* We are already inited */
695         };
696         
697         mono_config_parse_file_with_context (&state, filename);
698 }
699