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