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