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 <err.h>
18 #include <getopt.h>
19 #include <inttypes.h>
20 #include <math.h>
21 #include <sys/resource.h>
22 
23 #include <map>
24 #include <mutex>
25 #include <sstream>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 #include <android-base/file.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/strings.h>
33 #include <benchmark/benchmark.h>
34 #include <tinyxml2.h>
35 #include "util.h"
36 
37 #define _STR(x) #x
38 #define STRINGFY(x) _STR(x)
39 
40 static const std::vector<int> kCommonSizes{
41   8,
42   16,
43   32,
44   64,
45   512,
46   1 * KB,
47   8 * KB,
48   16 * KB,
49   32 * KB,
50   64 * KB,
51   128 * KB,
52 };
53 
54 static const std::vector<int> kSmallSizes{
55   // Increment by 1
56   1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
57   // Increment by 8
58   24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144,
59   // Increment by 16
60   160, 176, 192, 208, 224, 240, 256,
61 };
62 
63 static const std::vector<int> kMediumSizes{
64   512,
65   1 * KB,
66   8 * KB,
67   16 * KB,
68   32 * KB,
69   64 * KB,
70   128 * KB,
71 };
72 
73 static const std::vector<int> kLargeSizes{
74   256 * KB,
75   512 * KB,
76   1024 * KB,
77   2048 * KB,
78 };
79 
80 static std::map<std::string, const std::vector<int> &> kSizes{
81   { "SMALL",  kSmallSizes },
82   { "MEDIUM", kMediumSizes },
83   { "LARGE",  kLargeSizes },
84 };
85 
86 std::map<std::string, std::pair<benchmark_func_t, std::string>> g_str_to_func;
87 
88 std::mutex g_map_lock;
89 
90 static struct option g_long_options[] =
91 {
92   {"bionic_cpu", required_argument, nullptr, 'c'},
93   {"bionic_xml", required_argument, nullptr, 'x'},
94   {"bionic_iterations", required_argument, nullptr, 'i'},
95   {"bionic_extra", required_argument, nullptr, 'a'},
96   {"help", no_argument, nullptr, 'h'},
97   {nullptr, 0, nullptr, 0},
98 };
99 
100 typedef std::vector<std::vector<int64_t>> args_vector_t;
101 
Usage()102 void Usage() {
103   printf("Usage:\n");
104   printf("bionic_benchmarks [--bionic_cpu=<cpu_to_isolate>]\n");
105   printf("                  [--bionic_xml=<path_to_xml>]\n");
106   printf("                  [--bionic_iterations=<num_iter>]\n");
107   printf("                  [--bionic_extra=\"<fn_name> <arg1> <arg 2> ...\"]\n");
108   printf("                  [<Google benchmark flags>]\n");
109   printf("Google benchmark flags:\n");
110 
111   int fake_argc = 2;
112   char argv0[] = "bionic_benchmarks";
113   char argv1[] = "--help";
114   char* fake_argv[3] {argv0, argv1, nullptr};
115   benchmark::Initialize(&fake_argc, fake_argv);
116   exit(1);
117 }
118 
119 // This function removes any bionic benchmarks command line arguments by checking them
120 // against g_long_options. It fills new_argv with the filtered args.
SanitizeOpts(int argc,char ** argv,std::vector<char * > * new_argv)121 void SanitizeOpts(int argc, char** argv, std::vector<char*>* new_argv) {
122   // TO THOSE ADDING OPTIONS: This currently doesn't support optional arguments.
123   (*new_argv)[0] = argv[0];
124   for (int i = 1; i < argc; ++i) {
125     char* optarg = argv[i];
126     size_t opt_idx = 0;
127 
128     // Iterate through g_long_options until either we hit the end or we have a match.
129     for (opt_idx = 0; g_long_options[opt_idx].name &&
130                       strncmp(g_long_options[opt_idx].name, optarg + 2,
131                               strlen(g_long_options[opt_idx].name)); ++opt_idx) {
132     }
133 
134     if (!g_long_options[opt_idx].name) {
135       new_argv->push_back(optarg);
136     } else {
137       if (g_long_options[opt_idx].has_arg == required_argument) {
138         // If the arg was passed in with an =, it spans one char *.
139         // Otherwise, we skip a spot for the argument.
140         if (!strchr(optarg, '=')) {
141           i++;
142         }
143       }
144     }
145   }
146   new_argv->push_back(nullptr);
147 }
148 
ParseOpts(int argc,char ** argv)149 bench_opts_t ParseOpts(int argc, char** argv) {
150   bench_opts_t opts;
151   int opt;
152   int option_index = 0;
153 
154   // To make this parser handle the benchmark options silently:
155   extern int opterr;
156   opterr = 0;
157 
158   while ((opt = getopt_long(argc, argv, "c:x:i:a:h", g_long_options, &option_index)) != -1) {
159     if (opt == -1) {
160       break;
161     }
162     switch (opt) {
163       case 'c':
164         if (*optarg) {
165           char* check_null;
166           opts.cpu_to_lock = strtol(optarg, &check_null, 10);
167           if (*check_null) {
168             errx(1, "ERROR: Args %s is not a valid integer.", optarg);
169           }
170         } else {
171           printf("ERROR: no argument specified for bionic_cpu\n");
172           Usage();
173         }
174         break;
175       case 'x':
176         if (*optarg) {
177           opts.xmlpath = optarg;
178         } else {
179           printf("ERROR: no argument specified for bionic_xml\n");
180           Usage();
181         }
182         break;
183       case 'a':
184         if (*optarg) {
185           opts.extra_benchmarks.push_back(optarg);
186         } else {
187           printf("ERROR: no argument specified for bionic_extra\n");
188           Usage();
189         }
190         break;
191       case 'i':
192         if (*optarg){
193           char* check_null;
194           opts.num_iterations = strtol(optarg, &check_null, 10);
195           if (*check_null != '\0' or opts.num_iterations < 0) {
196             errx(1, "ERROR: Args %s is not a valid number of iterations.", optarg);
197           }
198         } else {
199           printf("ERROR: no argument specified for bionic_iterations\n");
200           Usage();
201         }
202         break;
203       case 'h':
204         Usage();
205         break;
206       case '?':
207         break;
208       default:
209         exit(1);
210     }
211   }
212   return opts;
213 }
214 
215 // This is a wrapper for every function call for per-benchmark cpu pinning.
LockAndRun(benchmark::State & state,benchmark_func_t func_to_bench,int cpu_to_lock)216 void LockAndRun(benchmark::State& state, benchmark_func_t func_to_bench, int cpu_to_lock) {
217   if (cpu_to_lock >= 0) LockToCPU(cpu_to_lock);
218 
219   // To avoid having to link against Google benchmarks in libutil,
220   // benchmarks are kept without parameter information, necessitating this cast.
221   reinterpret_cast<void(*) (benchmark::State&)>(func_to_bench)(state);
222 }
223 
224 static constexpr char kOnebufManualStr[] = "AT_ONEBUF_MANUAL_ALIGN_";
225 static constexpr char kTwobufManualStr[] = "AT_TWOBUF_MANUAL_ALIGN1_";
226 
ParseOnebufManualStr(std::string & arg,args_vector_t * to_populate)227 static bool ParseOnebufManualStr(std::string& arg, args_vector_t* to_populate) {
228   // The format of this is:
229   //   AT_ONEBUF_MANUAL_ALIGN_XX_SIZE_YY
230   // Where:
231   //   XX is the alignment
232   //   YY is the size
233   // The YY size can be either a number or a string representing the pre-defined
234   // sets of values:
235   //   SMALL (for values between 1 and 256)
236   //   MEDIUM (for values between 512 and 128KB)
237   //   LARGE (for values between 256KB and 2048KB)
238   int64_t align;
239   int64_t size;
240   char sizes[32] = { 0 };
241   int ret;
242 
243   ret = sscanf(arg.c_str(), "AT_ONEBUF_MANUAL_ALIGN_%" SCNd64 "_SIZE_%" SCNd64,
244                &align, &size);
245   if (ret == 1) {
246     ret = sscanf(arg.c_str(), "AT_ONEBUF_MANUAL_ALIGN_%" SCNd64 "_SIZE_"
247                               "%" STRINGFY(sizeof(sizes)-1) "s", &align, sizes);
248   }
249   if (ret != 2) {
250     return false;
251   }
252 
253   // Verify the alignment is powers of 2.
254   if (align != 0 && (align & (align - 1)) != 0) {
255     return false;
256   }
257 
258   auto sit = kSizes.find(sizes);
259   if (sit == kSizes.cend()) {
260     to_populate->push_back({size, align});
261   } else {
262     for (auto ssize : sit->second) {
263       to_populate->push_back({ssize, align});
264     }
265   }
266   return true;
267 }
268 
ParseTwobufManualStr(std::string & arg,args_vector_t * to_populate)269 static bool ParseTwobufManualStr(std::string& arg, args_vector_t* to_populate) {
270   // The format of this is:
271   //   AT_TWOBUF_MANUAL_ALIGN1_XX_ALIGN2_YY_SIZE_ZZ
272   // Where:
273   //   XX is the alignment of the first argument
274   //   YY is the alignment of the second argument
275   //   ZZ is the size
276   // The ZZ size can be either a number or a string representing the pre-defined
277   // sets of values:
278   //   SMALL (for values between 1 and 256)
279   //   MEDIUM (for values between 512 and 128KB)
280   //   LARGE (for values between 256KB and 2048KB)
281   int64_t align1;
282   int64_t align2;
283   int64_t size;
284   char sizes[32] = { 0 };
285   int ret;
286 
287   ret = sscanf(arg.c_str(), "AT_TWOBUF_MANUAL_ALIGN1_%" SCNd64 "_ALIGN2_%" SCNd64 "_SIZE_%" SCNd64,
288                             &align1, &align2, &size);
289   if (ret == 2) {
290     ret = sscanf(arg.c_str(), "AT_TWOBUF_MANUAL_ALIGN1_%" SCNd64 "_ALIGN2_%" SCNd64 "_SIZE_"
291                                "%" STRINGFY(sizeof(sizes)-1) "s",
292                                &align1, &align2, sizes);
293   }
294   if (ret != 3) {
295     return false;
296   }
297 
298   // Verify the alignments are powers of 2.
299   if ((align1 != 0 && (align1 & (align1 - 1)) != 0)
300       || (align2 != 0 && (align2 & (align2 - 1)) != 0)) {
301     return false;
302   }
303 
304   auto sit = kSizes.find(sizes);
305   if (sit == kSizes.cend()) {
306     to_populate->push_back({size, align1, align2});
307   } else {
308     for (auto ssize : sit->second) {
309       to_populate->push_back({ssize, align1, align2});
310     }
311   }
312   return true;
313 }
314 
ResolveArgs(args_vector_t * to_populate,std::string args,std::map<std::string,args_vector_t> & args_shorthand)315 args_vector_t* ResolveArgs(args_vector_t* to_populate, std::string args,
316                            std::map<std::string, args_vector_t>& args_shorthand) {
317   // args is either a space-separated list of ints, a macro name, or
318   // special free form macro.
319   // To ease formatting in XML files, args is left and right trimmed.
320   if (args_shorthand.count(args)) {
321     return &args_shorthand[args];
322   }
323   // Check for free form macro.
324   if (android::base::StartsWith(args, kOnebufManualStr)) {
325     if (!ParseOnebufManualStr(args, to_populate)) {
326       errx(1, "ERROR: Bad format of macro %s, should be AT_ONEBUF_MANUAL_ALIGN_XX_SIZE_YY",
327            args.c_str());
328     }
329     return to_populate;
330   } else if (android::base::StartsWith(args, kTwobufManualStr)) {
331     if (!ParseTwobufManualStr(args, to_populate)) {
332       errx(1,
333            "ERROR: Bad format of macro %s, should be AT_TWOBUF_MANUAL_ALIGN1_XX_ALIGNE2_YY_SIZE_ZZ",
334            args.c_str());
335     }
336     return to_populate;
337   }
338 
339   std::string trimmed_args = android::base::Trim(args);
340   if (!trimmed_args.empty()) {
341     std::stringstream sstream(trimmed_args);
342     std::string argstr;
343     while (sstream >> argstr) {
344       char* check_null;
345       int converted = static_cast<int>(strtol(argstr.c_str(), &check_null, 10));
346       if (*check_null == '\0') {
347         to_populate->emplace_back(std::vector<int64_t>{converted});
348         continue;
349       } else if (*check_null == '/') {
350         // The only supported format with a / is \d+(/\d+)\s*. Example 8/8/8 or 16/23.
351         std::vector<int64_t> test_args{converted};
352         while (true) {
353           converted = static_cast<int>(strtol(check_null + 1, &check_null, 10));
354           test_args.push_back(converted);
355           if (*check_null == '\0') {
356             to_populate->emplace_back(std::move(test_args));
357             break;
358           } else if (*check_null != '/') {
359             errx(1, "ERROR: Args str %s contains an invalid macro or int.", args.c_str());
360           }
361         }
362       } else {
363         errx(1, "ERROR: Args str %s contains an invalid macro or int.", args.c_str());
364       }
365     }
366   } else {
367     // No arguments, only the base benchmark.
368     to_populate->emplace_back(std::vector<int64_t>{});
369   }
370   return to_populate;
371 }
372 
RegisterGoogleBenchmarks(bench_opts_t primary_opts,bench_opts_t secondary_opts,const std::string & fn_name,args_vector_t * run_args)373 void RegisterGoogleBenchmarks(bench_opts_t primary_opts, bench_opts_t secondary_opts,
374                               const std::string& fn_name, args_vector_t* run_args) {
375   if (g_str_to_func.find(fn_name) == g_str_to_func.end()) {
376     errx(1, "ERROR: No benchmark for function %s", fn_name.c_str());
377   }
378   long iterations_to_use = primary_opts.num_iterations ? primary_opts.num_iterations :
379                                                          secondary_opts.num_iterations;
380   int cpu_to_use = -1;
381   if (primary_opts.cpu_to_lock >= 0) {
382     cpu_to_use = primary_opts.cpu_to_lock;
383 
384   } else if (secondary_opts.cpu_to_lock >= 0) {
385     cpu_to_use = secondary_opts.cpu_to_lock;
386   }
387 
388   benchmark_func_t benchmark_function = g_str_to_func.at(fn_name).first;
389   for (const std::vector<int64_t>& args : (*run_args)) {
390     auto registration = benchmark::RegisterBenchmark(fn_name.c_str(), LockAndRun,
391                                                      benchmark_function,
392                                                      cpu_to_use)->Args(args);
393     if (iterations_to_use > 0) {
394       registration->Iterations(iterations_to_use);
395     }
396   }
397 }
398 
RegisterCliBenchmarks(bench_opts_t cmdline_opts,std::map<std::string,args_vector_t> & args_shorthand)399 void RegisterCliBenchmarks(bench_opts_t cmdline_opts,
400                            std::map<std::string, args_vector_t>& args_shorthand) {
401   // Register any of the extra benchmarks that were specified in the options.
402   args_vector_t arg_vector;
403   args_vector_t* run_args = &arg_vector;
404   for (const std::string& extra_fn : cmdline_opts.extra_benchmarks) {
405     android::base::Trim(extra_fn);
406     size_t first_space_pos = extra_fn.find(' ');
407     std::string fn_name = extra_fn.substr(0, first_space_pos);
408     std::string cmd_args;
409     if (first_space_pos != std::string::npos) {
410       cmd_args = extra_fn.substr(extra_fn.find(' ') + 1);
411     } else {
412       cmd_args = "";
413     }
414     run_args = ResolveArgs(run_args, cmd_args, args_shorthand);
415     RegisterGoogleBenchmarks(bench_opts_t(), cmdline_opts, fn_name, run_args);
416 
417     run_args = &arg_vector;
418     arg_vector.clear();
419   }
420 }
421 
RegisterXmlBenchmarks(bench_opts_t cmdline_opts,std::map<std::string,args_vector_t> & args_shorthand)422 int RegisterXmlBenchmarks(bench_opts_t cmdline_opts,
423                           std::map<std::string, args_vector_t>& args_shorthand) {
424   // Structure of the XML file:
425   // - Element "fn"           Function to benchmark.
426   // - - Element "iterations" Number of iterations to run. Leaving this blank uses
427   //                          Google benchmarks' convergence heuristics.
428   // - - Element "cpu"        CPU to isolate to, if any.
429   // - - Element "args"       Whitespace-separated list of per-function integer arguments, or
430   //                          one of the macros defined in util.h.
431   tinyxml2::XMLDocument doc;
432   if (doc.LoadFile(cmdline_opts.xmlpath.c_str()) != tinyxml2::XML_SUCCESS) {
433     doc.PrintError();
434     return doc.ErrorID();
435   }
436 
437   // Read and register the functions.
438   tinyxml2::XMLNode* fn = doc.FirstChildElement("fn");
439   while (fn) {
440     if (fn == fn->ToComment()) {
441       // Skip comments.
442       fn = fn->NextSibling();
443       continue;
444     }
445 
446     auto fn_elem = fn->FirstChildElement("name");
447     if (!fn_elem) {
448       errx(1, "ERROR: Malformed XML entry: missing name element.");
449     }
450     std::string fn_name = fn_elem->GetText();
451     if (fn_name.empty()) {
452       errx(1, "ERROR: Malformed XML entry: error parsing name text.");
453     }
454     auto* xml_args = fn->FirstChildElement("args");
455     args_vector_t arg_vector;
456     args_vector_t* run_args = ResolveArgs(&arg_vector,
457                                           xml_args ? android::base::Trim(xml_args->GetText()) : "",
458                                           args_shorthand);
459 
460     // XML values for CPU and iterations take precedence over those passed in via CLI.
461     bench_opts_t xml_opts{};
462     auto* num_iterations_elem = fn->FirstChildElement("iterations");
463     if (num_iterations_elem) {
464       int temp;
465       num_iterations_elem->QueryIntText(&temp);
466       xml_opts.num_iterations = temp;
467     }
468     auto* cpu_to_lock_elem = fn->FirstChildElement("cpu");
469     if (cpu_to_lock_elem) {
470       int temp;
471       cpu_to_lock_elem->QueryIntText(&temp);
472       xml_opts.cpu_to_lock = temp;
473     }
474 
475     RegisterGoogleBenchmarks(xml_opts, cmdline_opts, fn_name, run_args);
476 
477     fn = fn->NextSibling();
478   }
479   return 0;
480 }
481 
SetArgs(const std::vector<int> & sizes,args_vector_t * args)482 static void SetArgs(const std::vector<int>& sizes, args_vector_t* args) {
483   for (int size : sizes) {
484     args->push_back({size});
485   }
486 }
487 
SetArgs(const std::vector<int> & sizes,int align,args_vector_t * args)488 static void SetArgs(const std::vector<int>& sizes, int align, args_vector_t* args) {
489   for (int size : sizes) {
490     args->push_back({size, align});
491   }
492 }
493 
494 
SetArgs(const std::vector<int> & sizes,int align1,int align2,args_vector_t * args)495 static void SetArgs(const std::vector<int>& sizes, int align1, int align2, args_vector_t* args) {
496   for (int size : sizes) {
497     args->push_back({size, align1, align2});
498   }
499 }
500 
GetArgs(const std::vector<int> & sizes)501 static args_vector_t GetArgs(const std::vector<int>& sizes) {
502   args_vector_t args;
503   SetArgs(sizes, &args);
504   return args;
505 }
506 
GetArgs(const std::vector<int> & sizes,int align)507 static args_vector_t GetArgs(const std::vector<int>& sizes, int align) {
508   args_vector_t args;
509   SetArgs(sizes, align, &args);
510   return args;
511 }
512 
GetArgs(const std::vector<int> & sizes,int align1,int align2)513 static args_vector_t GetArgs(const std::vector<int>& sizes, int align1, int align2) {
514   args_vector_t args;
515   SetArgs(sizes, align1, align2, &args);
516   return args;
517 }
518 
GetShorthand()519 std::map<std::string, args_vector_t> GetShorthand() {
520   std::vector<int> all_sizes(kSmallSizes);
521   all_sizes.insert(all_sizes.end(), kMediumSizes.begin(), kMediumSizes.end());
522   all_sizes.insert(all_sizes.end(), kLargeSizes.begin(), kLargeSizes.end());
523 
524   int page_sz = getpagesize();
525   std::vector<int> sub_page_sizes = {page_sz / 2, page_sz / 4, page_sz / 8};
526   std::vector<int> multi_page_sizes = {page_sz,      page_sz * 2,  page_sz * 3,  page_sz * 10,
527                                        page_sz * 25, page_sz * 50, page_sz * 75, page_sz * 100};
528   std::vector<int> all_page_sizes(sub_page_sizes);
529   all_page_sizes.insert(all_page_sizes.end(), multi_page_sizes.begin(), multi_page_sizes.end());
530 
531   std::map<std::string, args_vector_t> args_shorthand{
532       {"AT_COMMON_SIZES", GetArgs(kCommonSizes)},
533       {"AT_SMALL_SIZES", GetArgs(kSmallSizes)},
534       {"AT_MEDIUM_SIZES", GetArgs(kMediumSizes)},
535       {"AT_LARGE_SIZES", GetArgs(kLargeSizes)},
536       {"AT_ALL_SIZES", GetArgs(all_sizes)},
537       {"AT_SUB_PAGE_SIZES", GetArgs(sub_page_sizes)},
538       {"AT_MULTI_PAGE_SIZES", GetArgs(multi_page_sizes)},
539       {"AT_ALL_PAGE_SIZES", GetArgs(all_page_sizes)},
540 
541       {"AT_ALIGNED_ONEBUF", GetArgs(kCommonSizes, 0)},
542       {"AT_ALIGNED_ONEBUF_SMALL", GetArgs(kSmallSizes, 0)},
543       {"AT_ALIGNED_ONEBUF_MEDIUM", GetArgs(kMediumSizes, 0)},
544       {"AT_ALIGNED_ONEBUF_LARGE", GetArgs(kLargeSizes, 0)},
545       {"AT_ALIGNED_ONEBUF_ALL", GetArgs(all_sizes, 0)},
546 
547       {"AT_ALIGNED_TWOBUF", GetArgs(kCommonSizes, 0, 0)},
548       {"AT_ALIGNED_TWOBUF_SMALL", GetArgs(kSmallSizes, 0, 0)},
549       {"AT_ALIGNED_TWOBUF_MEDIUM", GetArgs(kMediumSizes, 0, 0)},
550       {"AT_ALIGNED_TWOBUF_LARGE", GetArgs(kLargeSizes, 0, 0)},
551       {"AT_ALIGNED_TWOBUF_ALL", GetArgs(all_sizes, 0, 0)},
552 
553       // Do not exceed 512. that is about the largest number of properties
554       // that can be created with the current property area size.
555       {"NUM_PROPS", args_vector_t{{1}, {4}, {16}, {64}, {128}, {256}, {512}}},
556 
557       {"MATH_COMMON", args_vector_t{{0}, {1}, {2}, {3}}},
558       {"MATH_SINCOS_COMMON", args_vector_t{{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}}},
559   };
560 
561   args_vector_t args_onebuf;
562   args_vector_t args_twobuf;
563   for (int size : all_sizes) {
564     args_onebuf.push_back({size, 0});
565     args_twobuf.push_back({size, 0, 0});
566     // Skip alignments on zero sizes.
567     if (size == 0) {
568       continue;
569     }
570     for (int align1 = 1; align1 <= 32; align1 <<= 1) {
571       args_onebuf.push_back({size, align1});
572       for (int align2 = 1; align2 <= 32; align2 <<= 1) {
573         args_twobuf.push_back({size, align1, align2});
574       }
575     }
576   }
577   args_shorthand.emplace("AT_MANY_ALIGNED_ONEBUF", args_onebuf);
578   args_shorthand.emplace("AT_MANY_ALIGNED_TWOBUF", args_twobuf);
579 
580   return args_shorthand;
581 }
582 
FileExists(const std::string & file)583 static bool FileExists(const std::string& file) {
584   struct stat st;
585   return stat(file.c_str(), &st) != -1 && S_ISREG(st.st_mode);
586 }
587 
RegisterAllBenchmarks(const bench_opts_t & opts,std::map<std::string,args_vector_t> & args_shorthand)588 void RegisterAllBenchmarks(const bench_opts_t& opts,
589                            std::map<std::string, args_vector_t>& args_shorthand) {
590   for (auto& entry : g_str_to_func) {
591     auto& function_info = entry.second;
592     args_vector_t arg_vector;
593     args_vector_t* run_args = ResolveArgs(&arg_vector, function_info.second,
594                                           args_shorthand);
595     RegisterGoogleBenchmarks(bench_opts_t(), opts, entry.first, run_args);
596   }
597 }
598 
main(int argc,char ** argv)599 int main(int argc, char** argv) {
600   std::map<std::string, args_vector_t> args_shorthand = GetShorthand();
601   bench_opts_t opts = ParseOpts(argc, argv);
602   std::vector<char*> new_argv(argc);
603   SanitizeOpts(argc, argv, &new_argv);
604 
605   if (opts.xmlpath.empty()) {
606     // Don't add the default xml file if a user is specifying the tests to run.
607     if (opts.extra_benchmarks.empty()) {
608       RegisterAllBenchmarks(opts, args_shorthand);
609     }
610   } else if (!FileExists(opts.xmlpath)) {
611     // See if this is a file in the suites directory.
612     std::string file(android::base::GetExecutableDirectory() + "/suites/" + opts.xmlpath);
613     if (opts.xmlpath[0] == '/' || !FileExists(file)) {
614       printf("Cannot find xml file %s: does not exist or is not a file.\n", opts.xmlpath.c_str());
615       return 1;
616     }
617     opts.xmlpath = file;
618   }
619 
620   if (!opts.xmlpath.empty()) {
621     if (int err = RegisterXmlBenchmarks(opts, args_shorthand)) {
622       return err;
623     }
624   }
625   RegisterCliBenchmarks(opts, args_shorthand);
626 
627   // Set the thread priority to the maximum.
628   if (setpriority(PRIO_PROCESS, 0, -20)) {
629     perror("Failed to raise priority of process. Are you root?\n");
630   }
631 
632   int new_argc = new_argv.size();
633   benchmark::Initialize(&new_argc, new_argv.data());
634   benchmark::RunSpecifiedBenchmarks();
635 }
636