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