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