Tizen 2.0 Release
[profile/ivi/osmesa.git] / src / mesa / drivers / dri / common / xmlconfig.c
1 /*
2  * XML DRI client-side driver configuration
3  * Copyright (C) 2003 Felix Kuehling
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included
13  * in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * FELIX KUEHLING, OR ANY OTHER CONTRIBUTORS BE LIABLE FOR ANY CLAIM, 
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
21  * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  * 
23  */
24 /**
25  * \file xmlconfig.c
26  * \brief Driver-independent client-side part of the XML configuration
27  * \author Felix Kuehling
28  */
29
30 #include "main/glheader.h"
31
32 #include <string.h>
33 #include <assert.h>
34 #include <expat.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include "main/imports.h"
39 #include "utils.h"
40 #include "xmlconfig.h"
41
42 #undef GET_PROGRAM_NAME
43
44 #if (defined(__GNU_LIBRARY__) || defined(__GLIBC__)) && !defined(__UCLIBC__)
45 #    if !defined(__GLIBC__) || (__GLIBC__ < 2)
46 /* These aren't declared in any libc5 header */
47 extern char *program_invocation_name, *program_invocation_short_name;
48 #    endif
49 #    define GET_PROGRAM_NAME() program_invocation_short_name
50 #elif defined(__FreeBSD__) && (__FreeBSD__ >= 2)
51 #    include <osreldate.h>
52 #    if (__FreeBSD_version >= 440000)
53 #        include <stdlib.h>
54 #        define GET_PROGRAM_NAME() getprogname()
55 #    endif
56 #elif defined(__NetBSD__) && defined(__NetBSD_Version) && (__NetBSD_Version >= 106000100)
57 #    include <stdlib.h>
58 #    define GET_PROGRAM_NAME() getprogname()
59 #elif defined(__APPLE__)
60 #    include <stdlib.h>
61 #    define GET_PROGRAM_NAME() getprogname()
62 #elif defined(__sun)
63 /* Solaris has getexecname() which returns the full path - return just
64    the basename to match BSD getprogname() */
65 #    include <stdlib.h>
66 #    include <libgen.h>
67
68 static const char *__getProgramName () {
69     static const char *progname;
70
71     if (progname == NULL) {
72         const char *e = getexecname();
73         if (e != NULL) {
74             /* Have to make a copy since getexecname can return a readonly
75                string, but basename expects to be able to modify its arg. */
76             char *n = strdup(e);
77             if (n != NULL) {
78                 progname = basename(n);
79             }
80         }
81     }
82     return progname;
83 }
84
85 #    define GET_PROGRAM_NAME() __getProgramName()
86 #endif
87
88 #if !defined(GET_PROGRAM_NAME)
89 #    if defined(__OpenBSD__) || defined(NetBSD) || defined(__UCLIBC__)
90 /* This is a hack. It's said to work on OpenBSD, NetBSD and GNU.
91  * Rogelio M.Serrano Jr. reported it's also working with UCLIBC. It's
92  * used as a last resort, if there is no documented facility available. */
93 static const char *__getProgramName () {
94     extern const char *__progname;
95     char * arg = strrchr(__progname, '/');
96     if (arg)
97         return arg+1;
98     else
99         return __progname;
100 }
101 #        define GET_PROGRAM_NAME() __getProgramName()
102 #    else
103 #        define GET_PROGRAM_NAME() ""
104 #        warning "Per application configuration won't work with your OS version."
105 #    endif
106 #endif
107
108 /** \brief Find an option in an option cache with the name as key */
109 static GLuint findOption (const driOptionCache *cache, const char *name) {
110     GLuint len = strlen (name);
111     GLuint size = 1 << cache->tableSize, mask = size - 1;
112     GLuint hash = 0;
113     GLuint i, shift;
114
115   /* compute a hash from the variable length name */
116     for (i = 0, shift = 0; i < len; ++i, shift = (shift+8) & 31)
117         hash += (GLuint)name[i] << shift;
118     hash *= hash;
119     hash = (hash >> (16-cache->tableSize/2)) & mask;
120
121   /* this is just the starting point of the linear search for the option */
122     for (i = 0; i < size; ++i, hash = (hash+1) & mask) {
123       /* if we hit an empty entry then the option is not defined (yet) */
124         if (cache->info[hash].name == 0)
125             break;
126         else if (!strcmp (name, cache->info[hash].name))
127             break;
128     }
129   /* this assertion fails if the hash table is full */
130     assert (i < size);
131
132     return hash;
133 }
134
135 /** \brief Count the real number of options in an option cache */
136 static GLuint countOptions (const driOptionCache *cache) {
137     GLuint size = 1 << cache->tableSize;
138     GLuint i, count = 0;
139     for (i = 0; i < size; ++i)
140         if (cache->info[i].name)
141             count++;
142     return count;
143 }
144
145 /** \brief Like strdup but using MALLOC and with error checking. */
146 #define XSTRDUP(dest,source) do { \
147     GLuint len = strlen (source); \
148     if (!(dest = MALLOC (len+1))) { \
149         fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__); \
150         abort(); \
151     } \
152     memcpy (dest, source, len+1); \
153 } while (0)
154
155 static int compare (const void *a, const void *b) {
156     return strcmp (*(char *const*)a, *(char *const*)b);
157 }
158 /** \brief Binary search in a string array. */
159 static GLuint bsearchStr (const XML_Char *name,
160                           const XML_Char *elems[], GLuint count) {
161     const XML_Char **found;
162     found = bsearch (&name, elems, count, sizeof (XML_Char *), compare);
163     if (found)
164         return found - elems;
165     else
166         return count;
167 }
168
169 /** \brief Locale-independent integer parser.
170  *
171  * Works similar to strtol. Leading space is NOT skipped. The input
172  * number may have an optional sign. Radix is specified by base. If
173  * base is 0 then decimal is assumed unless the input number is
174  * prefixed by 0x or 0X for hexadecimal or 0 for octal. After
175  * returning tail points to the first character that is not part of
176  * the integer number. If no number was found then tail points to the
177  * start of the input string. */
178 static GLint strToI (const XML_Char *string, const XML_Char **tail, int base) {
179     GLint radix = base == 0 ? 10 : base;
180     GLint result = 0;
181     GLint sign = 1;
182     GLboolean numberFound = GL_FALSE;
183     const XML_Char *start = string;
184
185     assert (radix >= 2 && radix <= 36);
186
187     if (*string == '-') {
188         sign = -1;
189         string++;
190     } else if (*string == '+')
191         string++;
192     if (base == 0 && *string == '0') {
193         numberFound = GL_TRUE; 
194         if (*(string+1) == 'x' || *(string+1) == 'X') {
195             radix = 16;
196             string += 2;
197         } else {
198             radix = 8;
199             string++;
200         }
201     }
202     do {
203         GLint digit = -1;
204         if (radix <= 10) {
205             if (*string >= '0' && *string < '0' + radix)
206                 digit = *string - '0';
207         } else {
208             if (*string >= '0' && *string <= '9')
209                 digit = *string - '0';
210             else if (*string >= 'a' && *string < 'a' + radix - 10)
211                 digit = *string - 'a' + 10;
212             else if (*string >= 'A' && *string < 'A' + radix - 10)
213                 digit = *string - 'A' + 10;
214         }
215         if (digit != -1) {
216             numberFound = GL_TRUE;
217             result = radix*result + digit;
218             string++;
219         } else
220             break;
221     } while (GL_TRUE);
222     *tail = numberFound ? string : start;
223     return sign * result;
224 }
225
226 /** \brief Locale-independent floating-point parser.
227  *
228  * Works similar to strtod. Leading space is NOT skipped. The input
229  * number may have an optional sign. '.' is interpreted as decimal
230  * point and may occur at most once. Optionally the number may end in
231  * [eE]<exponent>, where <exponent> is an integer as recognized by
232  * strToI. In that case the result is number * 10^exponent. After
233  * returning tail points to the first character that is not part of
234  * the floating point number. If no number was found then tail points
235  * to the start of the input string.
236  *
237  * Uses two passes for maximum accuracy. */
238 static GLfloat strToF (const XML_Char *string, const XML_Char **tail) {
239     GLint nDigits = 0, pointPos, exponent;
240     GLfloat sign = 1.0f, result = 0.0f, scale;
241     const XML_Char *start = string, *numStart;
242
243     /* sign */
244     if (*string == '-') {
245         sign = -1.0f;
246         string++;
247     } else if (*string == '+')
248         string++;
249
250     /* first pass: determine position of decimal point, number of
251      * digits, exponent and the end of the number. */
252     numStart = string;
253     while (*string >= '0' && *string <= '9') {
254         string++;
255         nDigits++;
256     }
257     pointPos = nDigits;
258     if (*string == '.') {
259         string++;
260         while (*string >= '0' && *string <= '9') {
261             string++;
262             nDigits++;
263         }
264     }
265     if (nDigits == 0) {
266         /* no digits, no number */
267         *tail = start;
268         return 0.0f;
269     }
270     *tail = string;
271     if (*string == 'e' || *string == 'E') {
272         const XML_Char *expTail;
273         exponent = strToI (string+1, &expTail, 10);
274         if (expTail == string+1)
275             exponent = 0;
276         else
277             *tail = expTail;
278     } else
279         exponent = 0;
280     string = numStart;
281
282     /* scale of the first digit */
283     scale = sign * (GLfloat)pow (10.0, (GLdouble)(pointPos-1 + exponent));
284
285     /* second pass: parse digits */
286     do {
287         if (*string != '.') {
288             assert (*string >= '0' && *string <= '9');
289             result += scale * (GLfloat)(*string - '0');
290             scale *= 0.1f;
291             nDigits--;
292         }
293         string++;
294     } while (nDigits > 0);
295
296     return result;
297 }
298
299 /** \brief Parse a value of a given type. */
300 static GLboolean parseValue (driOptionValue *v, driOptionType type,
301                              const XML_Char *string) {
302     const XML_Char *tail = NULL;
303   /* skip leading white-space */
304     string += strspn (string, " \f\n\r\t\v");
305     switch (type) {
306       case DRI_BOOL:
307         if (!strcmp (string, "false")) {
308             v->_bool = GL_FALSE;
309             tail = string + 5;
310         } else if (!strcmp (string, "true")) {
311             v->_bool = GL_TRUE;
312             tail = string + 4;
313         }
314         else
315             return GL_FALSE;
316         break;
317       case DRI_ENUM: /* enum is just a special integer */
318       case DRI_INT:
319         v->_int = strToI (string, &tail, 0);
320         break;
321       case DRI_FLOAT:
322         v->_float = strToF (string, &tail);
323         break;
324     }
325
326     if (tail == string)
327         return GL_FALSE; /* empty string (or containing only white-space) */
328   /* skip trailing white space */
329     if (*tail)
330         tail += strspn (tail, " \f\n\r\t\v");
331     if (*tail)
332         return GL_FALSE; /* something left over that is not part of value */
333
334     return GL_TRUE;
335 }
336
337 /** \brief Parse a list of ranges of type info->type. */
338 static GLboolean parseRanges (driOptionInfo *info, const XML_Char *string) {
339     XML_Char *cp, *range;
340     GLuint nRanges, i;
341     driOptionRange *ranges;
342
343     XSTRDUP (cp, string);
344   /* pass 1: determine the number of ranges (number of commas + 1) */
345     range = cp;
346     for (nRanges = 1; *range; ++range)
347         if (*range == ',')
348             ++nRanges;
349
350     if ((ranges = MALLOC (nRanges*sizeof(driOptionRange))) == NULL) {
351         fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
352         abort();
353     }
354
355   /* pass 2: parse all ranges into preallocated array */
356     range = cp;
357     for (i = 0; i < nRanges; ++i) {
358         XML_Char *end, *sep;
359         assert (range);
360         end = strchr (range, ',');
361         if (end)
362             *end = '\0';
363         sep = strchr (range, ':');
364         if (sep) { /* non-empty interval */
365             *sep = '\0';
366             if (!parseValue (&ranges[i].start, info->type, range) ||
367                 !parseValue (&ranges[i].end, info->type, sep+1))
368                 break;
369             if (info->type == DRI_INT &&
370                 ranges[i].start._int > ranges[i].end._int)
371                 break;
372             if (info->type == DRI_FLOAT &&
373                 ranges[i].start._float > ranges[i].end._float)
374                 break;
375         } else { /* empty interval */
376             if (!parseValue (&ranges[i].start, info->type, range))
377                 break;
378             ranges[i].end = ranges[i].start;
379         }
380         if (end)
381             range = end+1;
382         else
383             range = NULL;
384     }
385     FREE (cp);
386     if (i < nRanges) {
387         FREE (ranges);
388         return GL_FALSE;
389     } else
390         assert (range == NULL);
391
392     info->nRanges = nRanges;
393     info->ranges = ranges;
394     return GL_TRUE;
395 }
396
397 /** \brief Check if a value is in one of info->ranges. */
398 static GLboolean checkValue (const driOptionValue *v, const driOptionInfo *info) {
399     GLuint i;
400     assert (info->type != DRI_BOOL); /* should be caught by the parser */
401     if (info->nRanges == 0)
402         return GL_TRUE;
403     switch (info->type) {
404       case DRI_ENUM: /* enum is just a special integer */
405       case DRI_INT:
406         for (i = 0; i < info->nRanges; ++i)
407             if (v->_int >= info->ranges[i].start._int &&
408                 v->_int <= info->ranges[i].end._int)
409                 return GL_TRUE;
410         break;
411       case DRI_FLOAT:
412         for (i = 0; i < info->nRanges; ++i)
413             if (v->_float >= info->ranges[i].start._float &&
414                 v->_float <= info->ranges[i].end._float)
415                 return GL_TRUE;
416         break;
417       default:
418         assert (0); /* should never happen */
419     }
420     return GL_FALSE;
421 }
422
423 /** \brief Output a warning message. */
424 #define XML_WARNING1(msg) do {\
425     __driUtilMessage ("Warning in %s line %d, column %d: "msg, data->name, \
426                       (int) XML_GetCurrentLineNumber(data->parser), \
427                       (int) XML_GetCurrentColumnNumber(data->parser)); \
428 } while (0)
429 #define XML_WARNING(msg,args...) do { \
430     __driUtilMessage ("Warning in %s line %d, column %d: "msg, data->name, \
431                       (int) XML_GetCurrentLineNumber(data->parser), \
432                       (int) XML_GetCurrentColumnNumber(data->parser), \
433                       args); \
434 } while (0)
435 /** \brief Output an error message. */
436 #define XML_ERROR1(msg) do { \
437     __driUtilMessage ("Error in %s line %d, column %d: "msg, data->name, \
438                       (int) XML_GetCurrentLineNumber(data->parser), \
439                       (int) XML_GetCurrentColumnNumber(data->parser)); \
440 } while (0)
441 #define XML_ERROR(msg,args...) do { \
442     __driUtilMessage ("Error in %s line %d, column %d: "msg, data->name, \
443                       (int) XML_GetCurrentLineNumber(data->parser), \
444                       (int) XML_GetCurrentColumnNumber(data->parser), \
445                       args); \
446 } while (0)
447 /** \brief Output a fatal error message and abort. */
448 #define XML_FATAL1(msg) do { \
449     fprintf (stderr, "Fatal error in %s line %d, column %d: "msg"\n", \
450              data->name, \
451              (int) XML_GetCurrentLineNumber(data->parser),      \
452              (int) XML_GetCurrentColumnNumber(data->parser)); \
453     abort();\
454 } while (0)
455 #define XML_FATAL(msg,args...) do { \
456     fprintf (stderr, "Fatal error in %s line %d, column %d: "msg"\n", \
457              data->name, \
458              (int) XML_GetCurrentLineNumber(data->parser),      \
459              (int) XML_GetCurrentColumnNumber(data->parser),            \
460              args); \
461     abort();\
462 } while (0)
463
464 /** \brief Parser context for __driConfigOptions. */
465 struct OptInfoData {
466     const char *name;
467     XML_Parser parser;
468     driOptionCache *cache;
469     GLboolean inDriInfo;
470     GLboolean inSection;
471     GLboolean inDesc;
472     GLboolean inOption;
473     GLboolean inEnum;
474     int curOption;
475 };
476
477 /** \brief Elements in __driConfigOptions. */
478 enum OptInfoElem {
479     OI_DESCRIPTION = 0, OI_DRIINFO, OI_ENUM, OI_OPTION, OI_SECTION, OI_COUNT
480 };
481 static const XML_Char *OptInfoElems[] = {
482     "description", "driinfo", "enum", "option", "section"
483 };
484
485 /** \brief Parse attributes of an enum element.
486  *
487  * We're not actually interested in the data. Just make sure this is ok
488  * for external configuration tools.
489  */
490 static void parseEnumAttr (struct OptInfoData *data, const XML_Char **attr) {
491     GLuint i;
492     const XML_Char *value = NULL, *text = NULL;
493     driOptionValue v;
494     GLuint opt = data->curOption;
495     for (i = 0; attr[i]; i += 2) {
496         if (!strcmp (attr[i], "value")) value = attr[i+1];
497         else if (!strcmp (attr[i], "text")) text = attr[i+1];
498         else XML_FATAL("illegal enum attribute: %s.", attr[i]);
499     }
500     if (!value) XML_FATAL1 ("value attribute missing in enum.");
501     if (!text) XML_FATAL1 ("text attribute missing in enum.");
502      if (!parseValue (&v, data->cache->info[opt].type, value))
503         XML_FATAL ("illegal enum value: %s.", value);
504     if (!checkValue (&v, &data->cache->info[opt]))
505         XML_FATAL ("enum value out of valid range: %s.", value);
506 }
507
508 /** \brief Parse attributes of a description element.
509  *
510  * We're not actually interested in the data. Just make sure this is ok
511  * for external configuration tools.
512  */
513 static void parseDescAttr (struct OptInfoData *data, const XML_Char **attr) {
514     GLuint i;
515     const XML_Char *lang = NULL, *text = NULL;
516     for (i = 0; attr[i]; i += 2) {
517         if (!strcmp (attr[i], "lang")) lang = attr[i+1];
518         else if (!strcmp (attr[i], "text")) text = attr[i+1];
519         else XML_FATAL("illegal description attribute: %s.", attr[i]);
520     }
521     if (!lang) XML_FATAL1 ("lang attribute missing in description.");
522     if (!text) XML_FATAL1 ("text attribute missing in description.");
523 }
524
525 /** \brief Parse attributes of an option element. */
526 static void parseOptInfoAttr (struct OptInfoData *data, const XML_Char **attr) {
527     enum OptAttr {OA_DEFAULT = 0, OA_NAME, OA_TYPE, OA_VALID, OA_COUNT};
528     static const XML_Char *optAttr[] = {"default", "name", "type", "valid"};
529     const XML_Char *attrVal[OA_COUNT] = {NULL, NULL, NULL, NULL};
530     const char *defaultVal;
531     driOptionCache *cache = data->cache;
532     GLuint opt, i;
533     for (i = 0; attr[i]; i += 2) {
534         GLuint attrName = bsearchStr (attr[i], optAttr, OA_COUNT);
535         if (attrName >= OA_COUNT)
536             XML_FATAL ("illegal option attribute: %s", attr[i]);
537         attrVal[attrName] = attr[i+1];
538     }
539     if (!attrVal[OA_NAME]) XML_FATAL1 ("name attribute missing in option.");
540     if (!attrVal[OA_TYPE]) XML_FATAL1 ("type attribute missing in option.");
541     if (!attrVal[OA_DEFAULT]) XML_FATAL1 ("default attribute missing in option.");
542
543     opt = findOption (cache, attrVal[OA_NAME]);
544     if (cache->info[opt].name)
545         XML_FATAL ("option %s redefined.", attrVal[OA_NAME]);
546     data->curOption = opt;
547
548     XSTRDUP (cache->info[opt].name, attrVal[OA_NAME]);
549
550     if (!strcmp (attrVal[OA_TYPE], "bool"))
551         cache->info[opt].type = DRI_BOOL;
552     else if (!strcmp (attrVal[OA_TYPE], "enum"))
553         cache->info[opt].type = DRI_ENUM;
554     else if (!strcmp (attrVal[OA_TYPE], "int"))
555         cache->info[opt].type = DRI_INT;
556     else if (!strcmp (attrVal[OA_TYPE], "float"))
557         cache->info[opt].type = DRI_FLOAT;
558     else
559         XML_FATAL ("illegal type in option: %s.", attrVal[OA_TYPE]);
560
561     defaultVal = getenv (cache->info[opt].name);
562     if (defaultVal != NULL) {
563       /* don't use XML_WARNING, we want the user to see this! */
564         fprintf (stderr,
565                  "ATTENTION: default value of option %s overridden by environment.\n",
566                  cache->info[opt].name);
567     } else
568         defaultVal = attrVal[OA_DEFAULT];
569     if (!parseValue (&cache->values[opt], cache->info[opt].type, defaultVal))
570         XML_FATAL ("illegal default value: %s.", defaultVal);
571
572     if (attrVal[OA_VALID]) {
573         if (cache->info[opt].type == DRI_BOOL)
574             XML_FATAL1 ("boolean option with valid attribute.");
575         if (!parseRanges (&cache->info[opt], attrVal[OA_VALID]))
576             XML_FATAL ("illegal valid attribute: %s.", attrVal[OA_VALID]);
577         if (!checkValue (&cache->values[opt], &cache->info[opt]))
578             XML_FATAL ("default value out of valid range '%s': %s.",
579                        attrVal[OA_VALID], defaultVal);
580     } else if (cache->info[opt].type == DRI_ENUM) {
581         XML_FATAL1 ("valid attribute missing in option (mandatory for enums).");
582     } else {
583         cache->info[opt].nRanges = 0;
584         cache->info[opt].ranges = NULL;
585     }
586 }
587
588 /** \brief Handler for start element events. */
589 static void optInfoStartElem (void *userData, const XML_Char *name,
590                               const XML_Char **attr) {
591     struct OptInfoData *data = (struct OptInfoData *)userData;
592     enum OptInfoElem elem = bsearchStr (name, OptInfoElems, OI_COUNT);
593     switch (elem) {
594       case OI_DRIINFO:
595         if (data->inDriInfo)
596             XML_FATAL1 ("nested <driinfo> elements.");
597         if (attr[0])
598             XML_FATAL1 ("attributes specified on <driinfo> element.");
599         data->inDriInfo = GL_TRUE;
600         break;
601       case OI_SECTION:
602         if (!data->inDriInfo)
603             XML_FATAL1 ("<section> must be inside <driinfo>.");
604         if (data->inSection)
605             XML_FATAL1 ("nested <section> elements.");
606         if (attr[0])
607             XML_FATAL1 ("attributes specified on <section> element.");
608         data->inSection = GL_TRUE;
609         break;
610       case OI_DESCRIPTION:
611         if (!data->inSection && !data->inOption)
612             XML_FATAL1 ("<description> must be inside <description> or <option.");
613         if (data->inDesc)
614             XML_FATAL1 ("nested <description> elements.");
615         data->inDesc = GL_TRUE;
616         parseDescAttr (data, attr);
617         break;
618       case OI_OPTION:
619         if (!data->inSection)
620             XML_FATAL1 ("<option> must be inside <section>.");
621         if (data->inDesc)
622             XML_FATAL1 ("<option> nested in <description> element.");
623         if (data->inOption)
624             XML_FATAL1 ("nested <option> elements.");
625         data->inOption = GL_TRUE;
626         parseOptInfoAttr (data, attr);
627         break;
628       case OI_ENUM:
629         if (!(data->inOption && data->inDesc))
630             XML_FATAL1 ("<enum> must be inside <option> and <description>.");
631         if (data->inEnum)
632             XML_FATAL1 ("nested <enum> elements.");
633         data->inEnum = GL_TRUE;
634         parseEnumAttr (data, attr);
635         break;
636       default:
637         XML_FATAL ("unknown element: %s.", name);
638     }
639 }
640
641 /** \brief Handler for end element events. */
642 static void optInfoEndElem (void *userData, const XML_Char *name) {
643     struct OptInfoData *data = (struct OptInfoData *)userData;
644     enum OptInfoElem elem = bsearchStr (name, OptInfoElems, OI_COUNT);
645     switch (elem) {
646       case OI_DRIINFO:
647         data->inDriInfo = GL_FALSE;
648         break;
649       case OI_SECTION:
650         data->inSection = GL_FALSE;
651         break;
652       case OI_DESCRIPTION:
653         data->inDesc = GL_FALSE;
654         break;
655       case OI_OPTION:
656         data->inOption = GL_FALSE;
657         break;
658       case OI_ENUM:
659         data->inEnum = GL_FALSE;
660         break;
661       default:
662         assert (0); /* should have been caught by StartElem */
663     }
664 }
665
666 void driParseOptionInfo (driOptionCache *info,
667                          const char *configOptions, GLuint nConfigOptions) {
668     XML_Parser p;
669     int status;
670     struct OptInfoData userData;
671     struct OptInfoData *data = &userData;
672     GLuint realNoptions;
673
674   /* determine hash table size and allocate memory:
675    * 3/2 of the number of options, rounded up, so there remains always
676    * at least one free entry. This is needed for detecting undefined
677    * options in configuration files without getting a hash table overflow.
678    * Round this up to a power of two. */
679     GLuint minSize = (nConfigOptions*3 + 1) / 2;
680     GLuint size, log2size;
681     for (size = 1, log2size = 0; size < minSize; size <<= 1, ++log2size);
682     info->tableSize = log2size;
683     info->info = CALLOC (size * sizeof (driOptionInfo));
684     info->values = CALLOC (size * sizeof (driOptionValue));
685     if (info->info == NULL || info->values == NULL) {
686         fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
687         abort();
688     }
689
690     p = XML_ParserCreate ("UTF-8"); /* always UTF-8 */
691     XML_SetElementHandler (p, optInfoStartElem, optInfoEndElem);
692     XML_SetUserData (p, data);
693
694     userData.name = "__driConfigOptions";
695     userData.parser = p;
696     userData.cache = info;
697     userData.inDriInfo = GL_FALSE;
698     userData.inSection = GL_FALSE;
699     userData.inDesc = GL_FALSE;
700     userData.inOption = GL_FALSE;
701     userData.inEnum = GL_FALSE;
702     userData.curOption = -1;
703
704     status = XML_Parse (p, configOptions, strlen (configOptions), 1);
705     if (!status)
706         XML_FATAL ("%s.", XML_ErrorString(XML_GetErrorCode(p)));
707
708     XML_ParserFree (p);
709
710   /* Check if the actual number of options matches nConfigOptions.
711    * A mismatch is not fatal (a hash table overflow would be) but we
712    * want the driver developer's attention anyway. */
713     realNoptions = countOptions (info);
714     if (realNoptions != nConfigOptions) {
715         fprintf (stderr,
716                  "Error: nConfigOptions (%u) does not match the actual number of options in\n"
717                  "       __driConfigOptions (%u).\n",
718                  nConfigOptions, realNoptions);
719     }
720 }
721
722 /** \brief Parser context for configuration files. */
723 struct OptConfData {
724     const char *name;
725     XML_Parser parser;
726     driOptionCache *cache;
727     GLint screenNum;
728     const char *driverName, *execName;
729     GLuint ignoringDevice;
730     GLuint ignoringApp;
731     GLuint inDriConf;
732     GLuint inDevice;
733     GLuint inApp;
734     GLuint inOption;
735 };
736
737 /** \brief Elements in configuration files. */
738 enum OptConfElem {
739     OC_APPLICATION = 0, OC_DEVICE, OC_DRICONF, OC_OPTION, OC_COUNT
740 };
741 static const XML_Char *OptConfElems[] = {
742     "application", "device", "driconf", "option"
743 };
744
745 /** \brief Parse attributes of a device element. */
746 static void parseDeviceAttr (struct OptConfData *data, const XML_Char **attr) {
747     GLuint i;
748     const XML_Char *driver = NULL, *screen = NULL;
749     for (i = 0; attr[i]; i += 2) {
750         if (!strcmp (attr[i], "driver")) driver = attr[i+1];
751         else if (!strcmp (attr[i], "screen")) screen = attr[i+1];
752         else XML_WARNING("unknown device attribute: %s.", attr[i]);
753     }
754     if (driver && strcmp (driver, data->driverName))
755         data->ignoringDevice = data->inDevice;
756     else if (screen) {
757         driOptionValue screenNum;
758         if (!parseValue (&screenNum, DRI_INT, screen))
759             XML_WARNING("illegal screen number: %s.", screen);
760         else if (screenNum._int != data->screenNum)
761             data->ignoringDevice = data->inDevice;
762     }
763 }
764
765 /** \brief Parse attributes of an application element. */
766 static void parseAppAttr (struct OptConfData *data, const XML_Char **attr) {
767     GLuint i;
768     const XML_Char *name = NULL, *exec = NULL;
769     for (i = 0; attr[i]; i += 2) {
770         if (!strcmp (attr[i], "name")) name = attr[i+1];
771         else if (!strcmp (attr[i], "executable")) exec = attr[i+1];
772         else XML_WARNING("unknown application attribute: %s.", attr[i]);
773     }
774     if (exec && strcmp (exec, data->execName))
775         data->ignoringApp = data->inApp;
776 }
777
778 /** \brief Parse attributes of an option element. */
779 static void parseOptConfAttr (struct OptConfData *data, const XML_Char **attr) {
780     GLuint i;
781     const XML_Char *name = NULL, *value = NULL;
782     for (i = 0; attr[i]; i += 2) {
783         if (!strcmp (attr[i], "name")) name = attr[i+1];
784         else if (!strcmp (attr[i], "value")) value = attr[i+1];
785         else XML_WARNING("unknown option attribute: %s.", attr[i]);
786     }
787     if (!name) XML_WARNING1 ("name attribute missing in option.");
788     if (!value) XML_WARNING1 ("value attribute missing in option.");
789     if (name && value) {
790         driOptionCache *cache = data->cache;
791         GLuint opt = findOption (cache, name);
792         if (cache->info[opt].name == NULL)
793             XML_WARNING ("undefined option: %s.", name);
794         else if (getenv (cache->info[opt].name))
795           /* don't use XML_WARNING, we want the user to see this! */
796             fprintf (stderr, "ATTENTION: option value of option %s ignored.\n",
797                      cache->info[opt].name);
798         else if (!parseValue (&cache->values[opt], cache->info[opt].type, value))
799             XML_WARNING ("illegal option value: %s.", value);
800     }
801 }
802
803 /** \brief Handler for start element events. */
804 static void optConfStartElem (void *userData, const XML_Char *name,
805                               const XML_Char **attr) {
806     struct OptConfData *data = (struct OptConfData *)userData;
807     enum OptConfElem elem = bsearchStr (name, OptConfElems, OC_COUNT);
808     switch (elem) {
809       case OC_DRICONF:
810         if (data->inDriConf)
811             XML_WARNING1 ("nested <driconf> elements.");
812         if (attr[0])
813             XML_WARNING1 ("attributes specified on <driconf> element.");
814         data->inDriConf++;
815         break;
816       case OC_DEVICE:
817         if (!data->inDriConf)
818             XML_WARNING1 ("<device> should be inside <driconf>.");
819         if (data->inDevice)
820             XML_WARNING1 ("nested <device> elements.");
821         data->inDevice++;
822         if (!data->ignoringDevice && !data->ignoringApp)
823             parseDeviceAttr (data, attr);
824         break;
825       case OC_APPLICATION:
826         if (!data->inDevice)
827             XML_WARNING1 ("<application> should be inside <device>.");
828         if (data->inApp)
829             XML_WARNING1 ("nested <application> elements.");
830         data->inApp++;
831         if (!data->ignoringDevice && !data->ignoringApp)
832             parseAppAttr (data, attr);
833         break;
834       case OC_OPTION:
835         if (!data->inApp)
836             XML_WARNING1 ("<option> should be inside <application>.");
837         if (data->inOption)
838             XML_WARNING1 ("nested <option> elements.");
839         data->inOption++;
840         if (!data->ignoringDevice && !data->ignoringApp)
841             parseOptConfAttr (data, attr);
842         break;
843       default:
844         XML_WARNING ("unknown element: %s.", name);
845     }
846 }
847
848 /** \brief Handler for end element events. */
849 static void optConfEndElem (void *userData, const XML_Char *name) {
850     struct OptConfData *data = (struct OptConfData *)userData;
851     enum OptConfElem elem = bsearchStr (name, OptConfElems, OC_COUNT);
852     switch (elem) {
853       case OC_DRICONF:
854         data->inDriConf--;
855         break;
856       case OC_DEVICE:
857         if (data->inDevice-- == data->ignoringDevice)
858             data->ignoringDevice = 0;
859         break;
860       case OC_APPLICATION:
861         if (data->inApp-- == data->ignoringApp)
862             data->ignoringApp = 0;
863         break;
864       case OC_OPTION:
865         data->inOption--;
866         break;
867       default:
868         /* unknown element, warning was produced on start tag */;
869     }
870 }
871
872 /** \brief Initialize an option cache based on info */
873 static void initOptionCache (driOptionCache *cache, const driOptionCache *info) {
874     cache->info = info->info;
875     cache->tableSize = info->tableSize;
876     cache->values = MALLOC ((1<<info->tableSize) * sizeof (driOptionValue));
877     if (cache->values == NULL) {
878         fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
879         abort();
880     }
881     memcpy (cache->values, info->values,
882             (1<<info->tableSize) * sizeof (driOptionValue));
883 }
884
885 /** \brief Parse the named configuration file */
886 static void parseOneConfigFile (XML_Parser p) {
887 #define BUF_SIZE 0x1000
888     struct OptConfData *data = (struct OptConfData *)XML_GetUserData (p);
889     int status;
890     int fd;
891
892     if ((fd = open (data->name, O_RDONLY)) == -1) {
893         __driUtilMessage ("Can't open configuration file %s: %s.",
894                           data->name, strerror (errno));
895         return;
896     }
897
898     while (1) {
899         int bytesRead;
900         void *buffer = XML_GetBuffer (p, BUF_SIZE);
901         if (!buffer) {
902             __driUtilMessage ("Can't allocate parser buffer.");
903             break;
904         }
905         bytesRead = read (fd, buffer, BUF_SIZE);
906         if (bytesRead == -1) {
907             __driUtilMessage ("Error reading from configuration file %s: %s.",
908                               data->name, strerror (errno));
909             break;
910         }
911         status = XML_ParseBuffer (p, bytesRead, bytesRead == 0);
912         if (!status) {
913             XML_ERROR ("%s.", XML_ErrorString(XML_GetErrorCode(p)));
914             break;
915         }
916         if (bytesRead == 0)
917             break;
918     }
919
920     close (fd);
921 #undef BUF_SIZE
922 }
923
924 void driParseConfigFiles (driOptionCache *cache, const driOptionCache *info,
925                           GLint screenNum, const char *driverName) {
926     char *filenames[2] = {"/etc/drirc", NULL};
927     char *home;
928     GLuint i;
929     struct OptConfData userData;
930
931     initOptionCache (cache, info);
932
933     userData.cache = cache;
934     userData.screenNum = screenNum;
935     userData.driverName = driverName;
936     userData.execName = GET_PROGRAM_NAME();
937
938     if ((home = getenv ("HOME"))) {
939         GLuint len = strlen (home);
940         filenames[1] = MALLOC (len + 7+1);
941         if (filenames[1] == NULL)
942             __driUtilMessage ("Can't allocate memory for %s/.drirc.", home);
943         else {
944             memcpy (filenames[1], home, len);
945             memcpy (filenames[1] + len, "/.drirc", 7+1);
946         }
947     }
948
949     for (i = 0; i < 2; ++i) {
950         XML_Parser p;
951         if (filenames[i] == NULL)
952             continue;
953
954         p = XML_ParserCreate (NULL); /* use encoding specified by file */
955         XML_SetElementHandler (p, optConfStartElem, optConfEndElem);
956         XML_SetUserData (p, &userData);
957         userData.parser = p;
958         userData.name = filenames[i];
959         userData.ignoringDevice = 0;
960         userData.ignoringApp = 0;
961         userData.inDriConf = 0;
962         userData.inDevice = 0;
963         userData.inApp = 0;
964         userData.inOption = 0;
965
966         parseOneConfigFile (p);
967         XML_ParserFree (p);
968     }
969
970     if (filenames[1])
971         FREE (filenames[1]);
972 }
973
974 void driDestroyOptionInfo (driOptionCache *info) {
975     driDestroyOptionCache (info);
976     if (info->info) {
977         GLuint i, size = 1 << info->tableSize;
978         for (i = 0; i < size; ++i) {
979             if (info->info[i].name) {
980                 FREE (info->info[i].name);
981                 if (info->info[i].ranges)
982                     FREE (info->info[i].ranges);
983             }
984         }
985         FREE (info->info);
986     }
987 }
988
989 void driDestroyOptionCache (driOptionCache *cache) {
990     if (cache->values)
991         FREE (cache->values);
992 }
993
994 GLboolean driCheckOption (const driOptionCache *cache, const char *name,
995                           driOptionType type) {
996     GLuint i = findOption (cache, name);
997     return cache->info[i].name != NULL && cache->info[i].type == type;
998 }
999
1000 GLboolean driQueryOptionb (const driOptionCache *cache, const char *name) {
1001     GLuint i = findOption (cache, name);
1002   /* make sure the option is defined and has the correct type */
1003     assert (cache->info[i].name != NULL);
1004     assert (cache->info[i].type == DRI_BOOL);
1005     return cache->values[i]._bool;
1006 }
1007
1008 GLint driQueryOptioni (const driOptionCache *cache, const char *name) {
1009     GLuint i = findOption (cache, name);
1010   /* make sure the option is defined and has the correct type */
1011     assert (cache->info[i].name != NULL);
1012     assert (cache->info[i].type == DRI_INT || cache->info[i].type == DRI_ENUM);
1013     return cache->values[i]._int;
1014 }
1015
1016 GLfloat driQueryOptionf (const driOptionCache *cache, const char *name) {
1017     GLuint i = findOption (cache, name);
1018   /* make sure the option is defined and has the correct type */
1019     assert (cache->info[i].name != NULL);
1020     assert (cache->info[i].type == DRI_FLOAT);
1021     return cache->values[i]._float;
1022 }