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