i965/vs: Allocate register set once at context creation.
[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 "main/glheader.h"
31
32 #include <string.h>
33 #include <assert.h>
34 #include <expat.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include "main/imports.h"
39 #include "utils.h"
40 #include "xmlconfig.h"
41
42 #undef GET_PROGRAM_NAME
43
44 #if (defined(__GNU_LIBRARY__) || defined(__GLIBC__)) && !defined(__UCLIBC__)
45 # if !defined(__GLIBC__) || (__GLIBC__ < 2)
46 /* These aren't declared in any libc5 header */
47 extern char *program_invocation_name, *program_invocation_short_name;
48 # endif
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 GLuint findOption (const driOptionCache *cache, const char *name) {
110 GLuint len = strlen (name);
111 GLuint size = 1 << cache->tableSize, mask = size - 1;
112 GLuint hash = 0;
113 GLuint 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 += (GLuint)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 GLuint 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 GLuint bsearchStr (const XML_Char *name,
150 const XML_Char *elems[], GLuint 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 GLint strToI (const XML_Char *string, const XML_Char **tail, int base) {
169 GLint radix = base == 0 ? 10 : base;
170 GLint result = 0;
171 GLint sign = 1;
172 GLboolean numberFound = GL_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 = GL_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 GLint 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 = GL_TRUE;
207 result = radix*result + digit;
208 string++;
209 } else
210 break;
211 } while (GL_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 GLfloat strToF (const XML_Char *string, const XML_Char **tail) {
229 GLint nDigits = 0, pointPos, exponent;
230 GLfloat 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 * (GLfloat)pow (10.0, (GLdouble)(pointPos-1 + exponent));
274
275 /* second pass: parse digits */
276 do {
277 if (*string != '.') {
278 assert (*string >= '0' && *string <= '9');
279 result += scale * (GLfloat)(*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 GLboolean 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 = GL_FALSE;
299 tail = string + 5;
300 } else if (!strcmp (string, "true")) {
301 v->_bool = GL_TRUE;
302 tail = string + 4;
303 }
304 else
305 return GL_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 }
315
316 if (tail == string)
317 return GL_FALSE; /* empty string (or containing only white-space) */
318 /* skip trailing white space */
319 if (*tail)
320 tail += strspn (tail, " \f\n\r\t\v");
321 if (*tail)
322 return GL_FALSE; /* something left over that is not part of value */
323
324 return GL_TRUE;
325 }
326
327 /** \brief Parse a list of ranges of type info->type. */
328 static GLboolean parseRanges (driOptionInfo *info, const XML_Char *string) {
329 XML_Char *cp, *range;
330 GLuint nRanges, i;
331 driOptionRange *ranges;
332
333 XSTRDUP (cp, string);
334 /* pass 1: determine the number of ranges (number of commas + 1) */
335 range = cp;
336 for (nRanges = 1; *range; ++range)
337 if (*range == ',')
338 ++nRanges;
339
340 if ((ranges = malloc(nRanges*sizeof(driOptionRange))) == NULL) {
341 fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
342 abort();
343 }
344
345 /* pass 2: parse all ranges into preallocated array */
346 range = cp;
347 for (i = 0; i < nRanges; ++i) {
348 XML_Char *end, *sep;
349 assert (range);
350 end = strchr (range, ',');
351 if (end)
352 *end = '\0';
353 sep = strchr (range, ':');
354 if (sep) { /* non-empty interval */
355 *sep = '\0';
356 if (!parseValue (&ranges[i].start, info->type, range) ||
357 !parseValue (&ranges[i].end, info->type, sep+1))
358 break;
359 if (info->type == DRI_INT &&
360 ranges[i].start._int > ranges[i].end._int)
361 break;
362 if (info->type == DRI_FLOAT &&
363 ranges[i].start._float > ranges[i].end._float)
364 break;
365 } else { /* empty interval */
366 if (!parseValue (&ranges[i].start, info->type, range))
367 break;
368 ranges[i].end = ranges[i].start;
369 }
370 if (end)
371 range = end+1;
372 else
373 range = NULL;
374 }
375 free(cp);
376 if (i < nRanges) {
377 free(ranges);
378 return GL_FALSE;
379 } else
380 assert (range == NULL);
381
382 info->nRanges = nRanges;
383 info->ranges = ranges;
384 return GL_TRUE;
385 }
386
387 /** \brief Check if a value is in one of info->ranges. */
388 static GLboolean checkValue (const driOptionValue *v, const driOptionInfo *info) {
389 GLuint i;
390 assert (info->type != DRI_BOOL); /* should be caught by the parser */
391 if (info->nRanges == 0)
392 return GL_TRUE;
393 switch (info->type) {
394 case DRI_ENUM: /* enum is just a special integer */
395 case DRI_INT:
396 for (i = 0; i < info->nRanges; ++i)
397 if (v->_int >= info->ranges[i].start._int &&
398 v->_int <= info->ranges[i].end._int)
399 return GL_TRUE;
400 break;
401 case DRI_FLOAT:
402 for (i = 0; i < info->nRanges; ++i)
403 if (v->_float >= info->ranges[i].start._float &&
404 v->_float <= info->ranges[i].end._float)
405 return GL_TRUE;
406 break;
407 default:
408 assert (0); /* should never happen */
409 }
410 return GL_FALSE;
411 }
412
413 /**
414 * Print message to \c stderr if the \c LIBGL_DEBUG environment variable
415 * is set.
416 *
417 * Is called from the drivers.
418 *
419 * \param f \c printf like format string.
420 */
421 static void
422 __driUtilMessage(const char *f, ...)
423 {
424 va_list args;
425
426 if (getenv("LIBGL_DEBUG")) {
427 fprintf(stderr, "libGL: ");
428 va_start(args, f);
429 vfprintf(stderr, f, args);
430 va_end(args);
431 fprintf(stderr, "\n");
432 }
433 }
434
435 /** \brief Output a warning message. */
436 #define XML_WARNING1(msg) do {\
437 __driUtilMessage ("Warning in %s line %d, column %d: "msg, data->name, \
438 (int) XML_GetCurrentLineNumber(data->parser), \
439 (int) XML_GetCurrentColumnNumber(data->parser)); \
440 } while (0)
441 #define XML_WARNING(msg,args...) do { \
442 __driUtilMessage ("Warning in %s line %d, column %d: "msg, data->name, \
443 (int) XML_GetCurrentLineNumber(data->parser), \
444 (int) XML_GetCurrentColumnNumber(data->parser), \
445 args); \
446 } while (0)
447 /** \brief Output an error message. */
448 #define XML_ERROR1(msg) do { \
449 __driUtilMessage ("Error in %s line %d, column %d: "msg, data->name, \
450 (int) XML_GetCurrentLineNumber(data->parser), \
451 (int) XML_GetCurrentColumnNumber(data->parser)); \
452 } while (0)
453 #define XML_ERROR(msg,args...) do { \
454 __driUtilMessage ("Error in %s line %d, column %d: "msg, data->name, \
455 (int) XML_GetCurrentLineNumber(data->parser), \
456 (int) XML_GetCurrentColumnNumber(data->parser), \
457 args); \
458 } while (0)
459 /** \brief Output a fatal error message and abort. */
460 #define XML_FATAL1(msg) do { \
461 fprintf (stderr, "Fatal error in %s line %d, column %d: "msg"\n", \
462 data->name, \
463 (int) XML_GetCurrentLineNumber(data->parser), \
464 (int) XML_GetCurrentColumnNumber(data->parser)); \
465 abort();\
466 } while (0)
467 #define XML_FATAL(msg,args...) do { \
468 fprintf (stderr, "Fatal error in %s line %d, column %d: "msg"\n", \
469 data->name, \
470 (int) XML_GetCurrentLineNumber(data->parser), \
471 (int) XML_GetCurrentColumnNumber(data->parser), \
472 args); \
473 abort();\
474 } while (0)
475
476 /** \brief Parser context for __driConfigOptions. */
477 struct OptInfoData {
478 const char *name;
479 XML_Parser parser;
480 driOptionCache *cache;
481 GLboolean inDriInfo;
482 GLboolean inSection;
483 GLboolean inDesc;
484 GLboolean inOption;
485 GLboolean inEnum;
486 int curOption;
487 };
488
489 /** \brief Elements in __driConfigOptions. */
490 enum OptInfoElem {
491 OI_DESCRIPTION = 0, OI_DRIINFO, OI_ENUM, OI_OPTION, OI_SECTION, OI_COUNT
492 };
493 static const XML_Char *OptInfoElems[] = {
494 "description", "driinfo", "enum", "option", "section"
495 };
496
497 /** \brief Parse attributes of an enum element.
498 *
499 * We're not actually interested in the data. Just make sure this is ok
500 * for external configuration tools.
501 */
502 static void parseEnumAttr (struct OptInfoData *data, const XML_Char **attr) {
503 GLuint i;
504 const XML_Char *value = NULL, *text = NULL;
505 driOptionValue v;
506 GLuint opt = data->curOption;
507 for (i = 0; attr[i]; i += 2) {
508 if (!strcmp (attr[i], "value")) value = attr[i+1];
509 else if (!strcmp (attr[i], "text")) text = attr[i+1];
510 else XML_FATAL("illegal enum attribute: %s.", attr[i]);
511 }
512 if (!value) XML_FATAL1 ("value attribute missing in enum.");
513 if (!text) XML_FATAL1 ("text attribute missing in enum.");
514 if (!parseValue (&v, data->cache->info[opt].type, value))
515 XML_FATAL ("illegal enum value: %s.", value);
516 if (!checkValue (&v, &data->cache->info[opt]))
517 XML_FATAL ("enum value out of valid range: %s.", value);
518 }
519
520 /** \brief Parse attributes of a description element.
521 *
522 * We're not actually interested in the data. Just make sure this is ok
523 * for external configuration tools.
524 */
525 static void parseDescAttr (struct OptInfoData *data, const XML_Char **attr) {
526 GLuint i;
527 const XML_Char *lang = NULL, *text = NULL;
528 for (i = 0; attr[i]; i += 2) {
529 if (!strcmp (attr[i], "lang")) lang = attr[i+1];
530 else if (!strcmp (attr[i], "text")) text = attr[i+1];
531 else XML_FATAL("illegal description attribute: %s.", attr[i]);
532 }
533 if (!lang) XML_FATAL1 ("lang attribute missing in description.");
534 if (!text) XML_FATAL1 ("text attribute missing in description.");
535 }
536
537 /** \brief Parse attributes of an option element. */
538 static void parseOptInfoAttr (struct OptInfoData *data, const XML_Char **attr) {
539 enum OptAttr {OA_DEFAULT = 0, OA_NAME, OA_TYPE, OA_VALID, OA_COUNT};
540 static const XML_Char *optAttr[] = {"default", "name", "type", "valid"};
541 const XML_Char *attrVal[OA_COUNT] = {NULL, NULL, NULL, NULL};
542 const char *defaultVal;
543 driOptionCache *cache = data->cache;
544 GLuint opt, i;
545 for (i = 0; attr[i]; i += 2) {
546 GLuint attrName = bsearchStr (attr[i], optAttr, OA_COUNT);
547 if (attrName >= OA_COUNT)
548 XML_FATAL ("illegal option attribute: %s", attr[i]);
549 attrVal[attrName] = attr[i+1];
550 }
551 if (!attrVal[OA_NAME]) XML_FATAL1 ("name attribute missing in option.");
552 if (!attrVal[OA_TYPE]) XML_FATAL1 ("type attribute missing in option.");
553 if (!attrVal[OA_DEFAULT]) XML_FATAL1 ("default attribute missing in option.");
554
555 opt = findOption (cache, attrVal[OA_NAME]);
556 if (cache->info[opt].name)
557 XML_FATAL ("option %s redefined.", attrVal[OA_NAME]);
558 data->curOption = opt;
559
560 XSTRDUP (cache->info[opt].name, attrVal[OA_NAME]);
561
562 if (!strcmp (attrVal[OA_TYPE], "bool"))
563 cache->info[opt].type = DRI_BOOL;
564 else if (!strcmp (attrVal[OA_TYPE], "enum"))
565 cache->info[opt].type = DRI_ENUM;
566 else if (!strcmp (attrVal[OA_TYPE], "int"))
567 cache->info[opt].type = DRI_INT;
568 else if (!strcmp (attrVal[OA_TYPE], "float"))
569 cache->info[opt].type = DRI_FLOAT;
570 else
571 XML_FATAL ("illegal type in option: %s.", attrVal[OA_TYPE]);
572
573 defaultVal = getenv (cache->info[opt].name);
574 if (defaultVal != NULL) {
575 /* don't use XML_WARNING, we want the user to see this! */
576 fprintf (stderr,
577 "ATTENTION: default value of option %s overridden by environment.\n",
578 cache->info[opt].name);
579 } else
580 defaultVal = attrVal[OA_DEFAULT];
581 if (!parseValue (&cache->values[opt], cache->info[opt].type, defaultVal))
582 XML_FATAL ("illegal default value for %s: %s.", cache->info[opt].name, defaultVal);
583
584 if (attrVal[OA_VALID]) {
585 if (cache->info[opt].type == DRI_BOOL)
586 XML_FATAL1 ("boolean option with valid attribute.");
587 if (!parseRanges (&cache->info[opt], attrVal[OA_VALID]))
588 XML_FATAL ("illegal valid attribute: %s.", attrVal[OA_VALID]);
589 if (!checkValue (&cache->values[opt], &cache->info[opt]))
590 XML_FATAL ("default value out of valid range '%s': %s.",
591 attrVal[OA_VALID], defaultVal);
592 } else if (cache->info[opt].type == DRI_ENUM) {
593 XML_FATAL1 ("valid attribute missing in option (mandatory for enums).");
594 } else {
595 cache->info[opt].nRanges = 0;
596 cache->info[opt].ranges = NULL;
597 }
598 }
599
600 /** \brief Handler for start element events. */
601 static void optInfoStartElem (void *userData, const XML_Char *name,
602 const XML_Char **attr) {
603 struct OptInfoData *data = (struct OptInfoData *)userData;
604 enum OptInfoElem elem = bsearchStr (name, OptInfoElems, OI_COUNT);
605 switch (elem) {
606 case OI_DRIINFO:
607 if (data->inDriInfo)
608 XML_FATAL1 ("nested <driinfo> elements.");
609 if (attr[0])
610 XML_FATAL1 ("attributes specified on <driinfo> element.");
611 data->inDriInfo = GL_TRUE;
612 break;
613 case OI_SECTION:
614 if (!data->inDriInfo)
615 XML_FATAL1 ("<section> must be inside <driinfo>.");
616 if (data->inSection)
617 XML_FATAL1 ("nested <section> elements.");
618 if (attr[0])
619 XML_FATAL1 ("attributes specified on <section> element.");
620 data->inSection = GL_TRUE;
621 break;
622 case OI_DESCRIPTION:
623 if (!data->inSection && !data->inOption)
624 XML_FATAL1 ("<description> must be inside <description> or <option.");
625 if (data->inDesc)
626 XML_FATAL1 ("nested <description> elements.");
627 data->inDesc = GL_TRUE;
628 parseDescAttr (data, attr);
629 break;
630 case OI_OPTION:
631 if (!data->inSection)
632 XML_FATAL1 ("<option> must be inside <section>.");
633 if (data->inDesc)
634 XML_FATAL1 ("<option> nested in <description> element.");
635 if (data->inOption)
636 XML_FATAL1 ("nested <option> elements.");
637 data->inOption = GL_TRUE;
638 parseOptInfoAttr (data, attr);
639 break;
640 case OI_ENUM:
641 if (!(data->inOption && data->inDesc))
642 XML_FATAL1 ("<enum> must be inside <option> and <description>.");
643 if (data->inEnum)
644 XML_FATAL1 ("nested <enum> elements.");
645 data->inEnum = GL_TRUE;
646 parseEnumAttr (data, attr);
647 break;
648 default:
649 XML_FATAL ("unknown element: %s.", name);
650 }
651 }
652
653 /** \brief Handler for end element events. */
654 static void optInfoEndElem (void *userData, const XML_Char *name) {
655 struct OptInfoData *data = (struct OptInfoData *)userData;
656 enum OptInfoElem elem = bsearchStr (name, OptInfoElems, OI_COUNT);
657 switch (elem) {
658 case OI_DRIINFO:
659 data->inDriInfo = GL_FALSE;
660 break;
661 case OI_SECTION:
662 data->inSection = GL_FALSE;
663 break;
664 case OI_DESCRIPTION:
665 data->inDesc = GL_FALSE;
666 break;
667 case OI_OPTION:
668 data->inOption = GL_FALSE;
669 break;
670 case OI_ENUM:
671 data->inEnum = GL_FALSE;
672 break;
673 default:
674 assert (0); /* should have been caught by StartElem */
675 }
676 }
677
678 void driParseOptionInfo (driOptionCache *info, const char *configOptions) {
679 XML_Parser p;
680 int status;
681 struct OptInfoData userData;
682 struct OptInfoData *data = &userData;
683
684 /* Make the hash table big enough to fit more than the maximum number of
685 * config options we've ever seen in a driver.
686 */
687 info->tableSize = 6;
688 info->info = calloc(1 << info->tableSize, sizeof (driOptionInfo));
689 info->values = calloc(1 << info->tableSize, sizeof (driOptionValue));
690 if (info->info == NULL || info->values == NULL) {
691 fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
692 abort();
693 }
694
695 p = XML_ParserCreate ("UTF-8"); /* always UTF-8 */
696 XML_SetElementHandler (p, optInfoStartElem, optInfoEndElem);
697 XML_SetUserData (p, data);
698
699 userData.name = "__driConfigOptions";
700 userData.parser = p;
701 userData.cache = info;
702 userData.inDriInfo = GL_FALSE;
703 userData.inSection = GL_FALSE;
704 userData.inDesc = GL_FALSE;
705 userData.inOption = GL_FALSE;
706 userData.inEnum = GL_FALSE;
707 userData.curOption = -1;
708
709 status = XML_Parse (p, configOptions, strlen (configOptions), 1);
710 if (!status)
711 XML_FATAL ("%s.", XML_ErrorString(XML_GetErrorCode(p)));
712
713 XML_ParserFree (p);
714 }
715
716 /** \brief Parser context for configuration files. */
717 struct OptConfData {
718 const char *name;
719 XML_Parser parser;
720 driOptionCache *cache;
721 GLint screenNum;
722 const char *driverName, *execName;
723 GLuint ignoringDevice;
724 GLuint ignoringApp;
725 GLuint inDriConf;
726 GLuint inDevice;
727 GLuint inApp;
728 GLuint inOption;
729 };
730
731 /** \brief Elements in configuration files. */
732 enum OptConfElem {
733 OC_APPLICATION = 0, OC_DEVICE, OC_DRICONF, OC_OPTION, OC_COUNT
734 };
735 static const XML_Char *OptConfElems[] = {
736 "application", "device", "driconf", "option"
737 };
738
739 /** \brief Parse attributes of a device element. */
740 static void parseDeviceAttr (struct OptConfData *data, const XML_Char **attr) {
741 GLuint i;
742 const XML_Char *driver = NULL, *screen = NULL;
743 for (i = 0; attr[i]; i += 2) {
744 if (!strcmp (attr[i], "driver")) driver = attr[i+1];
745 else if (!strcmp (attr[i], "screen")) screen = attr[i+1];
746 else XML_WARNING("unknown device attribute: %s.", attr[i]);
747 }
748 if (driver && strcmp (driver, data->driverName))
749 data->ignoringDevice = data->inDevice;
750 else if (screen) {
751 driOptionValue screenNum;
752 if (!parseValue (&screenNum, DRI_INT, screen))
753 XML_WARNING("illegal screen number: %s.", screen);
754 else if (screenNum._int != data->screenNum)
755 data->ignoringDevice = data->inDevice;
756 }
757 }
758
759 /** \brief Parse attributes of an application element. */
760 static void parseAppAttr (struct OptConfData *data, const XML_Char **attr) {
761 GLuint i;
762 const XML_Char *exec = NULL;
763 for (i = 0; attr[i]; i += 2) {
764 if (!strcmp (attr[i], "name")) /* not needed here */;
765 else if (!strcmp (attr[i], "executable")) exec = attr[i+1];
766 else XML_WARNING("unknown application attribute: %s.", attr[i]);
767 }
768 if (exec && strcmp (exec, data->execName))
769 data->ignoringApp = data->inApp;
770 }
771
772 /** \brief Parse attributes of an option element. */
773 static void parseOptConfAttr (struct OptConfData *data, const XML_Char **attr) {
774 GLuint i;
775 const XML_Char *name = NULL, *value = NULL;
776 for (i = 0; attr[i]; i += 2) {
777 if (!strcmp (attr[i], "name")) name = attr[i+1];
778 else if (!strcmp (attr[i], "value")) value = attr[i+1];
779 else XML_WARNING("unknown option attribute: %s.", attr[i]);
780 }
781 if (!name) XML_WARNING1 ("name attribute missing in option.");
782 if (!value) XML_WARNING1 ("value attribute missing in option.");
783 if (name && value) {
784 driOptionCache *cache = data->cache;
785 GLuint opt = findOption (cache, name);
786 if (cache->info[opt].name == NULL)
787 /* don't use XML_WARNING, drirc defines options for all drivers,
788 * but not all drivers support them */
789 return;
790 else if (getenv (cache->info[opt].name))
791 /* don't use XML_WARNING, we want the user to see this! */
792 fprintf (stderr, "ATTENTION: option value of option %s ignored.\n",
793 cache->info[opt].name);
794 else if (!parseValue (&cache->values[opt], cache->info[opt].type, value))
795 XML_WARNING ("illegal option value: %s.", value);
796 }
797 }
798
799 /** \brief Handler for start element events. */
800 static void optConfStartElem (void *userData, const XML_Char *name,
801 const XML_Char **attr) {
802 struct OptConfData *data = (struct OptConfData *)userData;
803 enum OptConfElem elem = bsearchStr (name, OptConfElems, OC_COUNT);
804 switch (elem) {
805 case OC_DRICONF:
806 if (data->inDriConf)
807 XML_WARNING1 ("nested <driconf> elements.");
808 if (attr[0])
809 XML_WARNING1 ("attributes specified on <driconf> element.");
810 data->inDriConf++;
811 break;
812 case OC_DEVICE:
813 if (!data->inDriConf)
814 XML_WARNING1 ("<device> should be inside <driconf>.");
815 if (data->inDevice)
816 XML_WARNING1 ("nested <device> elements.");
817 data->inDevice++;
818 if (!data->ignoringDevice && !data->ignoringApp)
819 parseDeviceAttr (data, attr);
820 break;
821 case OC_APPLICATION:
822 if (!data->inDevice)
823 XML_WARNING1 ("<application> should be inside <device>.");
824 if (data->inApp)
825 XML_WARNING1 ("nested <application> elements.");
826 data->inApp++;
827 if (!data->ignoringDevice && !data->ignoringApp)
828 parseAppAttr (data, attr);
829 break;
830 case OC_OPTION:
831 if (!data->inApp)
832 XML_WARNING1 ("<option> should be inside <application>.");
833 if (data->inOption)
834 XML_WARNING1 ("nested <option> elements.");
835 data->inOption++;
836 if (!data->ignoringDevice && !data->ignoringApp)
837 parseOptConfAttr (data, attr);
838 break;
839 default:
840 XML_WARNING ("unknown element: %s.", name);
841 }
842 }
843
844 /** \brief Handler for end element events. */
845 static void optConfEndElem (void *userData, const XML_Char *name) {
846 struct OptConfData *data = (struct OptConfData *)userData;
847 enum OptConfElem elem = bsearchStr (name, OptConfElems, OC_COUNT);
848 switch (elem) {
849 case OC_DRICONF:
850 data->inDriConf--;
851 break;
852 case OC_DEVICE:
853 if (data->inDevice-- == data->ignoringDevice)
854 data->ignoringDevice = 0;
855 break;
856 case OC_APPLICATION:
857 if (data->inApp-- == data->ignoringApp)
858 data->ignoringApp = 0;
859 break;
860 case OC_OPTION:
861 data->inOption--;
862 break;
863 default:
864 /* unknown element, warning was produced on start tag */;
865 }
866 }
867
868 /** \brief Initialize an option cache based on info */
869 static void initOptionCache (driOptionCache *cache, const driOptionCache *info) {
870 cache->info = info->info;
871 cache->tableSize = info->tableSize;
872 cache->values = malloc((1<<info->tableSize) * sizeof (driOptionValue));
873 if (cache->values == NULL) {
874 fprintf (stderr, "%s: %d: out of memory.\n", __FILE__, __LINE__);
875 abort();
876 }
877 memcpy (cache->values, info->values,
878 (1<<info->tableSize) * sizeof (driOptionValue));
879 }
880
881 /** \brief Parse the named configuration file */
882 static void parseOneConfigFile (XML_Parser p) {
883 #define BUF_SIZE 0x1000
884 struct OptConfData *data = (struct OptConfData *)XML_GetUserData (p);
885 int status;
886 int fd;
887
888 if ((fd = open (data->name, O_RDONLY)) == -1) {
889 __driUtilMessage ("Can't open configuration file %s: %s.",
890 data->name, strerror (errno));
891 return;
892 }
893
894 while (1) {
895 int bytesRead;
896 void *buffer = XML_GetBuffer (p, BUF_SIZE);
897 if (!buffer) {
898 __driUtilMessage ("Can't allocate parser buffer.");
899 break;
900 }
901 bytesRead = read (fd, buffer, BUF_SIZE);
902 if (bytesRead == -1) {
903 __driUtilMessage ("Error reading from configuration file %s: %s.",
904 data->name, strerror (errno));
905 break;
906 }
907 status = XML_ParseBuffer (p, bytesRead, bytesRead == 0);
908 if (!status) {
909 XML_ERROR ("%s.", XML_ErrorString(XML_GetErrorCode(p)));
910 break;
911 }
912 if (bytesRead == 0)
913 break;
914 }
915
916 close (fd);
917 #undef BUF_SIZE
918 }
919
920 void driParseConfigFiles (driOptionCache *cache, const driOptionCache *info,
921 GLint screenNum, const char *driverName) {
922 char *filenames[2] = {"/etc/drirc", NULL};
923 char *home;
924 GLuint i;
925 struct OptConfData userData;
926
927 initOptionCache (cache, info);
928
929 userData.cache = cache;
930 userData.screenNum = screenNum;
931 userData.driverName = driverName;
932 userData.execName = GET_PROGRAM_NAME();
933
934 if ((home = getenv ("HOME"))) {
935 GLuint len = strlen (home);
936 filenames[1] = malloc(len + 7+1);
937 if (filenames[1] == NULL)
938 __driUtilMessage ("Can't allocate memory for %s/.drirc.", home);
939 else {
940 memcpy (filenames[1], home, len);
941 memcpy (filenames[1] + len, "/.drirc", 7+1);
942 }
943 }
944
945 for (i = 0; i < 2; ++i) {
946 XML_Parser p;
947 if (filenames[i] == NULL)
948 continue;
949
950 p = XML_ParserCreate (NULL); /* use encoding specified by file */
951 XML_SetElementHandler (p, optConfStartElem, optConfEndElem);
952 XML_SetUserData (p, &userData);
953 userData.parser = p;
954 userData.name = filenames[i];
955 userData.ignoringDevice = 0;
956 userData.ignoringApp = 0;
957 userData.inDriConf = 0;
958 userData.inDevice = 0;
959 userData.inApp = 0;
960 userData.inOption = 0;
961
962 parseOneConfigFile (p);
963 XML_ParserFree (p);
964 }
965
966 free(filenames[1]);
967 }
968
969 void driDestroyOptionInfo (driOptionCache *info) {
970 driDestroyOptionCache (info);
971 if (info->info) {
972 GLuint i, size = 1 << info->tableSize;
973 for (i = 0; i < size; ++i) {
974 if (info->info[i].name) {
975 free(info->info[i].name);
976 free(info->info[i].ranges);
977 }
978 }
979 free(info->info);
980 }
981 }
982
983 void driDestroyOptionCache (driOptionCache *cache) {
984 free(cache->values);
985 }
986
987 GLboolean driCheckOption (const driOptionCache *cache, const char *name,
988 driOptionType type) {
989 GLuint i = findOption (cache, name);
990 return cache->info[i].name != NULL && cache->info[i].type == type;
991 }
992
993 GLboolean driQueryOptionb (const driOptionCache *cache, const char *name) {
994 GLuint i = findOption (cache, name);
995 /* make sure the option is defined and has the correct type */
996 assert (cache->info[i].name != NULL);
997 assert (cache->info[i].type == DRI_BOOL);
998 return cache->values[i]._bool;
999 }
1000
1001 GLint driQueryOptioni (const driOptionCache *cache, const char *name) {
1002 GLuint i = findOption (cache, name);
1003 /* make sure the option is defined and has the correct type */
1004 assert (cache->info[i].name != NULL);
1005 assert (cache->info[i].type == DRI_INT || cache->info[i].type == DRI_ENUM);
1006 return cache->values[i]._int;
1007 }
1008
1009 GLfloat driQueryOptionf (const driOptionCache *cache, const char *name) {
1010 GLuint i = findOption (cache, name);
1011 /* make sure the option is defined and has the correct type */
1012 assert (cache->info[i].name != NULL);
1013 assert (cache->info[i].type == DRI_FLOAT);
1014 return cache->values[i]._float;
1015 }