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