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