init from v2.6.32.60
[mach-moxart.git] / tools / perf / util / config.c
blob1720d0101b0b516d761f9857181d23136a4cce6a
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "util.h"
9 #include "cache.h"
10 #include "exec_cmd.h"
12 #define MAXNAME (256)
14 static FILE *config_file;
15 static const char *config_file_name;
16 static int config_linenr;
17 static int config_file_eof;
19 const char *config_exclusive_filename = NULL;
21 static int get_next_char(void)
23 int c;
24 FILE *f;
26 c = '\n';
27 if ((f = config_file) != NULL) {
28 c = fgetc(f);
29 if (c == '\r') {
30 /* DOS like systems */
31 c = fgetc(f);
32 if (c != '\n') {
33 ungetc(c, f);
34 c = '\r';
37 if (c == '\n')
38 config_linenr++;
39 if (c == EOF) {
40 config_file_eof = 1;
41 c = '\n';
44 return c;
47 static char *parse_value(void)
49 static char value[1024];
50 int quote = 0, comment = 0, space = 0;
51 size_t len = 0;
53 for (;;) {
54 int c = get_next_char();
56 if (len >= sizeof(value) - 1)
57 return NULL;
58 if (c == '\n') {
59 if (quote)
60 return NULL;
61 value[len] = 0;
62 return value;
64 if (comment)
65 continue;
66 if (isspace(c) && !quote) {
67 space = 1;
68 continue;
70 if (!quote) {
71 if (c == ';' || c == '#') {
72 comment = 1;
73 continue;
76 if (space) {
77 if (len)
78 value[len++] = ' ';
79 space = 0;
81 if (c == '\\') {
82 c = get_next_char();
83 switch (c) {
84 case '\n':
85 continue;
86 case 't':
87 c = '\t';
88 break;
89 case 'b':
90 c = '\b';
91 break;
92 case 'n':
93 c = '\n';
94 break;
95 /* Some characters escape as themselves */
96 case '\\': case '"':
97 break;
98 /* Reject unknown escape sequences */
99 default:
100 return NULL;
102 value[len++] = c;
103 continue;
105 if (c == '"') {
106 quote = 1-quote;
107 continue;
109 value[len++] = c;
113 static inline int iskeychar(int c)
115 return isalnum(c) || c == '-';
118 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
120 int c;
121 char *value;
123 /* Get the full name */
124 for (;;) {
125 c = get_next_char();
126 if (config_file_eof)
127 break;
128 if (!iskeychar(c))
129 break;
130 name[len++] = tolower(c);
131 if (len >= MAXNAME)
132 return -1;
134 name[len] = 0;
135 while (c == ' ' || c == '\t')
136 c = get_next_char();
138 value = NULL;
139 if (c != '\n') {
140 if (c != '=')
141 return -1;
142 value = parse_value();
143 if (!value)
144 return -1;
146 return fn(name, value, data);
149 static int get_extended_base_var(char *name, int baselen, int c)
151 do {
152 if (c == '\n')
153 return -1;
154 c = get_next_char();
155 } while (isspace(c));
157 /* We require the format to be '[base "extension"]' */
158 if (c != '"')
159 return -1;
160 name[baselen++] = '.';
162 for (;;) {
163 int ch = get_next_char();
165 if (ch == '\n')
166 return -1;
167 if (ch == '"')
168 break;
169 if (ch == '\\') {
170 ch = get_next_char();
171 if (ch == '\n')
172 return -1;
174 name[baselen++] = ch;
175 if (baselen > MAXNAME / 2)
176 return -1;
179 /* Final ']' */
180 if (get_next_char() != ']')
181 return -1;
182 return baselen;
185 static int get_base_var(char *name)
187 int baselen = 0;
189 for (;;) {
190 int c = get_next_char();
191 if (config_file_eof)
192 return -1;
193 if (c == ']')
194 return baselen;
195 if (isspace(c))
196 return get_extended_base_var(name, baselen, c);
197 if (!iskeychar(c) && c != '.')
198 return -1;
199 if (baselen > MAXNAME / 2)
200 return -1;
201 name[baselen++] = tolower(c);
205 static int perf_parse_file(config_fn_t fn, void *data)
207 int comment = 0;
208 int baselen = 0;
209 static char var[MAXNAME];
211 /* U+FEFF Byte Order Mark in UTF8 */
212 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
213 const unsigned char *bomptr = utf8_bom;
215 for (;;) {
216 int c = get_next_char();
217 if (bomptr && *bomptr) {
218 /* We are at the file beginning; skip UTF8-encoded BOM
219 * if present. Sane editors won't put this in on their
220 * own, but e.g. Windows Notepad will do it happily. */
221 if ((unsigned char) c == *bomptr) {
222 bomptr++;
223 continue;
224 } else {
225 /* Do not tolerate partial BOM. */
226 if (bomptr != utf8_bom)
227 break;
228 /* No BOM at file beginning. Cool. */
229 bomptr = NULL;
232 if (c == '\n') {
233 if (config_file_eof)
234 return 0;
235 comment = 0;
236 continue;
238 if (comment || isspace(c))
239 continue;
240 if (c == '#' || c == ';') {
241 comment = 1;
242 continue;
244 if (c == '[') {
245 baselen = get_base_var(var);
246 if (baselen <= 0)
247 break;
248 var[baselen++] = '.';
249 var[baselen] = 0;
250 continue;
252 if (!isalpha(c))
253 break;
254 var[baselen] = tolower(c);
255 if (get_value(fn, data, var, baselen+1) < 0)
256 break;
258 die("bad config file line %d in %s", config_linenr, config_file_name);
261 static int parse_unit_factor(const char *end, unsigned long *val)
263 if (!*end)
264 return 1;
265 else if (!strcasecmp(end, "k")) {
266 *val *= 1024;
267 return 1;
269 else if (!strcasecmp(end, "m")) {
270 *val *= 1024 * 1024;
271 return 1;
273 else if (!strcasecmp(end, "g")) {
274 *val *= 1024 * 1024 * 1024;
275 return 1;
277 return 0;
280 static int perf_parse_long(const char *value, long *ret)
282 if (value && *value) {
283 char *end;
284 long val = strtol(value, &end, 0);
285 unsigned long factor = 1;
286 if (!parse_unit_factor(end, &factor))
287 return 0;
288 *ret = val * factor;
289 return 1;
291 return 0;
294 int perf_parse_ulong(const char *value, unsigned long *ret)
296 if (value && *value) {
297 char *end;
298 unsigned long val = strtoul(value, &end, 0);
299 if (!parse_unit_factor(end, &val))
300 return 0;
301 *ret = val;
302 return 1;
304 return 0;
307 static void die_bad_config(const char *name)
309 if (config_file_name)
310 die("bad config value for '%s' in %s", name, config_file_name);
311 die("bad config value for '%s'", name);
314 int perf_config_int(const char *name, const char *value)
316 long ret = 0;
317 if (!perf_parse_long(value, &ret))
318 die_bad_config(name);
319 return ret;
322 unsigned long perf_config_ulong(const char *name, const char *value)
324 unsigned long ret;
325 if (!perf_parse_ulong(value, &ret))
326 die_bad_config(name);
327 return ret;
330 int perf_config_bool_or_int(const char *name, const char *value, int *is_bool)
332 *is_bool = 1;
333 if (!value)
334 return 1;
335 if (!*value)
336 return 0;
337 if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on"))
338 return 1;
339 if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off"))
340 return 0;
341 *is_bool = 0;
342 return perf_config_int(name, value);
345 int perf_config_bool(const char *name, const char *value)
347 int discard;
348 return !!perf_config_bool_or_int(name, value, &discard);
351 int perf_config_string(const char **dest, const char *var, const char *value)
353 if (!value)
354 return config_error_nonbool(var);
355 *dest = strdup(value);
356 return 0;
359 static int perf_default_core_config(const char *var __used, const char *value __used)
361 /* Add other config variables here and to Documentation/config.txt. */
362 return 0;
365 int perf_default_config(const char *var, const char *value, void *dummy __used)
367 if (!prefixcmp(var, "core."))
368 return perf_default_core_config(var, value);
370 /* Add other config variables here and to Documentation/config.txt. */
371 return 0;
374 int perf_config_from_file(config_fn_t fn, const char *filename, void *data)
376 int ret;
377 FILE *f = fopen(filename, "r");
379 ret = -1;
380 if (f) {
381 config_file = f;
382 config_file_name = filename;
383 config_linenr = 1;
384 config_file_eof = 0;
385 ret = perf_parse_file(fn, data);
386 fclose(f);
387 config_file_name = NULL;
389 return ret;
392 const char *perf_etc_perfconfig(void)
394 static const char *system_wide;
395 if (!system_wide)
396 system_wide = system_path(ETC_PERFCONFIG);
397 return system_wide;
400 static int perf_env_bool(const char *k, int def)
402 const char *v = getenv(k);
403 return v ? perf_config_bool(k, v) : def;
406 int perf_config_system(void)
408 return !perf_env_bool("PERF_CONFIG_NOSYSTEM", 0);
411 int perf_config_global(void)
413 return !perf_env_bool("PERF_CONFIG_NOGLOBAL", 0);
416 int perf_config(config_fn_t fn, void *data)
418 int ret = 0, found = 0;
419 const char *home = NULL;
421 /* Setting $PERF_CONFIG makes perf read _only_ the given config file. */
422 if (config_exclusive_filename)
423 return perf_config_from_file(fn, config_exclusive_filename, data);
424 if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK)) {
425 ret += perf_config_from_file(fn, perf_etc_perfconfig(),
426 data);
427 found += 1;
430 home = getenv("HOME");
431 if (perf_config_global() && home) {
432 char *user_config = strdup(mkpath("%s/.perfconfig", home));
433 if (!access(user_config, R_OK)) {
434 ret += perf_config_from_file(fn, user_config, data);
435 found += 1;
437 free(user_config);
440 if (found == 0)
441 return -1;
442 return ret;
446 * Find all the stuff for perf_config_set() below.
449 #define MAX_MATCHES 512
451 static struct {
452 int baselen;
453 char* key;
454 int do_not_match;
455 regex_t* value_regex;
456 int multi_replace;
457 size_t offset[MAX_MATCHES];
458 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
459 int seen;
460 } store;
462 static int matches(const char* key, const char* value)
464 return !strcmp(key, store.key) &&
465 (store.value_regex == NULL ||
466 (store.do_not_match ^
467 !regexec(store.value_regex, value, 0, NULL, 0)));
470 static int store_aux(const char* key, const char* value, void *cb __used)
472 int section_len;
473 const char *ep;
475 switch (store.state) {
476 case KEY_SEEN:
477 if (matches(key, value)) {
478 if (store.seen == 1 && store.multi_replace == 0) {
479 warning("%s has multiple values", key);
480 } else if (store.seen >= MAX_MATCHES) {
481 error("too many matches for %s", key);
482 return 1;
485 store.offset[store.seen] = ftell(config_file);
486 store.seen++;
488 break;
489 case SECTION_SEEN:
491 * What we are looking for is in store.key (both
492 * section and var), and its section part is baselen
493 * long. We found key (again, both section and var).
494 * We would want to know if this key is in the same
495 * section as what we are looking for. We already
496 * know we are in the same section as what should
497 * hold store.key.
499 ep = strrchr(key, '.');
500 section_len = ep - key;
502 if ((section_len != store.baselen) ||
503 memcmp(key, store.key, section_len+1)) {
504 store.state = SECTION_END_SEEN;
505 break;
509 * Do not increment matches: this is no match, but we
510 * just made sure we are in the desired section.
512 store.offset[store.seen] = ftell(config_file);
513 /* fallthru */
514 case SECTION_END_SEEN:
515 case START:
516 if (matches(key, value)) {
517 store.offset[store.seen] = ftell(config_file);
518 store.state = KEY_SEEN;
519 store.seen++;
520 } else {
521 if (strrchr(key, '.') - key == store.baselen &&
522 !strncmp(key, store.key, store.baselen)) {
523 store.state = SECTION_SEEN;
524 store.offset[store.seen] = ftell(config_file);
527 default:
528 break;
530 return 0;
533 static int store_write_section(int fd, const char* key)
535 const char *dot;
536 int i, success;
537 struct strbuf sb = STRBUF_INIT;
539 dot = memchr(key, '.', store.baselen);
540 if (dot) {
541 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
542 for (i = dot - key + 1; i < store.baselen; i++) {
543 if (key[i] == '"' || key[i] == '\\')
544 strbuf_addch(&sb, '\\');
545 strbuf_addch(&sb, key[i]);
547 strbuf_addstr(&sb, "\"]\n");
548 } else {
549 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
552 success = (write_in_full(fd, sb.buf, sb.len) == (ssize_t)sb.len);
553 strbuf_release(&sb);
555 return success;
558 static int store_write_pair(int fd, const char* key, const char* value)
560 int i, success;
561 int length = strlen(key + store.baselen + 1);
562 const char *quote = "";
563 struct strbuf sb = STRBUF_INIT;
566 * Check to see if the value needs to be surrounded with a dq pair.
567 * Note that problematic characters are always backslash-quoted; this
568 * check is about not losing leading or trailing SP and strings that
569 * follow beginning-of-comment characters (i.e. ';' and '#') by the
570 * configuration parser.
572 if (value[0] == ' ')
573 quote = "\"";
574 for (i = 0; value[i]; i++)
575 if (value[i] == ';' || value[i] == '#')
576 quote = "\"";
577 if (i && value[i - 1] == ' ')
578 quote = "\"";
580 strbuf_addf(&sb, "\t%.*s = %s",
581 length, key + store.baselen + 1, quote);
583 for (i = 0; value[i]; i++)
584 switch (value[i]) {
585 case '\n':
586 strbuf_addstr(&sb, "\\n");
587 break;
588 case '\t':
589 strbuf_addstr(&sb, "\\t");
590 break;
591 case '"':
592 case '\\':
593 strbuf_addch(&sb, '\\');
594 default:
595 strbuf_addch(&sb, value[i]);
596 break;
598 strbuf_addf(&sb, "%s\n", quote);
600 success = (write_in_full(fd, sb.buf, sb.len) == (ssize_t)sb.len);
601 strbuf_release(&sb);
603 return success;
606 static ssize_t find_beginning_of_line(const char* contents, size_t size,
607 size_t offset_, int* found_bracket)
609 size_t equal_offset = size, bracket_offset = size;
610 ssize_t offset;
612 contline:
613 for (offset = offset_-2; offset > 0
614 && contents[offset] != '\n'; offset--)
615 switch (contents[offset]) {
616 case '=': equal_offset = offset; break;
617 case ']': bracket_offset = offset; break;
618 default: break;
620 if (offset > 0 && contents[offset-1] == '\\') {
621 offset_ = offset;
622 goto contline;
624 if (bracket_offset < equal_offset) {
625 *found_bracket = 1;
626 offset = bracket_offset+1;
627 } else
628 offset++;
630 return offset;
633 int perf_config_set(const char* key, const char* value)
635 return perf_config_set_multivar(key, value, NULL, 0);
639 * If value==NULL, unset in (remove from) config,
640 * if value_regex!=NULL, disregard key/value pairs where value does not match.
641 * if multi_replace==0, nothing, or only one matching key/value is replaced,
642 * else all matching key/values (regardless how many) are removed,
643 * before the new pair is written.
645 * Returns 0 on success.
647 * This function does this:
649 * - it locks the config file by creating ".perf/config.lock"
651 * - it then parses the config using store_aux() as validator to find
652 * the position on the key/value pair to replace. If it is to be unset,
653 * it must be found exactly once.
655 * - the config file is mmap()ed and the part before the match (if any) is
656 * written to the lock file, then the changed part and the rest.
658 * - the config file is removed and the lock file rename()d to it.
661 int perf_config_set_multivar(const char* key, const char* value,
662 const char* value_regex, int multi_replace)
664 int i, dot;
665 int fd = -1, in_fd;
666 int ret = 0;
667 char* config_filename;
668 const char* last_dot = strrchr(key, '.');
670 if (config_exclusive_filename)
671 config_filename = strdup(config_exclusive_filename);
672 else
673 config_filename = perf_pathdup("config");
676 * Since "key" actually contains the section name and the real
677 * key name separated by a dot, we have to know where the dot is.
680 if (last_dot == NULL) {
681 error("key does not contain a section: %s", key);
682 ret = 2;
683 goto out_free;
685 store.baselen = last_dot - key;
687 store.multi_replace = multi_replace;
690 * Validate the key and while at it, lower case it for matching.
692 store.key = malloc(strlen(key) + 1);
693 dot = 0;
694 for (i = 0; key[i]; i++) {
695 unsigned char c = key[i];
696 if (c == '.')
697 dot = 1;
698 /* Leave the extended basename untouched.. */
699 if (!dot || i > store.baselen) {
700 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
701 error("invalid key: %s", key);
702 free(store.key);
703 ret = 1;
704 goto out_free;
706 c = tolower(c);
707 } else if (c == '\n') {
708 error("invalid key (newline): %s", key);
709 free(store.key);
710 ret = 1;
711 goto out_free;
713 store.key[i] = c;
715 store.key[i] = 0;
718 * If .perf/config does not exist yet, write a minimal version.
720 in_fd = open(config_filename, O_RDONLY);
721 if ( in_fd < 0 ) {
722 free(store.key);
724 if ( ENOENT != errno ) {
725 error("opening %s: %s", config_filename,
726 strerror(errno));
727 ret = 3; /* same as "invalid config file" */
728 goto out_free;
730 /* if nothing to unset, error out */
731 if (value == NULL) {
732 ret = 5;
733 goto out_free;
736 store.key = (char*)key;
737 if (!store_write_section(fd, key) ||
738 !store_write_pair(fd, key, value))
739 goto write_err_out;
740 } else {
741 struct stat st;
742 char *contents;
743 ssize_t contents_sz, copy_begin, copy_end;
744 int new_line = 0;
746 if (value_regex == NULL)
747 store.value_regex = NULL;
748 else {
749 if (value_regex[0] == '!') {
750 store.do_not_match = 1;
751 value_regex++;
752 } else
753 store.do_not_match = 0;
755 store.value_regex = (regex_t*)malloc(sizeof(regex_t));
756 if (regcomp(store.value_regex, value_regex,
757 REG_EXTENDED)) {
758 error("invalid pattern: %s", value_regex);
759 free(store.value_regex);
760 ret = 6;
761 goto out_free;
765 store.offset[0] = 0;
766 store.state = START;
767 store.seen = 0;
770 * After this, store.offset will contain the *end* offset
771 * of the last match, or remain at 0 if no match was found.
772 * As a side effect, we make sure to transform only a valid
773 * existing config file.
775 if (perf_config_from_file(store_aux, config_filename, NULL)) {
776 error("invalid config file %s", config_filename);
777 free(store.key);
778 if (store.value_regex != NULL) {
779 regfree(store.value_regex);
780 free(store.value_regex);
782 ret = 3;
783 goto out_free;
786 free(store.key);
787 if (store.value_regex != NULL) {
788 regfree(store.value_regex);
789 free(store.value_regex);
792 /* if nothing to unset, or too many matches, error out */
793 if ((store.seen == 0 && value == NULL) ||
794 (store.seen > 1 && multi_replace == 0)) {
795 ret = 5;
796 goto out_free;
799 fstat(in_fd, &st);
800 contents_sz = xsize_t(st.st_size);
801 contents = mmap(NULL, contents_sz, PROT_READ,
802 MAP_PRIVATE, in_fd, 0);
803 close(in_fd);
805 if (store.seen == 0)
806 store.seen = 1;
808 for (i = 0, copy_begin = 0; i < store.seen; i++) {
809 if (store.offset[i] == 0) {
810 store.offset[i] = copy_end = contents_sz;
811 } else if (store.state != KEY_SEEN) {
812 copy_end = store.offset[i];
813 } else
814 copy_end = find_beginning_of_line(
815 contents, contents_sz,
816 store.offset[i]-2, &new_line);
818 if (copy_end > 0 && contents[copy_end-1] != '\n')
819 new_line = 1;
821 /* write the first part of the config */
822 if (copy_end > copy_begin) {
823 if (write_in_full(fd, contents + copy_begin,
824 copy_end - copy_begin) <
825 copy_end - copy_begin)
826 goto write_err_out;
827 if (new_line &&
828 write_in_full(fd, "\n", 1) != 1)
829 goto write_err_out;
831 copy_begin = store.offset[i];
834 /* write the pair (value == NULL means unset) */
835 if (value != NULL) {
836 if (store.state == START) {
837 if (!store_write_section(fd, key))
838 goto write_err_out;
840 if (!store_write_pair(fd, key, value))
841 goto write_err_out;
844 /* write the rest of the config */
845 if (copy_begin < contents_sz)
846 if (write_in_full(fd, contents + copy_begin,
847 contents_sz - copy_begin) <
848 contents_sz - copy_begin)
849 goto write_err_out;
851 munmap(contents, contents_sz);
854 ret = 0;
856 out_free:
857 free(config_filename);
858 return ret;
860 write_err_out:
861 goto out_free;
866 * Call this to report error for your variable that should not
867 * get a boolean value (i.e. "[my] var" means "true").
869 int config_error_nonbool(const char *var)
871 return error("Missing value for '%s'", var);