android: util: fix missing include path
[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 const char *applicationName;
719 uint32_t engineVersion;
720 uint32_t applicationVersion;
721 uint32_t ignoringDevice;
722 uint32_t ignoringApp;
723 uint32_t inDriConf;
724 uint32_t inDevice;
725 uint32_t inApp;
726 uint32_t inOption;
727 };
728
729 /** \brief Elements in configuration files. */
730 enum OptConfElem {
731 OC_APPLICATION = 0, OC_DEVICE, OC_DRICONF, OC_ENGINE, OC_OPTION, OC_COUNT
732 };
733 static const XML_Char *OptConfElems[] = {
734 [OC_APPLICATION] = "application",
735 [OC_DEVICE] = "device",
736 [OC_DRICONF] = "driconf",
737 [OC_ENGINE] = "engine",
738 [OC_OPTION] = "option",
739 };
740
741 /** \brief Parse attributes of a device element. */
742 static void
743 parseDeviceAttr(struct OptConfData *data, const XML_Char **attr)
744 {
745 uint32_t i;
746 const XML_Char *driver = NULL, *screen = NULL, *kernel = NULL;
747 for (i = 0; attr[i]; i += 2) {
748 if (!strcmp (attr[i], "driver")) driver = attr[i+1];
749 else if (!strcmp (attr[i], "screen")) screen = attr[i+1];
750 else if (!strcmp (attr[i], "kernel_driver")) kernel = attr[i+1];
751 else XML_WARNING("unknown device attribute: %s.", attr[i]);
752 }
753 if (driver && strcmp (driver, data->driverName))
754 data->ignoringDevice = data->inDevice;
755 else if (kernel && (!data->kernelDriverName || strcmp (kernel, data->kernelDriverName)))
756 data->ignoringDevice = data->inDevice;
757 else if (screen) {
758 driOptionValue screenNum;
759 if (!parseValue (&screenNum, DRI_INT, screen))
760 XML_WARNING("illegal screen number: %s.", screen);
761 else if (screenNum._int != data->screenNum)
762 data->ignoringDevice = data->inDevice;
763 }
764 }
765
766 static bool
767 valueInRanges(const driOptionInfo *info, uint32_t value)
768 {
769 uint32_t i;
770
771 for (i = 0; i < info->nRanges; i++) {
772 if (info->ranges[i].start._int <= value &&
773 info->ranges[i].end._int >= value)
774 return true;
775 }
776
777 return false;
778 }
779
780 /** \brief Parse attributes of an application element. */
781 static void
782 parseAppAttr(struct OptConfData *data, const XML_Char **attr)
783 {
784 uint32_t i;
785 const XML_Char *exec = NULL;
786 const XML_Char *sha1 = NULL;
787 const XML_Char *application_name_match = NULL;
788 const XML_Char *application_versions = NULL;
789 driOptionInfo version_ranges = {
790 .type = DRI_INT,
791 };
792
793 for (i = 0; attr[i]; i += 2) {
794 if (!strcmp (attr[i], "name")) /* not needed here */;
795 else if (!strcmp (attr[i], "executable")) exec = attr[i+1];
796 else if (!strcmp (attr[i], "sha1")) sha1 = attr[i+1];
797 else if (!strcmp (attr[i], "application_name_match"))
798 application_name_match = attr[i+1];
799 else if (!strcmp (attr[i], "application_versions"))
800 application_versions = attr[i+1];
801 else XML_WARNING("unknown application attribute: %s.", attr[i]);
802 }
803 if (exec && strcmp (exec, data->execName)) {
804 data->ignoringApp = data->inApp;
805 } else if (sha1) {
806 /* SHA1_DIGEST_STRING_LENGTH includes terminating null byte */
807 if (strlen(sha1) != (SHA1_DIGEST_STRING_LENGTH - 1)) {
808 XML_WARNING("Incorrect sha1 application attribute");
809 data->ignoringApp = data->inApp;
810 } else {
811 size_t len;
812 char* content;
813 char path[PATH_MAX];
814 if (util_get_process_exec_path(path, ARRAY_SIZE(path)) > 0 &&
815 (content = os_read_file(path, &len))) {
816 uint8_t sha1x[SHA1_DIGEST_LENGTH];
817 char sha1s[SHA1_DIGEST_STRING_LENGTH];
818 _mesa_sha1_compute(content, len, sha1x);
819 _mesa_sha1_format((char*) sha1s, sha1x);
820 free(content);
821
822 if (strcmp(sha1, sha1s)) {
823 data->ignoringApp = data->inApp;
824 }
825 } else {
826 data->ignoringApp = data->inApp;
827 }
828 }
829 } else if (application_name_match) {
830 regex_t re;
831
832 if (regcomp (&re, application_name_match, REG_EXTENDED|REG_NOSUB) == 0) {
833 if (regexec (&re, data->applicationName, 0, NULL, 0) == REG_NOMATCH)
834 data->ignoringApp = data->inApp;
835 regfree (&re);
836 } else
837 XML_WARNING ("Invalid application_name_match=\"%s\".", application_name_match);
838 }
839 if (application_versions) {
840 if (parseRanges (&version_ranges, application_versions) &&
841 !valueInRanges (&version_ranges, data->applicationVersion))
842 data->ignoringApp = data->inApp;
843 }
844 }
845
846 /** \brief Parse attributes of an application element. */
847 static void
848 parseEngineAttr(struct OptConfData *data, const XML_Char **attr)
849 {
850 uint32_t i;
851 const XML_Char *engine_name_match = NULL, *engine_versions = NULL;
852 driOptionInfo version_ranges = {
853 .type = DRI_INT,
854 };
855 for (i = 0; attr[i]; i += 2) {
856 if (!strcmp (attr[i], "name")) /* not needed here */;
857 else if (!strcmp (attr[i], "engine_name_match")) engine_name_match = attr[i+1];
858 else if (!strcmp (attr[i], "engine_versions")) engine_versions = attr[i+1];
859 else XML_WARNING("unknown application attribute: %s.", attr[i]);
860 }
861 if (engine_name_match) {
862 regex_t re;
863
864 if (regcomp (&re, engine_name_match, REG_EXTENDED|REG_NOSUB) == 0) {
865 if (regexec (&re, data->engineName, 0, NULL, 0) == REG_NOMATCH)
866 data->ignoringApp = data->inApp;
867 regfree (&re);
868 } else
869 XML_WARNING ("Invalid engine_name_match=\"%s\".", engine_name_match);
870 }
871 if (engine_versions) {
872 if (parseRanges (&version_ranges, engine_versions) &&
873 !valueInRanges (&version_ranges, data->engineVersion))
874 data->ignoringApp = data->inApp;
875 }
876
877 free(version_ranges.ranges);
878 }
879
880 /** \brief Parse attributes of an option element. */
881 static void
882 parseOptConfAttr(struct OptConfData *data, const XML_Char **attr)
883 {
884 uint32_t i;
885 const XML_Char *name = NULL, *value = NULL;
886 for (i = 0; attr[i]; i += 2) {
887 if (!strcmp (attr[i], "name")) name = attr[i+1];
888 else if (!strcmp (attr[i], "value")) value = attr[i+1];
889 else XML_WARNING("unknown option attribute: %s.", attr[i]);
890 }
891 if (!name) XML_WARNING1 ("name attribute missing in option.");
892 if (!value) XML_WARNING1 ("value attribute missing in option.");
893 if (name && value) {
894 driOptionCache *cache = data->cache;
895 uint32_t opt = findOption (cache, name);
896 if (cache->info[opt].name == NULL)
897 /* don't use XML_WARNING, drirc defines options for all drivers,
898 * but not all drivers support them */
899 return;
900 else if (getenv (cache->info[opt].name)) {
901 /* don't use XML_WARNING, we want the user to see this! */
902 if (be_verbose()) {
903 fprintf(stderr,
904 "ATTENTION: option value of option %s ignored.\n",
905 cache->info[opt].name);
906 }
907 } else if (!parseValue (&cache->values[opt], cache->info[opt].type, value))
908 XML_WARNING ("illegal option value: %s.", value);
909 }
910 }
911
912 /** \brief Handler for start element events. */
913 static void
914 optConfStartElem(void *userData, const XML_Char *name,
915 const XML_Char **attr)
916 {
917 struct OptConfData *data = (struct OptConfData *)userData;
918 enum OptConfElem elem = bsearchStr (name, OptConfElems, OC_COUNT);
919 switch (elem) {
920 case OC_DRICONF:
921 if (data->inDriConf)
922 XML_WARNING1 ("nested <driconf> elements.");
923 if (attr[0])
924 XML_WARNING1 ("attributes specified on <driconf> element.");
925 data->inDriConf++;
926 break;
927 case OC_DEVICE:
928 if (!data->inDriConf)
929 XML_WARNING1 ("<device> should be inside <driconf>.");
930 if (data->inDevice)
931 XML_WARNING1 ("nested <device> elements.");
932 data->inDevice++;
933 if (!data->ignoringDevice && !data->ignoringApp)
934 parseDeviceAttr (data, attr);
935 break;
936 case OC_APPLICATION:
937 if (!data->inDevice)
938 XML_WARNING1 ("<application> should be inside <device>.");
939 if (data->inApp)
940 XML_WARNING1 ("nested <application> or <engine> elements.");
941 data->inApp++;
942 if (!data->ignoringDevice && !data->ignoringApp)
943 parseAppAttr (data, attr);
944 break;
945 case OC_ENGINE:
946 if (!data->inDevice)
947 XML_WARNING1 ("<engine> should be inside <device>.");
948 if (data->inApp)
949 XML_WARNING1 ("nested <application> or <engine> elements.");
950 data->inApp++;
951 if (!data->ignoringDevice && !data->ignoringApp)
952 parseEngineAttr (data, attr);
953 break;
954 case OC_OPTION:
955 if (!data->inApp)
956 XML_WARNING1 ("<option> should be inside <application>.");
957 if (data->inOption)
958 XML_WARNING1 ("nested <option> elements.");
959 data->inOption++;
960 if (!data->ignoringDevice && !data->ignoringApp)
961 parseOptConfAttr (data, attr);
962 break;
963 default:
964 XML_WARNING ("unknown element: %s.", name);
965 }
966 }
967
968 /** \brief Handler for end element events. */
969 static void
970 optConfEndElem(void *userData, const XML_Char *name)
971 {
972 struct OptConfData *data = (struct OptConfData *)userData;
973 enum OptConfElem elem = bsearchStr (name, OptConfElems, OC_COUNT);
974 switch (elem) {
975 case OC_DRICONF:
976 data->inDriConf--;
977 break;
978 case OC_DEVICE:
979 if (data->inDevice-- == data->ignoringDevice)
980 data->ignoringDevice = 0;
981 break;
982 case OC_APPLICATION:
983 case OC_ENGINE:
984 if (data->inApp-- == data->ignoringApp)
985 data->ignoringApp = 0;
986 break;
987 case OC_OPTION:
988 data->inOption--;
989 break;
990 default:
991 /* unknown element, warning was produced on start tag */;
992 }
993 }
994
995 /** \brief Initialize an option cache based on info */
996 static void
997 initOptionCache(driOptionCache *cache, const driOptionCache *info)
998 {
999 unsigned i, size = 1 << info->tableSize;
1000 cache->info = info->info;
1001 cache->tableSize = info->tableSize;
1002 cache->values = malloc((1<<info->tableSize) * sizeof (driOptionValue));
1003 if (cache->values == NULL) {
1004 fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
1005 abort();
1006 }
1007 memcpy (cache->values, info->values,
1008 (1<<info->tableSize) * sizeof (driOptionValue));
1009 for (i = 0; i < size; ++i) {
1010 if (cache->info[i].type == DRI_STRING)
1011 XSTRDUP(cache->values[i]._string, info->values[i]._string);
1012 }
1013 }
1014
1015 static void
1016 _parseOneConfigFile(XML_Parser p)
1017 {
1018 #define BUF_SIZE 0x1000
1019 struct OptConfData *data = (struct OptConfData *)XML_GetUserData (p);
1020 int status;
1021 int fd;
1022
1023 if ((fd = open (data->name, O_RDONLY)) == -1) {
1024 __driUtilMessage ("Can't open configuration file %s: %s.",
1025 data->name, strerror (errno));
1026 return;
1027 }
1028
1029 while (1) {
1030 int bytesRead;
1031 void *buffer = XML_GetBuffer (p, BUF_SIZE);
1032 if (!buffer) {
1033 __driUtilMessage ("Can't allocate parser buffer.");
1034 break;
1035 }
1036 bytesRead = read (fd, buffer, BUF_SIZE);
1037 if (bytesRead == -1) {
1038 __driUtilMessage ("Error reading from configuration file %s: %s.",
1039 data->name, strerror (errno));
1040 break;
1041 }
1042 status = XML_ParseBuffer (p, bytesRead, bytesRead == 0);
1043 if (!status) {
1044 XML_ERROR ("%s.", XML_ErrorString(XML_GetErrorCode(p)));
1045 break;
1046 }
1047 if (bytesRead == 0)
1048 break;
1049 }
1050
1051 close (fd);
1052 #undef BUF_SIZE
1053 }
1054
1055 /** \brief Parse the named configuration file */
1056 static void
1057 parseOneConfigFile(struct OptConfData *data, const char *filename)
1058 {
1059 XML_Parser p;
1060
1061 p = XML_ParserCreate (NULL); /* use encoding specified by file */
1062 XML_SetElementHandler (p, optConfStartElem, optConfEndElem);
1063 XML_SetUserData (p, data);
1064 data->parser = p;
1065 data->name = filename;
1066 data->ignoringDevice = 0;
1067 data->ignoringApp = 0;
1068 data->inDriConf = 0;
1069 data->inDevice = 0;
1070 data->inApp = 0;
1071 data->inOption = 0;
1072
1073 _parseOneConfigFile (p);
1074 XML_ParserFree (p);
1075 }
1076
1077 static int
1078 scandir_filter(const struct dirent *ent)
1079 {
1080 #ifndef DT_REG /* systems without d_type in dirent results */
1081 struct stat st;
1082
1083 if ((lstat(ent->d_name, &st) != 0) ||
1084 (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode)))
1085 return 0;
1086 #else
1087 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
1088 return 0;
1089 #endif
1090
1091 if (fnmatch("*.conf", ent->d_name, 0))
1092 return 0;
1093
1094 return 1;
1095 }
1096
1097 /** \brief Parse configuration files in a directory */
1098 static void
1099 parseConfigDir(struct OptConfData *data, const char *dirname)
1100 {
1101 int i, count;
1102 struct dirent **entries = NULL;
1103
1104 count = scandir(dirname, &entries, scandir_filter, alphasort);
1105 if (count < 0)
1106 return;
1107
1108 for (i = 0; i < count; i++) {
1109 char filename[PATH_MAX];
1110
1111 snprintf(filename, PATH_MAX, "%s/%s", dirname, entries[i]->d_name);
1112 free(entries[i]);
1113
1114 parseOneConfigFile(data, filename);
1115 }
1116
1117 free(entries);
1118 }
1119
1120 #ifndef SYSCONFDIR
1121 #define SYSCONFDIR "/etc"
1122 #endif
1123
1124 #ifndef DATADIR
1125 #define DATADIR "/usr/share"
1126 #endif
1127
1128 void
1129 driParseConfigFiles(driOptionCache *cache, const driOptionCache *info,
1130 int screenNum, const char *driverName,
1131 const char *kernelDriverName,
1132 const char *applicationName, uint32_t applicationVersion,
1133 const char *engineName, uint32_t engineVersion)
1134 {
1135 char *home;
1136 struct OptConfData userData;
1137
1138 initOptionCache (cache, info);
1139
1140 userData.cache = cache;
1141 userData.screenNum = screenNum;
1142 userData.driverName = driverName;
1143 userData.kernelDriverName = kernelDriverName;
1144 userData.applicationName = applicationName ? applicationName : "";
1145 userData.applicationVersion = applicationVersion;
1146 userData.engineName = engineName ? engineName : "";
1147 userData.engineVersion = engineVersion;
1148 userData.execName = util_get_process_name();
1149
1150 parseConfigDir(&userData, DATADIR "/drirc.d");
1151 parseOneConfigFile(&userData, SYSCONFDIR "/drirc");
1152
1153 if ((home = getenv ("HOME"))) {
1154 char filename[PATH_MAX];
1155
1156 snprintf(filename, PATH_MAX, "%s/.drirc", home);
1157 parseOneConfigFile(&userData, filename);
1158 }
1159 }
1160
1161 void
1162 driDestroyOptionInfo(driOptionCache *info)
1163 {
1164 driDestroyOptionCache(info);
1165 if (info->info) {
1166 uint32_t i, size = 1 << info->tableSize;
1167 for (i = 0; i < size; ++i) {
1168 if (info->info[i].name) {
1169 free(info->info[i].name);
1170 free(info->info[i].ranges);
1171 }
1172 }
1173 free(info->info);
1174 }
1175 }
1176
1177 void
1178 driDestroyOptionCache(driOptionCache *cache)
1179 {
1180 if (cache->info) {
1181 unsigned i, size = 1 << cache->tableSize;
1182 for (i = 0; i < size; ++i) {
1183 if (cache->info[i].type == DRI_STRING)
1184 free(cache->values[i]._string);
1185 }
1186 }
1187 free(cache->values);
1188 }
1189
1190 unsigned char
1191 driCheckOption(const driOptionCache *cache, const char *name,
1192 driOptionType type)
1193 {
1194 uint32_t i = findOption (cache, name);
1195 return cache->info[i].name != NULL && cache->info[i].type == type;
1196 }
1197
1198 unsigned char
1199 driQueryOptionb(const driOptionCache *cache, const char *name)
1200 {
1201 uint32_t i = findOption (cache, name);
1202 /* make sure the option is defined and has the correct type */
1203 assert (cache->info[i].name != NULL);
1204 assert (cache->info[i].type == DRI_BOOL);
1205 return cache->values[i]._bool;
1206 }
1207
1208 int
1209 driQueryOptioni(const driOptionCache *cache, const char *name)
1210 {
1211 uint32_t i = findOption (cache, name);
1212 /* make sure the option is defined and has the correct type */
1213 assert (cache->info[i].name != NULL);
1214 assert (cache->info[i].type == DRI_INT || cache->info[i].type == DRI_ENUM);
1215 return cache->values[i]._int;
1216 }
1217
1218 float
1219 driQueryOptionf(const driOptionCache *cache, const char *name)
1220 {
1221 uint32_t i = findOption (cache, name);
1222 /* make sure the option is defined and has the correct type */
1223 assert (cache->info[i].name != NULL);
1224 assert (cache->info[i].type == DRI_FLOAT);
1225 return cache->values[i]._float;
1226 }
1227
1228 char *
1229 driQueryOptionstr(const driOptionCache *cache, const char *name)
1230 {
1231 uint32_t i = findOption (cache, name);
1232 /* make sure the option is defined and has the correct type */
1233 assert (cache->info[i].name != NULL);
1234 assert (cache->info[i].type == DRI_STRING);
1235 return cache->values[i]._string;
1236 }