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