1 /*
2  * Copyright (C) 2017 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 <errno.h>
18 #include <fcntl.h>
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include <algorithm>
27 #include <cctype>
28 #include <charconv>
29 #include <regex>
30 #include <string>
31 #include <string_view>
32 #include <unordered_map>
33 #include <vector>
34 
35 #include <gtest/gtest.h>
36 
37 #include "Options.h"
38 
39 namespace android {
40 namespace gtest_extras {
41 
42 // The total time each test can run before timing out and being killed.
43 constexpr uint64_t kDefaultDeadlineThresholdMs = 90000;
44 
45 // The total time each test can run before a warning is issued.
46 constexpr uint64_t kDefaultSlowThresholdMs = 2000;
47 
48 const std::unordered_map<std::string, Options::ArgInfo> Options::kArgs = {
49     {"deadline_threshold_ms", {FLAG_REQUIRES_VALUE, &Options::SetNumeric}},
50     {"slow_threshold_ms", {FLAG_REQUIRES_VALUE, &Options::SetNumeric}},
51     {"gtest_list_tests", {FLAG_NONE, &Options::SetBool}},
52     {"gtest_filter", {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE, &Options::SetString}},
53     {"gtest_flagfile", {FLAG_REQUIRES_VALUE, &Options::SetString}},
54     {
55         "gtest_repeat",
56         {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE, &Options::SetIterations},
57     },
58     {"gtest_output", {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE, &Options::SetXmlFile}},
59     {"gtest_print_time", {FLAG_ENVIRONMENT_VARIABLE | FLAG_OPTIONAL_VALUE, &Options::SetPrintTime}},
60     {
61         "gtest_also_run_disabled_tests",
62         {FLAG_ENVIRONMENT_VARIABLE | FLAG_CHILD, &Options::SetBool},
63     },
64     {"gtest_color",
65      {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE | FLAG_CHILD, &Options::SetString}},
66     {"gtest_death_test_style",
67      {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE | FLAG_CHILD, nullptr}},
68     {"gtest_break_on_failure", {FLAG_ENVIRONMENT_VARIABLE, &Options::SetBool}},
69     {"gtest_catch_exceptions", {FLAG_ENVIRONMENT_VARIABLE | FLAG_INCOMPATIBLE, nullptr}},
70     {"gtest_random_seed", {FLAG_ENVIRONMENT_VARIABLE | FLAG_INCOMPATIBLE, nullptr}},
71     {"gtest_shuffle", {FLAG_ENVIRONMENT_VARIABLE | FLAG_INCOMPATIBLE, nullptr}},
72     {"gtest_stream_result_to", {FLAG_ENVIRONMENT_VARIABLE | FLAG_INCOMPATIBLE, nullptr}},
73     {"gtest_throw_on_failure", {FLAG_ENVIRONMENT_VARIABLE, &Options::SetBool}},
74     {"gtest_shard_index",
75      {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE, &Options::SetNumericEnvOnly}},
76     {"gtest_total_shards",
77      {FLAG_ENVIRONMENT_VARIABLE | FLAG_REQUIRES_VALUE, &Options::SetNumericEnvOnly}},
78     // This does nothing, only added so that passing this option does not exit.
79     {"gtest_format", {FLAG_NONE, &Options::SetBool}},
80 };
81 
PrintError(const std::string & arg,std::string_view msg,bool from_env)82 static void PrintError(const std::string& arg, std::string_view msg, bool from_env) {
83   if (from_env) {
84     std::string variable(arg);
85     std::transform(variable.begin(), variable.end(), variable.begin(),
86                    [](char c) { return std::toupper(c); });
87     printf("env[%s] %s\n", variable.c_str(), msg.data());
88   } else if (arg[0] == '-') {
89     printf("%s %s\n", arg.c_str(), msg.data());
90   } else {
91     printf("--%s %s\n", arg.c_str(), msg.data());
92   }
93 }
94 
95 template <typename IntType>
GetNumeric(const std::string & arg,const std::string & value,IntType * numeric_value,bool from_env)96 static bool GetNumeric(const std::string& arg, const std::string& value, IntType* numeric_value,
97                        bool from_env) {
98   auto result = std::from_chars(value.c_str(), value.c_str() + value.size(), *numeric_value, 10);
99   if (result.ec == std::errc::result_out_of_range) {
100     PrintError(arg, std::string("value overflows (") + value + ")", from_env);
101     return false;
102   } else if (result.ec == std::errc::invalid_argument || result.ptr == nullptr ||
103              *result.ptr != '\0') {
104     PrintError(arg, std::string("value is not formatted as a numeric value (") + value + ")",
105                from_env);
106     return false;
107   }
108   return true;
109 }
110 
SetPrintTime(const std::string &,const std::string & value,bool)111 bool Options::SetPrintTime(const std::string&, const std::string& value, bool) {
112   if (!value.empty() && strtol(value.c_str(), nullptr, 10) == 0) {
113     bools_.find("gtest_print_time")->second = false;
114   }
115   return true;
116 }
117 
SetNumeric(const std::string & arg,const std::string & value,bool from_env)118 bool Options::SetNumeric(const std::string& arg, const std::string& value, bool from_env) {
119   uint64_t* numeric = &numerics_.find(arg)->second;
120   if (!GetNumeric<uint64_t>(arg, value, numeric, from_env)) {
121     return false;
122   }
123   if (*numeric == 0) {
124     PrintError(arg, "requires a number greater than zero.", from_env);
125     return false;
126   }
127   return true;
128 }
129 
SetNumericEnvOnly(const std::string & arg,const std::string & value,bool from_env)130 bool Options::SetNumericEnvOnly(const std::string& arg, const std::string& value, bool from_env) {
131   if (!from_env) {
132     PrintError(arg, "is only supported as an environment variable.", false);
133     return false;
134   }
135   uint64_t* numeric = &numerics_.find(arg)->second;
136   if (!GetNumeric<uint64_t>(arg, value, numeric, from_env)) {
137     return false;
138   }
139   return true;
140 }
141 
SetBool(const std::string & arg,const std::string &,bool)142 bool Options::SetBool(const std::string& arg, const std::string&, bool) {
143   bools_.find(arg)->second = true;
144   return true;
145 }
146 
SetIterations(const std::string & arg,const std::string & value,bool from_env)147 bool Options::SetIterations(const std::string& arg, const std::string& value, bool from_env) {
148   if (!GetNumeric<int>(arg, value, &num_iterations_, from_env)) {
149     return false;
150   }
151   return true;
152 }
153 
SetString(const std::string & arg,const std::string & value,bool)154 bool Options::SetString(const std::string& arg, const std::string& value, bool) {
155   strings_.find(arg)->second = value;
156   return true;
157 }
158 
SetXmlFile(const std::string & arg,const std::string & value,bool from_env)159 bool Options::SetXmlFile(const std::string& arg, const std::string& value, bool from_env) {
160   if (value.substr(0, 4) != "xml:") {
161     PrintError(arg, "only supports an xml output file.", from_env);
162     return false;
163   }
164   std::string xml_file(value.substr(4));
165   if (xml_file.empty()) {
166     PrintError(arg, "requires a file name after xml:", from_env);
167     return false;
168   }
169   // Need an absolute file.
170   if (xml_file[0] != '/') {
171     char* cwd = getcwd(nullptr, 0);
172     if (cwd == nullptr) {
173       PrintError(arg,
174                  std::string("cannot get absolute pathname, getcwd() is failing: ") +
175                      strerror(errno) + '\n',
176                  from_env);
177       return false;
178     }
179     xml_file = std::string(cwd) + '/' + xml_file;
180     free(cwd);
181   }
182 
183   // If the output file is a directory, add the name of a file.
184   if (xml_file.back() == '/') {
185     xml_file += "test_details.xml";
186   }
187   strings_.find("xml_file")->second = xml_file;
188   return true;
189 }
190 
HandleArg(const std::string & arg,const std::string & value,const ArgInfo & info,bool from_env)191 bool Options::HandleArg(const std::string& arg, const std::string& value, const ArgInfo& info,
192                         bool from_env) {
193   if (info.flags & FLAG_INCOMPATIBLE) {
194     PrintError(arg, "is not compatible with isolation runs.", from_env);
195     return false;
196   }
197 
198   if (info.flags & FLAG_TAKES_VALUE) {
199     if ((info.flags & FLAG_REQUIRES_VALUE) && value.empty()) {
200       PrintError(arg, "requires an argument.", from_env);
201       return false;
202     }
203 
204     if (info.func != nullptr && !(this->*(info.func))(arg, value, from_env)) {
205       return false;
206     }
207   } else if (!value.empty()) {
208     PrintError(arg, "does not take an argument.", from_env);
209     return false;
210   } else if (info.func != nullptr) {
211     return (this->*(info.func))(arg, value, from_env);
212   }
213   return true;
214 }
215 
ReadFileToString(const std::string & file,std::string * contents)216 static bool ReadFileToString(const std::string& file, std::string* contents) {
217   int fd = static_cast<int>(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC)));
218   if (fd == -1) {
219     return false;
220   }
221   char buf[4096];
222   ssize_t bytes_read;
223   while ((bytes_read = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)))) > 0) {
224     contents->append(buf, static_cast<size_t>(bytes_read));
225   }
226   close(fd);
227   return true;
228 }
229 
ProcessFlagfile(const std::string & file,std::vector<char * > * child_args)230 bool Options::ProcessFlagfile(const std::string& file, std::vector<char*>* child_args) {
231   std::string contents;
232   if (!ReadFileToString(file, &contents)) {
233     printf("Unable to read data from file %s\n", file.c_str());
234     return false;
235   }
236 
237   std::regex flag_regex("^\\s*(\\S.*\\S)\\s*$");
238   std::regex empty_line_regex("^\\s*$");
239   size_t idx = 0;
240   while (idx < contents.size()) {
241     size_t newline_idx = contents.find('\n', idx);
242     if (newline_idx == std::string::npos) {
243       newline_idx = contents.size();
244     }
245     std::string line(&contents[idx], newline_idx - idx);
246     idx = newline_idx + 1;
247     std::smatch match;
248     if (std::regex_match(line, match, flag_regex)) {
249       line = match[1];
250     } else if (std::regex_match(line, match, empty_line_regex)) {
251       // Skip lines with only whitespace.
252       continue;
253     }
254     if (!ProcessSingle(line.c_str(), child_args, false)) {
255       return false;
256     }
257   }
258   return true;
259 }
260 
ProcessSingle(const char * arg,std::vector<char * > * child_args,bool allow_flagfile)261 bool Options::ProcessSingle(const char* arg, std::vector<char*>* child_args, bool allow_flagfile) {
262   if (strncmp("--", arg, 2) != 0) {
263     if (arg[0] == '-') {
264       printf("Unknown argument: %s\n", arg);
265       return false;
266     } else {
267       printf("Unexpected argument '%s'\n", arg);
268       return false;
269     }
270   }
271 
272   // See if this is a name=value argument.
273   std::string name;
274   std::string value;
275   const char* equal = strchr(arg, '=');
276   if (equal != nullptr) {
277     name = std::string(&arg[2], static_cast<size_t>(equal - arg) - 2);
278     value = equal + 1;
279   } else {
280     name = &arg[2];
281   }
282   auto entry = kArgs.find(name);
283   if (entry == kArgs.end()) {
284     printf("Unknown argument: %s\n", arg);
285     return false;
286   }
287 
288   if (entry->second.flags & FLAG_CHILD) {
289     child_args->push_back(strdup(arg));
290   }
291 
292   if (!HandleArg(name, value, entry->second)) {
293     return false;
294   }
295 
296   // Special case, if gtest_flagfile is set, then we need to read the
297   // file and treat each line as a flag.
298   if (name == "gtest_flagfile") {
299     if (!allow_flagfile) {
300       printf("Argument: %s is not allowed in flag file.\n", arg);
301       return false;
302     }
303     if (!ProcessFlagfile(value, child_args)) {
304       return false;
305     }
306   }
307 
308   return true;
309 }
310 
Process(const std::vector<const char * > & args,std::vector<char * > * child_args)311 bool Options::Process(const std::vector<const char*>& args, std::vector<char*>* child_args) {
312   // Initialize the variables.
313   job_count_ = static_cast<size_t>(sysconf(_SC_NPROCESSORS_ONLN));
314   num_iterations_ = ::testing::GTEST_FLAG(repeat);
315   stop_on_error_ = false;
316   numerics_.clear();
317   numerics_["deadline_threshold_ms"] = kDefaultDeadlineThresholdMs;
318   numerics_["slow_threshold_ms"] = kDefaultSlowThresholdMs;
319   numerics_["gtest_shard_index"] = 0;
320   numerics_["gtest_total_shards"] = 0;
321   strings_.clear();
322   strings_["gtest_color"] = ::testing::GTEST_FLAG(color);
323   strings_["xml_file"] = ::testing::GTEST_FLAG(output);
324   strings_["gtest_filter"] = "";
325   strings_["gtest_flagfile"] = "";
326   bools_.clear();
327   bools_["gtest_print_time"] = ::testing::GTEST_FLAG(print_time);
328   bools_["gtest_also_run_disabled_tests"] = ::testing::GTEST_FLAG(also_run_disabled_tests);
329   bools_["gtest_list_tests"] = false;
330   bools_["gtest_break_on_failure"] = false;
331   bools_["gtest_throw_on_failure"] = false;
332 
333   // This does nothing, only added so that passing this option does not exit.
334   bools_["gtest_format"] = true;
335 
336   // Loop through all of the possible environment variables.
337   for (const auto& entry : kArgs) {
338     if (entry.second.flags & FLAG_ENVIRONMENT_VARIABLE) {
339       std::string variable(entry.first);
340       std::transform(variable.begin(), variable.end(), variable.begin(),
341                      [](char c) { return std::toupper(c); });
342       char* env = getenv(variable.c_str());
343       if (env == nullptr) {
344         continue;
345       }
346       std::string value(env);
347       if (!HandleArg(entry.first, value, entry.second, true)) {
348         return false;
349       }
350     }
351   }
352 
353   child_args->push_back(strdup(args[0]));
354 
355   // Assumes the first value is not an argument, so skip it.
356   for (size_t i = 1; i < args.size(); i++) {
357     // Special handle of -j or -jXX. This flag is not allowed to be present
358     // in a --gtest_flagfile.
359     if (strncmp(args[i], "-j", 2) == 0) {
360       const char* value = &args[i][2];
361       if (*value == '\0') {
362         // Get the next argument.
363         if (i == args.size() - 1) {
364           printf("-j requires an argument.\n");
365           return false;
366         }
367         i++;
368         value = args[i];
369       }
370       if (!GetNumeric<size_t>("-j", value, &job_count_, false)) {
371         return false;
372       }
373     } else {
374       if (!ProcessSingle(args[i], child_args, true)) {
375         return false;
376       }
377     }
378   }
379 
380   if (bools_["gtest_break_on_failure"] || bools_["gtest_throw_on_failure"]) {
381     stop_on_error_ = true;
382   }
383 
384   return true;
385 }
386 
387 }  // namespace gtest_extras
388 }  // namespace android
389