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