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