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