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