• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 <dirent.h>
18 #include <err.h>
19 #include <limits.h>
20 #include <stdio.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #if defined(__linux__)
26 #include <sched.h>
27 #endif
28 
29 #include <atomic>
30 #include <chrono>
31 #include <functional>
32 #include <iostream>
33 #include <map>
34 #include <memory>
35 #include <set>
36 #include <sstream>
37 #include <string>
38 #include <thread>
39 #include <unordered_map>
40 #include <vector>
41 
42 #include <llvm/ADT/StringRef.h>
43 
44 #include <android-base/file.h>
45 #include <android-base/macros.h>
46 #include <android-base/parseint.h>
47 
48 #include "Arch.h"
49 #include "DeclarationDatabase.h"
50 #include "Driver.h"
51 #include "Preprocessor.h"
52 #include "SymbolDatabase.h"
53 #include "Utils.h"
54 #include "VFS.h"
55 
56 #include "versioner.h"
57 
58 using namespace std::chrono_literals;
59 using namespace std::string_literals;
60 
61 bool strict;
62 bool verbose;
63 bool add_include;
64 
65 static int getCpuCount();
66 static int max_thread_count = getCpuCount();
67 
getCpuCount()68 static int getCpuCount() {
69 #if defined(__linux__)
70   cpu_set_t cpu_set;
71   int rc = sched_getaffinity(getpid(), sizeof(cpu_set), &cpu_set);
72   if (rc != 0) {
73     err(1, "sched_getaffinity failed");
74   }
75   return CPU_COUNT(&cpu_set);
76 #else
77   return 1;
78 #endif
79 }
80 
collectRequirements(const Arch & arch,const std::string & header_dir,const std::string & dependency_dir)81 static CompilationRequirements collectRequirements(const Arch& arch, const std::string& header_dir,
82                                                    const std::string& dependency_dir) {
83   std::vector<std::string> headers = collectHeaders(header_dir);
84   std::vector<std::string> dependencies = { header_dir };
85   if (!dependency_dir.empty()) {
86     auto collect_children = [&dependencies](const std::string& dir_path) {
87       DIR* dir = opendir(dir_path.c_str());
88       if (!dir) {
89         err(1, "failed to open dependency directory '%s'", dir_path.c_str());
90       }
91 
92       struct dirent* dent;
93       while ((dent = readdir(dir))) {
94         if (dent->d_name[0] == '.') {
95           continue;
96         }
97 
98         // TODO: Resolve symlinks.
99         std::string dependency = dir_path + "/" + dent->d_name;
100 
101         struct stat st;
102         if (stat(dependency.c_str(), &st) != 0) {
103           err(1, "failed to stat dependency '%s'", dependency.c_str());
104         }
105 
106         if (!S_ISDIR(st.st_mode)) {
107           errx(1, "'%s' is not a directory", dependency.c_str());
108         }
109 
110         dependencies.push_back(dependency);
111       }
112 
113       closedir(dir);
114     };
115 
116     collect_children(dependency_dir + "/common");
117     collect_children(dependency_dir + "/" + to_string(arch));
118   }
119 
120   auto new_end = std::remove_if(headers.begin(), headers.end(), [&arch](llvm::StringRef header) {
121     for (const auto& it : header_blacklist) {
122       if (it.second.find(arch) == it.second.end()) {
123         continue;
124       }
125 
126       if (header.endswith("/" + it.first)) {
127         return true;
128       }
129     }
130     return false;
131   });
132 
133   headers.erase(new_end, headers.end());
134 
135   CompilationRequirements result = { .headers = headers, .dependencies = dependencies };
136   return result;
137 }
138 
generateCompilationTypes(const std::set<Arch> selected_architectures,const std::set<int> & selected_levels)139 static std::set<CompilationType> generateCompilationTypes(const std::set<Arch> selected_architectures,
140                                                           const std::set<int>& selected_levels) {
141   std::set<CompilationType> result;
142   for (const auto& arch : selected_architectures) {
143     int min_api = arch_min_api[arch];
144     for (int api_level : selected_levels) {
145       if (api_level < min_api) {
146         continue;
147       }
148 
149       for (int file_offset_bits : { 32, 64 }) {
150         CompilationType type = {
151           .arch = arch, .api_level = api_level, .file_offset_bits = file_offset_bits
152         };
153         result.insert(type);
154       }
155     }
156   }
157   return result;
158 }
159 
compileHeaders(const std::set<CompilationType> & types,const std::string & header_dir,const std::string & dependency_dir)160 static std::unique_ptr<HeaderDatabase> compileHeaders(const std::set<CompilationType>& types,
161                                                       const std::string& header_dir,
162                                                       const std::string& dependency_dir) {
163   if (types.empty()) {
164     errx(1, "compileHeaders received no CompilationTypes");
165   }
166 
167   auto vfs = createCommonVFS(header_dir, dependency_dir, add_include);
168 
169   size_t thread_count = max_thread_count;
170   std::vector<std::thread> threads;
171 
172   std::map<CompilationType, HeaderDatabase> header_databases;
173   std::unordered_map<Arch, CompilationRequirements> requirements;
174 
175   auto result = std::make_unique<HeaderDatabase>();
176   for (const auto& type : types) {
177     if (requirements.count(type.arch) == 0) {
178       requirements[type.arch] = collectRequirements(type.arch, header_dir, dependency_dir);
179     }
180   }
181 
182   initializeTargetCC1FlagCache(vfs, types, requirements);
183 
184   std::vector<std::pair<CompilationType, const std::string&>> jobs;
185   std::atomic<size_t> job_index(0);
186   for (CompilationType type : types) {
187     CompilationRequirements& req = requirements[type.arch];
188     for (const std::string& header : req.headers) {
189       jobs.emplace_back(type, header);
190     }
191   }
192 
193   thread_count = std::min(thread_count, jobs.size());
194 
195   if (thread_count == 1) {
196     for (const auto& job : jobs) {
197       compileHeader(vfs, result.get(), job.first, job.second);
198     }
199   } else {
200     // Spawn threads.
201     for (size_t i = 0; i < thread_count; ++i) {
202       threads.emplace_back([&jobs, &job_index, &result, vfs]() {
203         while (true) {
204           size_t idx = job_index++;
205           if (idx >= jobs.size()) {
206             return;
207           }
208 
209           const auto& job = jobs[idx];
210           compileHeader(vfs, result.get(), job.first, job.second);
211         }
212       });
213     }
214 
215     // Reap them.
216     for (auto& thread : threads) {
217       thread.join();
218     }
219     threads.clear();
220   }
221 
222   return result;
223 }
224 
getCompilationTypes(const Declaration * decl)225 static std::set<CompilationType> getCompilationTypes(const Declaration* decl) {
226   std::set<CompilationType> result;
227   for (const auto& it : decl->availability) {
228     result.insert(it.first);
229   }
230   return result;
231 }
232 
233 template<typename T>
Intersection(const std::set<T> & a,const std::set<T> & b)234 static std::vector<T> Intersection(const std::set<T>& a, const std::set<T>& b) {
235   std::vector<T> intersection;
236   std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(intersection));
237   return intersection;
238 }
239 
240 // Perform a sanity check on a symbol's declarations, enforcing the following invariants:
241 //   1. At most one inline definition of the function exists.
242 //   2. All of the availability declarations for a symbol are compatible.
243 //      If a function is declared as an inline before a certain version, the inline definition
244 //      should have no version tag.
245 //   3. Each availability type must only be present globally or on a per-arch basis.
246 //      (e.g. __INTRODUCED_IN_ARM(9) __INTRODUCED_IN_X86(10) __DEPRECATED_IN(11) is fine,
247 //      but not __INTRODUCED_IN(9) __INTRODUCED_IN_X86(10))
checkSymbol(const Symbol & symbol)248 static bool checkSymbol(const Symbol& symbol) {
249   std::string cwd = getWorkingDir() + "/";
250 
251   std::unordered_map<const Declaration*, std::set<CompilationType>> inline_definitions;
252   for (const auto& decl_it : symbol.declarations) {
253     const Declaration* decl = &decl_it.second;
254     if (decl->is_definition) {
255       std::set<CompilationType> compilation_types = getCompilationTypes(decl);
256       for (const auto& inline_def_it : inline_definitions) {
257         auto intersection = Intersection(compilation_types, inline_def_it.second);
258         if (!intersection.empty()) {
259           fprintf(stderr, "versioner: conflicting inline definitions:\n");
260           fprintf(stderr, "  declarations visible in: %s\n", Join(intersection, ", ").c_str());
261           decl->dump(cwd, stderr, 4);
262           inline_def_it.first->dump(cwd, stderr, 4);
263           return false;
264         }
265       }
266 
267       inline_definitions[decl] = std::move(compilation_types);
268     }
269 
270     DeclarationAvailability availability;
271     if (!decl->calculateAvailability(&availability)) {
272       fprintf(stderr, "versioner: failed to calculate availability for declaration:\n");
273       decl->dump(cwd, stderr, 2);
274       return false;
275     }
276 
277     if (decl->is_definition && !availability.empty()) {
278       fprintf(stderr, "versioner: inline definition has non-empty versioning information:\n");
279       decl->dump(cwd, stderr, 2);
280       return false;
281     }
282   }
283 
284   DeclarationAvailability availability;
285   if (!symbol.calculateAvailability(&availability)) {
286     fprintf(stderr, "versioner: inconsistent availability for symbol '%s'\n", symbol.name.c_str());
287     symbol.dump(cwd);
288     return false;
289   }
290 
291   // TODO: Check invariant #3.
292   return true;
293 }
294 
sanityCheck(const HeaderDatabase * database)295 static bool sanityCheck(const HeaderDatabase* database) {
296   bool error = false;
297   std::string cwd = getWorkingDir() + "/";
298 
299   for (const auto& symbol_it : database->symbols) {
300     if (!checkSymbol(symbol_it.second)) {
301       error = true;
302     }
303   }
304   return !error;
305 }
306 
307 // Check that our symbol availability declarations match the actual NDK
308 // platform symbol availability.
checkVersions(const std::set<CompilationType> & types,const HeaderDatabase * header_database,const NdkSymbolDatabase & symbol_database)309 static bool checkVersions(const std::set<CompilationType>& types,
310                           const HeaderDatabase* header_database,
311                           const NdkSymbolDatabase& symbol_database) {
312   std::string cwd = getWorkingDir() + "/";
313   bool failed = false;
314 
315   std::map<Arch, std::set<CompilationType>> arch_types;
316   for (const CompilationType& type : types) {
317     arch_types[type.arch].insert(type);
318   }
319 
320   std::set<std::string> completely_unavailable;
321   std::map<std::string, std::set<CompilationType>> missing_availability;
322   std::map<std::string, std::set<CompilationType>> extra_availability;
323 
324   for (const auto& symbol_it : header_database->symbols) {
325     const auto& symbol_name = symbol_it.first;
326     DeclarationAvailability symbol_availability;
327 
328     if (!symbol_it.second.calculateAvailability(&symbol_availability)) {
329       errx(1, "failed to calculate symbol availability");
330     }
331 
332     const auto platform_availability_it = symbol_database.find(symbol_name);
333     if (platform_availability_it == symbol_database.end()) {
334       completely_unavailable.insert(symbol_name);
335       continue;
336     }
337 
338     const auto& platform_availability = platform_availability_it->second;
339 
340     for (const CompilationType& type : types) {
341       bool should_be_available = true;
342       const auto& global_availability = symbol_availability.global_availability;
343       const auto& arch_availability = symbol_availability.arch_availability[type.arch];
344       if (global_availability.introduced != 0 && global_availability.introduced > type.api_level) {
345         should_be_available = false;
346       }
347 
348       if (arch_availability.introduced != 0 && arch_availability.introduced > type.api_level) {
349         should_be_available = false;
350       }
351 
352       if (global_availability.obsoleted != 0 && global_availability.obsoleted <= type.api_level) {
353         should_be_available = false;
354       }
355 
356       if (arch_availability.obsoleted != 0 && arch_availability.obsoleted <= type.api_level) {
357         should_be_available = false;
358       }
359 
360       if (arch_availability.future) {
361         continue;
362       }
363 
364       // The function declaration might be (validly) missing for the given CompilationType.
365       if (!symbol_it.second.hasDeclaration(type)) {
366         should_be_available = false;
367       }
368 
369       bool is_available = platform_availability.count(type);
370 
371       if (should_be_available != is_available) {
372         if (is_available) {
373           extra_availability[symbol_name].insert(type);
374         } else {
375           missing_availability[symbol_name].insert(type);
376         }
377       }
378     }
379   }
380 
381   for (const auto& it : symbol_database) {
382     const std::string& symbol_name = it.first;
383 
384     bool symbol_error = false;
385     if (auto missing_it = missing_availability.find(symbol_name);
386         missing_it != missing_availability.end()) {
387       printf("%s: declaration marked available but symbol missing in [%s]\n", symbol_name.c_str(),
388              Join(missing_it->second, ", ").c_str());
389       symbol_error = true;
390       failed = true;
391     }
392 
393     if (strict) {
394       if (auto extra_it = extra_availability.find(symbol_name);
395           extra_it != extra_availability.end()) {
396         printf("%s: declaration marked unavailable but symbol available in [%s]\n",
397                symbol_name.c_str(), Join(extra_it->second, ", ").c_str());
398         symbol_error = true;
399         failed = true;
400       }
401     }
402 
403     if (symbol_error) {
404       if (auto symbol_it = header_database->symbols.find(symbol_name);
405           symbol_it != header_database->symbols.end()) {
406         symbol_it->second.dump(cwd);
407       } else {
408         errx(1, "failed to find symbol in header database");
409       }
410     }
411   }
412 
413   // TODO: Verify that function/variable declarations are actually function/variable symbols.
414   return !failed;
415 }
416 
usage(bool help=false)417 static void usage(bool help = false) {
418   fprintf(stderr, "Usage: versioner [OPTION]... [HEADER_PATH] [DEPS_PATH]\n");
419   if (!help) {
420     printf("Try 'versioner -h' for more information.\n");
421     exit(1);
422   } else {
423     fprintf(stderr, "Version headers at HEADER_PATH, with DEPS_PATH/ARCH/* on the include path\n");
424     fprintf(stderr, "Autodetects paths if HEADER_PATH and DEPS_PATH are not specified\n");
425     fprintf(stderr, "\n");
426     fprintf(stderr, "Target specification (defaults to all):\n");
427     fprintf(stderr, "  -a API_LEVEL\tbuild with specified API level (can be repeated)\n");
428     fprintf(stderr, "    \t\tvalid levels are %s\n", Join(supported_levels).c_str());
429     fprintf(stderr, "  -r ARCH\tbuild with specified architecture (can be repeated)\n");
430     fprintf(stderr, "    \t\tvalid architectures are %s\n", Join(supported_archs).c_str());
431     fprintf(stderr, "\n");
432     fprintf(stderr, "Validation:\n");
433     fprintf(stderr, "  -p PATH\tcompare against NDK platform at PATH\n");
434     fprintf(stderr, "  -s\t\tenable strict warnings\n");
435     fprintf(stderr, "\n");
436     fprintf(stderr, "Preprocessing:\n");
437     fprintf(stderr, "  -o PATH\tpreprocess header files and emit them at PATH\n");
438     fprintf(stderr, "  -f\t\tpreprocess header files even if validation fails\n");
439     fprintf(stderr, "\n");
440     fprintf(stderr, "Miscellaneous:\n");
441     fprintf(stderr, "  -d\t\tdump function availability\n");
442     fprintf(stderr, "  -j THREADS\tmaximum number of threads to use\n");
443     fprintf(stderr, "  -v\t\tenable verbose logging\n");
444     fprintf(stderr, "  -h\t\tdisplay this message\n");
445     exit(0);
446   }
447 }
448 
449 // versioner uses a prebuilt version of clang, which is not up-to-date wrt/
450 // container annotations. So disable container overflow checking. b/37775238
__asan_default_options()451 extern "C" const char* __asan_default_options() {
452   return "detect_container_overflow=0";
453 }
454 
main(int argc,char ** argv)455 int main(int argc, char** argv) {
456   std::string cwd = getWorkingDir() + "/";
457   bool default_args = true;
458   std::string platform_dir;
459   std::set<Arch> selected_architectures;
460   std::set<int> selected_levels;
461   std::string preprocessor_output_path;
462   bool force = false;
463   bool dump = false;
464 
465   int c;
466   while ((c = getopt(argc, argv, "a:r:p:so:fdj:vhi")) != -1) {
467     default_args = false;
468     switch (c) {
469       case 'a': {
470         char* end;
471         int api_level = strtol(optarg, &end, 10);
472         if (end == optarg || strlen(end) > 0) {
473           usage();
474         }
475 
476         if (supported_levels.count(api_level) == 0) {
477           errx(1, "unsupported API level %d", api_level);
478         }
479 
480         selected_levels.insert(api_level);
481         break;
482       }
483 
484       case 'r': {
485         Arch arch = arch_from_string(optarg);
486         selected_architectures.insert(arch);
487         break;
488       }
489 
490       case 'p': {
491         if (!platform_dir.empty()) {
492           usage();
493         }
494 
495         platform_dir = optarg;
496 
497         if (platform_dir.empty()) {
498           usage();
499         }
500 
501         struct stat st;
502         if (stat(platform_dir.c_str(), &st) != 0) {
503           err(1, "failed to stat platform directory '%s'", platform_dir.c_str());
504         }
505         if (!S_ISDIR(st.st_mode)) {
506           errx(1, "'%s' is not a directory", optarg);
507         }
508         break;
509       }
510 
511       case 's':
512         strict = true;
513         break;
514 
515       case 'o':
516         if (!preprocessor_output_path.empty()) {
517           usage();
518         }
519         preprocessor_output_path = optarg;
520         if (preprocessor_output_path.empty()) {
521           usage();
522         }
523         break;
524 
525       case 'f':
526         force = true;
527         break;
528 
529       case 'd':
530         dump = true;
531         break;
532 
533       case 'j':
534         if (!android::base::ParseInt<int>(optarg, &max_thread_count, 1)) {
535           usage();
536         }
537         break;
538 
539       case 'v':
540         verbose = true;
541         break;
542 
543       case 'h':
544         usage(true);
545         break;
546 
547       case 'i':
548         // Secret option for tests to -include <android/versioning.h>.
549         add_include = true;
550         break;
551 
552       default:
553         usage();
554         break;
555     }
556   }
557 
558   if (argc - optind > 2 || optind > argc) {
559     usage();
560   }
561 
562   std::string header_dir;
563   std::string dependency_dir;
564 
565   const char* top = getenv("ANDROID_BUILD_TOP");
566   if (!top && (optind == argc || add_include)) {
567     fprintf(stderr, "versioner: failed to autodetect bionic paths. Is ANDROID_BUILD_TOP set?\n");
568     usage();
569   }
570 
571   if (optind == argc) {
572     // Neither HEADER_PATH nor DEPS_PATH were specified, so try to figure them out.
573     std::string versioner_dir = to_string(top) + "/bionic/tools/versioner";
574     header_dir = versioner_dir + "/current";
575     dependency_dir = versioner_dir + "/dependencies";
576     if (platform_dir.empty()) {
577       platform_dir = versioner_dir + "/platforms";
578     }
579   } else {
580     if (!android::base::Realpath(argv[optind], &header_dir)) {
581       err(1, "failed to get realpath for path '%s'", argv[optind]);
582     }
583 
584     if (argc - optind == 2) {
585       dependency_dir = argv[optind + 1];
586     }
587   }
588 
589   if (selected_levels.empty()) {
590     selected_levels = supported_levels;
591   }
592 
593   if (selected_architectures.empty()) {
594     selected_architectures = supported_archs;
595   }
596 
597 
598   struct stat st;
599   if (stat(header_dir.c_str(), &st) != 0) {
600     err(1, "failed to stat '%s'", header_dir.c_str());
601   } else if (!S_ISDIR(st.st_mode)) {
602     errx(1, "'%s' is not a directory", header_dir.c_str());
603   }
604 
605   std::set<CompilationType> compilation_types;
606   NdkSymbolDatabase symbol_database;
607 
608   compilation_types = generateCompilationTypes(selected_architectures, selected_levels);
609 
610   // Do this before compiling so that we can early exit if the platforms don't match what we
611   // expect.
612   if (!platform_dir.empty()) {
613     symbol_database = parsePlatforms(compilation_types, platform_dir);
614   }
615 
616   auto start = std::chrono::high_resolution_clock::now();
617   std::unique_ptr<HeaderDatabase> declaration_database =
618       compileHeaders(compilation_types, header_dir, dependency_dir);
619   auto end = std::chrono::high_resolution_clock::now();
620 
621   if (verbose) {
622     auto diff = (end - start) / 1.0ms;
623     printf("Compiled headers for %zu targets in %0.2LFms\n", compilation_types.size(), diff);
624   }
625 
626   bool failed = false;
627   if (dump) {
628     declaration_database->dump(header_dir + "/");
629   } else {
630     if (!sanityCheck(declaration_database.get())) {
631       printf("versioner: sanity check failed\n");
632       failed = true;
633     }
634 
635     if (!platform_dir.empty()) {
636       if (!checkVersions(compilation_types, declaration_database.get(), symbol_database)) {
637         printf("versioner: version check failed\n");
638         failed = true;
639       }
640     }
641   }
642 
643   if (!preprocessor_output_path.empty() && (force || !failed)) {
644     failed = !preprocessHeaders(preprocessor_output_path, header_dir, declaration_database.get());
645   }
646   return failed;
647 }
648