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