xref: /llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/argp_parse.c (revision cc6b86e175da1cf4fa7de98ee99bb9e55e16ac7d)
1 // RUN: %clang %s -o %t && %run %t -o baz
2 
3 // argp_parse is glibc specific.
4 // UNSUPPORTED: android, target={{.*(freebsd|netbsd).*}}
5 
6 #include <argp.h>
7 #include <assert.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 struct test {
12   const char *option_value;
13 };
14 
15 static const struct argp_option options[] = {
16     {"option", 'o', "OPTION", 0, "Option", 0},
17     {NULL, 0, NULL, 0, NULL, 0},
18 };
19 
parser(int key,char * arg,struct argp_state * state)20 static error_t parser(int key, char *arg, struct argp_state *state) {
21   if (key == 'o') {
22     ((struct test *)(state->input))->option_value = arg;
23     return 0;
24   }
25   return ARGP_ERR_UNKNOWN;
26 }
27 
28 static struct argp argp = {.options = options, .parser = parser};
29 
test_nulls(char * argv0)30 void test_nulls(char *argv0) {
31   char *argv[] = {argv0, NULL};
32   int res = argp_parse(NULL, 1, argv, 0, NULL, NULL);
33   assert(res == 0);
34 }
35 
test_synthetic(char * argv0)36 void test_synthetic(char *argv0) {
37   char *argv[] = {argv0, "-o", "foo", "bar", NULL};
38   struct test t = {NULL};
39   int arg_index;
40   int res = argp_parse(&argp, 4, argv, 0, &arg_index, &t);
41   assert(res == 0);
42   assert(arg_index == 3);
43   assert(strcmp(t.option_value, "foo") == 0);
44 }
45 
test_real(int argc,char ** argv)46 void test_real(int argc, char **argv) {
47   struct test t = {NULL};
48   int arg_index;
49   int res = argp_parse(&argp, argc, argv, 0, &arg_index, &t);
50   assert(res == 0);
51   assert(arg_index == 3);
52   assert(strcmp(t.option_value, "baz") == 0);
53 }
54 
main(int argc,char ** argv)55 int main(int argc, char **argv) {
56   test_nulls(argv[0]);
57   test_synthetic(argv[0]);
58   test_real(argc, argv);
59   return EXIT_SUCCESS;
60 }
61