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