1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "perfetto/ext/base/getopt_compat.h"
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <vector>
24
25 #include "perfetto/base/logging.h"
26
27 namespace perfetto {
28 namespace base {
29 namespace getopt_compat {
30
31 char* optarg = nullptr;
32 int optind = 0;
33
34 namespace {
35
36 char* nextchar = nullptr;
37
LookupLongOpt(const std::vector<option> & opts,const char * name,size_t len)38 const option* LookupLongOpt(const std::vector<option>& opts,
39 const char* name,
40 size_t len) {
41 for (const option& opt : opts) {
42 if (strncmp(opt.name, name, len) == 0 && strlen(opt.name) == len)
43 return &opt;
44 }
45 return nullptr;
46 }
47
LookupShortOpt(const std::vector<option> & opts,char c)48 const option* LookupShortOpt(const std::vector<option>& opts, char c) {
49 for (const option& opt : opts) {
50 if (opt.name == nullptr && opt.val == c)
51 return &opt;
52 }
53 return nullptr;
54 }
55
ParseOpts(const char * shortopts,const option * longopts,std::vector<option> * res)56 bool ParseOpts(const char* shortopts,
57 const option* longopts,
58 std::vector<option>* res) {
59 // Parse long options first.
60 for (const option* lopt = longopts; lopt && lopt->name; lopt++) {
61 PERFETTO_CHECK(lopt->flag == nullptr);
62 PERFETTO_CHECK(lopt->has_arg == no_argument ||
63 lopt->has_arg == required_argument);
64 res->emplace_back(*lopt);
65 }
66
67 // Merge short options.
68 for (const char* sopt = shortopts; sopt && *sopt;) {
69 const size_t idx = static_cast<size_t>(sopt - shortopts);
70 char c = *sopt++;
71 bool valid = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
72 (c >= '0' && c <= '9');
73 if (!valid) {
74 fprintf(stderr,
75 "Error parsing shortopts. Unexpected char '%c' at offset %zu\n",
76 c, idx);
77 return false;
78 }
79 res->emplace_back();
80 option& opt = res->back();
81 opt.val = c;
82 opt.has_arg = no_argument;
83 if (*sopt == ':') {
84 opt.has_arg = required_argument;
85 ++sopt;
86 }
87 }
88 return true;
89 }
90
91 } // namespace
92
getopt_long(int argc,char ** argv,const char * shortopts,const option * longopts,std::nullptr_t)93 int getopt_long(int argc,
94 char** argv,
95 const char* shortopts,
96 const option* longopts,
97 std::nullptr_t /*longind*/) {
98 std::vector<option> opts;
99 optarg = nullptr;
100
101 if (optind == 0)
102 optind = 1;
103
104 if (optind >= argc)
105 return -1;
106
107 if (!ParseOpts(shortopts, longopts, &opts))
108 return '?';
109
110 char* arg = argv[optind];
111
112 if (!nextchar) {
113 // If |nextchar| is null we are NOT in the middle of a short option and we
114 // should parse the next argv.
115 if (strncmp(arg, "--", 2) == 0 && strlen(arg) > 2) {
116 // A --long option.
117 arg += 2;
118 char* sep = strchr(arg, '=');
119 optind++;
120
121 size_t len = sep ? static_cast<size_t>(sep - arg) : strlen(arg);
122 const option* opt = LookupLongOpt(opts, arg, len);
123 if (!opt) {
124 fprintf(stderr, "unrecognized option '--%s'\n", arg);
125 return '?';
126 }
127
128 if (opt->has_arg == no_argument) {
129 if (sep) {
130 fprintf(stderr, "option '--%s' doesn't allow an argument\n", arg);
131 return '?';
132 } else {
133 return opt->val;
134 }
135 } else if (opt->has_arg == required_argument) {
136 if (sep) {
137 optarg = sep + 1;
138 return opt->val;
139 } else if (optind >= argc) {
140 fprintf(stderr, "option '--%s' requires an argument\n", arg);
141 return '?';
142 } else {
143 optarg = argv[optind++];
144 return opt->val;
145 }
146 }
147 // has_arg must be either |no_argument| or |required_argument|. We
148 // shoulnd't get here unless the check in ParseOpts() has a bug.
149 PERFETTO_CHECK(false);
150 } // if (arg ~= "--*").
151
152 if (strlen(arg) > 1 && arg[0] == '-' && arg[1] != '-') {
153 // A sequence of short options. Parsing logic continues below.
154 nextchar = &arg[1];
155 }
156 } // if(!nextchar)
157
158 if (nextchar) {
159 // At this point either:
160 // 1. This is the first char of a sequence of short options, and we fell
161 // through here from the lines above.
162 // 2. This is the N (>1) char of a sequence of short options, and we got
163 // here from a new getopt() call to getopt().
164 const char cur_char = *nextchar;
165 PERFETTO_CHECK(cur_char != '\0');
166
167 // Advance the option char in any case, before we start reasoning on them.
168 // if we got to the end of the "-abc" sequence, increment optind so the next
169 // getopt() call resumes from the next argv argument.
170 if (*(++nextchar) == '\0') {
171 nextchar = nullptr;
172 ++optind;
173 }
174
175 const option* opt = LookupShortOpt(opts, cur_char);
176 if (!opt) {
177 fprintf(stderr, "invalid option -- '%c'\n", cur_char);
178 return '?';
179 }
180 if (opt->has_arg == no_argument) {
181 return cur_char;
182 } else if (opt->has_arg == required_argument) {
183 // This is a subtle getopt behavior. Say you call `tar -fx`, there are
184 // two cases:
185 // 1. If 'f' is no_argument then 'x' (and anything else after) is
186 // interpreted as an independent argument (like `tar -f -x`).
187 // 2. If 'f' is required_argument, than everything else after the 'f'
188 // is interpreted as the option argument (like `tar -f x`)
189 if (!nextchar) {
190 // Case 1.
191 if (optind >= argc) {
192 fprintf(stderr, "option requires an argument -- '%c'\n", cur_char);
193 return '?';
194 } else {
195 optarg = argv[optind++];
196 return cur_char;
197 }
198 } else {
199 // Case 2.
200 optarg = nextchar;
201 nextchar = nullptr;
202 optind++;
203 return cur_char;
204 }
205 }
206 PERFETTO_CHECK(false);
207 } // if (nextchar)
208
209 // If we get here, we found the first non-option argument. Stop here.
210
211 if (strcmp(arg, "--") == 0)
212 optind++;
213
214 return -1;
215 }
216
getopt(int argc,char ** argv,const char * shortopts)217 int getopt(int argc, char** argv, const char* shortopts) {
218 return getopt_long(argc, argv, shortopts, nullptr, nullptr);
219 }
220
221 } // namespace getopt_compat
222 } // namespace base
223 } // namespace perfetto
224