blob: 91482edb1b0739d81b7746c7cdcbb51ff473793c [file] [log] [blame]
Josh Gaobf8a2852016-05-27 11:59:09 -07001/*
2 * Copyright 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#include <atomic>
26#include <iostream>
27#include <map>
28#include <memory>
29#include <set>
30#include <sstream>
31#include <string>
32#include <thread>
33#include <unordered_map>
34#include <vector>
35
36#include <clang/Frontend/TextDiagnosticPrinter.h>
37#include <clang/Tooling/Tooling.h>
38#include <llvm/ADT/StringRef.h>
39
40#include "DeclarationDatabase.h"
41#include "SymbolDatabase.h"
42#include "Utils.h"
43#include "versioner.h"
44
45using namespace std::string_literals;
46using namespace clang;
47using namespace clang::tooling;
48
49bool verbose;
50
51class HeaderCompilationDatabase : public CompilationDatabase {
52 CompilationType type;
53 std::string cwd;
54 std::vector<std::string> headers;
55 std::vector<std::string> include_dirs;
56
57 public:
58 HeaderCompilationDatabase(CompilationType type, std::string cwd, std::vector<std::string> headers,
59 std::vector<std::string> include_dirs)
60 : type(type),
61 cwd(std::move(cwd)),
62 headers(std::move(headers)),
63 include_dirs(std::move(include_dirs)) {
64 }
65
66 CompileCommand generateCompileCommand(const std::string& filename) const {
67 std::vector<std::string> command = { "clang-tool", filename, "-nostdlibinc" };
68 for (const auto& dir : include_dirs) {
69 command.push_back("-isystem");
70 command.push_back(dir);
71 }
72 command.push_back("-std=c11");
73 command.push_back("-DANDROID");
74 command.push_back("-D__ANDROID_API__="s + std::to_string(type.api_level));
75 command.push_back("-D_FORTIFY_SOURCE=2");
76 command.push_back("-D_GNU_SOURCE");
77 command.push_back("-Wno-unknown-attributes");
78 command.push_back("-target");
79 command.push_back(arch_targets[type.arch]);
80
81 return CompileCommand(cwd, filename, command);
82 }
83
84 std::vector<CompileCommand> getAllCompileCommands() const override {
85 std::vector<CompileCommand> commands;
86 for (const std::string& file : headers) {
87 commands.push_back(generateCompileCommand(file));
88 }
89 return commands;
90 }
91
92 std::vector<CompileCommand> getCompileCommands(StringRef file) const override {
93 std::vector<CompileCommand> commands;
94 commands.push_back(generateCompileCommand(file));
95 return commands;
96 }
97
98 std::vector<std::string> getAllFiles() const override {
99 return headers;
100 }
101};
102
103struct CompilationRequirements {
104 std::vector<std::string> headers;
105 std::vector<std::string> dependencies;
106};
107
108static CompilationRequirements collectRequirements(const std::string& arch,
109 const std::string& header_dir,
110 const std::string& dependency_dir) {
111 std::vector<std::string> headers = collectFiles(header_dir);
112
113 std::vector<std::string> dependencies = { header_dir };
114 if (!dependency_dir.empty()) {
115 auto collect_children = [&dependencies](const std::string& dir_path) {
116 DIR* dir = opendir(dir_path.c_str());
117 if (!dir) {
118 err(1, "failed to open dependency directory '%s'", dir_path.c_str());
119 }
120
121 struct dirent* dent;
122 while ((dent = readdir(dir))) {
123 if (dent->d_name[0] == '.') {
124 continue;
125 }
126
127 // TODO: Resolve symlinks.
128 std::string dependency = dir_path + "/" + dent->d_name;
129
130 struct stat st;
131 if (stat(dependency.c_str(), &st) != 0) {
132 err(1, "failed to stat dependency '%s'", dependency.c_str());
133 }
134
135 if (!S_ISDIR(st.st_mode)) {
136 errx(1, "'%s' is not a directory", dependency.c_str());
137 }
138
139 dependencies.push_back(dependency);
140 }
141
142 closedir(dir);
143 };
144
145 collect_children(dependency_dir + "/common");
146 collect_children(dependency_dir + "/" + arch);
147 }
148
149 auto new_end = std::remove_if(headers.begin(), headers.end(), [&arch](llvm::StringRef header) {
150 for (const auto& it : header_blacklist) {
151 if (it.second.find(arch) == it.second.end()) {
152 continue;
153 }
154
155 if (header.endswith("/" + it.first)) {
156 return true;
157 }
158 }
159 return false;
160 });
161
162 headers.erase(new_end, headers.end());
163
164 CompilationRequirements result = { .headers = headers, .dependencies = dependencies };
165 return result;
166}
167
168static std::set<CompilationType> generateCompilationTypes(
169 const std::set<std::string> selected_architectures, const std::set<int>& selected_levels) {
170 std::set<CompilationType> result;
171 for (const std::string& arch : selected_architectures) {
172 int min_api = arch_min_api[arch];
173 for (int api_level : selected_levels) {
174 if (api_level < min_api) {
175 continue;
176 }
177 CompilationType type = { .arch = arch, .api_level = api_level };
178 result.insert(type);
179 }
180 }
181 return result;
182}
183
184using DeclarationDatabase = std::map<std::string, std::map<CompilationType, Declaration>>;
185
186static DeclarationDatabase transposeHeaderDatabases(
187 const std::map<CompilationType, HeaderDatabase>& original) {
188 DeclarationDatabase result;
189 for (const auto& outer : original) {
190 const CompilationType& type = outer.first;
191 for (const auto& inner : outer.second.declarations) {
192 const std::string& symbol_name = inner.first;
193 result[symbol_name][type] = inner.second;
194 }
195 }
196 return result;
197}
198
199static DeclarationDatabase compileHeaders(const std::set<CompilationType>& types,
200 const std::string& header_dir,
201 const std::string& dependency_dir, bool* failed) {
202 constexpr size_t thread_count = 8;
203 size_t threads_created = 0;
204 std::mutex mutex;
205 std::vector<std::thread> threads(thread_count);
206
207 std::map<CompilationType, HeaderDatabase> header_databases;
208 std::unordered_map<std::string, CompilationRequirements> requirements;
209
210 std::string cwd = getWorkingDir();
211 bool errors = false;
212
213 for (const auto& type : types) {
214 if (requirements.count(type.arch) == 0) {
215 requirements[type.arch] = collectRequirements(type.arch, header_dir, dependency_dir);
216 }
217 }
218
219 for (const auto& type : types) {
220 size_t thread_id = threads_created++;
221 if (thread_id >= thread_count) {
222 thread_id = thread_id % thread_count;
223 threads[thread_id].join();
224 }
225
226 threads[thread_id] = std::thread(
227 [&](CompilationType type) {
228 const auto& req = requirements[type.arch];
229
230 HeaderDatabase database;
231 HeaderCompilationDatabase compilation_database(type, cwd, req.headers, req.dependencies);
232
233 ClangTool tool(compilation_database, req.headers);
234
235 clang::DiagnosticOptions diagnostic_options;
236 std::vector<std::unique_ptr<ASTUnit>> asts;
237 tool.buildASTs(asts);
238 for (const auto& ast : asts) {
239 clang::DiagnosticsEngine& diagnostics_engine = ast->getDiagnostics();
240 if (diagnostics_engine.getNumWarnings() || diagnostics_engine.hasErrorOccurred()) {
241 std::unique_lock<std::mutex> l(mutex);
242 errors = true;
243 printf("versioner: compilation failure for %s in %s\n", type.describe().c_str(),
244 ast->getOriginalSourceFileName().str().c_str());
245 }
246
247 database.parseAST(ast.get());
248 }
249
250 std::unique_lock<std::mutex> l(mutex);
251 header_databases[type] = database;
252 },
253 type);
254 }
255
256 if (threads_created < thread_count) {
257 threads.resize(threads_created);
258 }
259
260 for (auto& thread : threads) {
261 thread.join();
262 }
263
264 if (errors) {
265 printf("versioner: compilation generated warnings or errors\n");
266 *failed = errors;
267 }
268
269 return transposeHeaderDatabases(header_databases);
270}
271
272static bool sanityCheck(const std::set<CompilationType>& types,
273 const DeclarationDatabase& database) {
274 bool error = false;
275 for (auto outer : database) {
276 const std::string& symbol_name = outer.first;
277 CompilationType last_type;
278 DeclarationAvailability last_availability;
279
280 // Rely on std::set being sorted to loop through the types by architecture.
281 for (const CompilationType& type : types) {
282 auto inner = outer.second.find(type);
283 if (inner == outer.second.end()) {
284 // TODO: Check for holes.
285 continue;
286 }
287
288 const Declaration& declaration = inner->second;
289 bool found_availability = false;
290 bool availability_mismatch = false;
291 DeclarationAvailability current_availability;
292
293 // Make sure that all of the availability declarations for this symbol match.
294 for (const DeclarationLocation& location : declaration.locations) {
295 if (!found_availability) {
296 found_availability = true;
297 current_availability = location.availability;
298 continue;
299 }
300
301 if (current_availability != location.availability) {
302 availability_mismatch = true;
303 error = true;
304 }
305 }
306
307 if (availability_mismatch) {
308 printf("%s: availability mismatch for %s\n", symbol_name.c_str(), type.describe().c_str());
309 declaration.dump(getWorkingDir() + "/");
310 }
311
312 if (type.arch != last_type.arch) {
313 last_type = type;
314 last_availability = current_availability;
315 continue;
316 }
317
318 // Make sure that availability declarations are consistent across API levels for a given arch.
319 if (last_availability != current_availability) {
320 error = true;
321 printf("%s: availability mismatch between %s and %s: %s before, %s after\n",
322 symbol_name.c_str(), last_type.describe().c_str(), type.describe().c_str(),
323 last_availability.describe().c_str(), current_availability.describe().c_str());
324 }
325
326 last_type = type;
327 }
328 }
329 return !error;
330}
331
332// Check that our symbol availability declarations match the actual NDK
333// platform symbol availability.
334static bool checkVersions(const std::set<CompilationType>& types,
335 const DeclarationDatabase& declaration_database,
336 const NdkSymbolDatabase& symbol_database) {
337 bool failed = false;
338
339 std::map<std::string, std::set<CompilationType>> arch_types;
340 for (const CompilationType& type : types) {
341 arch_types[type.arch].insert(type);
342 }
343
Josh Gaod67dbf02016-06-02 15:21:14 -0700344 std::set<std::string> completely_unavailable;
345
Josh Gaobf8a2852016-05-27 11:59:09 -0700346 for (const auto& outer : declaration_database) {
347 const std::string& symbol_name = outer.first;
348 const auto& compilations = outer.second;
349
350 auto platform_availability_it = symbol_database.find(symbol_name);
351 if (platform_availability_it == symbol_database.end()) {
Josh Gaod67dbf02016-06-02 15:21:14 -0700352 completely_unavailable.insert(symbol_name);
Josh Gaobf8a2852016-05-27 11:59:09 -0700353 continue;
354 }
355
356 const auto& platform_availability = platform_availability_it->second;
357 std::set<CompilationType> missing_symbol;
358 std::set<CompilationType> missing_decl;
359
360 for (const CompilationType& type : types) {
361 auto it = compilations.find(type);
362 if (it == compilations.end()) {
363 missing_decl.insert(type);
364 continue;
365 }
366
367 const Declaration& declaration = it->second;
368
369 // sanityCheck ensured that the availability declarations for a given arch match.
370 DeclarationAvailability availability = declaration.locations.begin()->availability;
371 int api_level = type.api_level;
372
373 int introduced = std::max(0, availability.introduced);
374 int obsoleted = availability.obsoleted == 0 ? INT_MAX : availability.obsoleted;
375 bool decl_available = api_level >= introduced && api_level < obsoleted;
376
377 auto symbol_availability_it = platform_availability.find(type);
378 bool symbol_available = symbol_availability_it != platform_availability.end();
379 if (decl_available) {
380 if (!symbol_available) {
381 // Make sure that either it exists in the platform, or an inline definition is visible.
382 if (!declaration.hasDefinition()) {
383 missing_symbol.insert(type);
384 continue;
385 }
386 } else {
387 // Make sure that symbols declared as functions/variables actually are.
388 switch (declaration.type()) {
389 case DeclarationType::inconsistent:
390 printf("%s: inconsistent declaration type\n", symbol_name.c_str());
391 declaration.dump();
392 exit(1);
393
394 case DeclarationType::variable:
395 if (symbol_availability_it->second != NdkSymbolType::variable) {
396 printf("%s: declared as variable, exists in platform as function\n",
397 symbol_name.c_str());
398 failed = true;
399 }
400 break;
401
402 case DeclarationType::function:
403 if (symbol_availability_it->second != NdkSymbolType::function) {
404 printf("%s: declared as function, exists in platform as variable\n",
405 symbol_name.c_str());
406 failed = true;
407 }
408 break;
409 }
410 }
411 } else {
412 // Make sure it's not available in the platform.
413 if (symbol_availability_it != platform_availability.end()) {
414 printf("%s: symbol should be unavailable in %s (declared with availability %s)\n",
415 symbol_name.c_str(), type.describe().c_str(), availability.describe().c_str());
416 failed = true;
417 }
418 }
419 }
420
421 // Allow declarations to be missing from an entire architecture.
422 for (const auto& arch_type : arch_types) {
423 const std::string& arch = arch_type.first;
424 bool found_all = true;
425 for (const auto& type : arch_type.second) {
426 if (missing_decl.find(type) == missing_decl.end()) {
427 found_all = false;
428 break;
429 }
430 }
431
432 if (!found_all) {
433 continue;
434 }
435
436 for (auto it = missing_decl.begin(); it != missing_decl.end();) {
437 if (it->arch == arch) {
438 it = missing_decl.erase(it);
439 } else {
440 ++it;
441 }
442 }
443 }
444
445 auto types_to_string = [](const std::set<CompilationType>& types) {
446 std::string result;
447 for (const CompilationType& type : types) {
448 result += type.describe();
449 result += ", ";
450 }
451 result.resize(result.length() - 2);
452 return result;
453 };
454
455 if (!missing_decl.empty()) {
456 printf("%s: declaration missing in %s\n", symbol_name.c_str(),
457 types_to_string(missing_decl).c_str());
458 failed = true;
459 }
460
461 if (!missing_symbol.empty()) {
462 printf("%s: declaration marked available but symbol missing in [%s]\n", symbol_name.c_str(),
463 types_to_string(missing_symbol).c_str());
464 failed = true;
465 }
466 }
467
Josh Gaod67dbf02016-06-02 15:21:14 -0700468 for (const std::string& symbol_name : completely_unavailable) {
469 // This currently has some false positives (mostly functions that come from crtbegin).
470 // Therefore, only report these declarations when running with verbose for now.
471 if (!verbose) {
472 break;
473 }
474
475 // Check to see if the symbol is tagged with __INTRODUCED_IN_FUTURE.
476 auto symbol_it = declaration_database.find(symbol_name);
477 const Declaration& declaration = symbol_it->second.begin()->second;
478 DeclarationAvailability availability = declaration.locations.begin()->availability;
479 if (availability.introduced >= 10000) {
480 continue;
481 }
482
483 printf("%s: not available in any platform\n", symbol_name.c_str());
484 failed = true;
485 }
486
Josh Gaobf8a2852016-05-27 11:59:09 -0700487 return !failed;
488}
489
Josh Gao62aaf8f2016-06-02 14:27:21 -0700490static void usage(bool help = false) {
491 fprintf(stderr, "Usage: versioner [OPTION]... [HEADER_PATH] [DEPS_PATH]\n");
492 if (!help) {
493 printf("Try 'versioner -h' for more information.\n");
494 exit(1);
495 } else {
496 fprintf(stderr, "Version headers at HEADER_PATH, with DEPS_PATH/ARCH/* on the include path\n");
Josh Gao9b5af7a2016-06-02 14:29:13 -0700497 fprintf(stderr, "Autodetects paths if HEADER_PATH and DEPS_PATH are not specified\n");
Josh Gao62aaf8f2016-06-02 14:27:21 -0700498 fprintf(stderr, "\n");
499 fprintf(stderr, "Target specification (defaults to all):\n");
500 fprintf(stderr, " -a API_LEVEL\tbuild with specified API level (can be repeated)\n");
501 fprintf(stderr, " \t\tvalid levels are %s\n", Join(supported_levels).c_str());
502 fprintf(stderr, " -r ARCH\tbuild with specified architecture (can be repeated)\n");
503 fprintf(stderr, " \t\tvalid architectures are %s\n", Join(supported_archs).c_str());
504 fprintf(stderr, "\n");
505 fprintf(stderr, "Validation:\n");
506 fprintf(stderr, " -p PATH\tcompare against NDK platform at PATH\n");
507 fprintf(stderr, " -v\t\tenable verbose warnings\n");
508 fprintf(stderr, "\n");
509 fprintf(stderr, "Miscellaneous:\n");
510 fprintf(stderr, " -h\t\tdisplay this message\n");
511 exit(0);
512 }
Josh Gaobf8a2852016-05-27 11:59:09 -0700513}
514
515int main(int argc, char** argv) {
516 std::string cwd = getWorkingDir() + "/";
517 bool default_args = true;
518 std::string platform_dir;
519 std::set<std::string> selected_architectures;
520 std::set<int> selected_levels;
521
522 int c;
Josh Gao62aaf8f2016-06-02 14:27:21 -0700523 while ((c = getopt(argc, argv, "a:r:p:vh")) != -1) {
Josh Gaobf8a2852016-05-27 11:59:09 -0700524 default_args = false;
525 switch (c) {
526 case 'a': {
527 char* end;
528 int api_level = strtol(optarg, &end, 10);
529 if (end == optarg || strlen(end) > 0) {
530 usage();
531 }
532
533 if (supported_levels.count(api_level) == 0) {
534 errx(1, "unsupported API level %d", api_level);
535 }
536
537 selected_levels.insert(api_level);
538 break;
539 }
540
541 case 'r': {
542 if (supported_archs.count(optarg) == 0) {
543 errx(1, "unsupported architecture: %s", optarg);
544 }
545 selected_architectures.insert(optarg);
546 break;
547 }
548
549 case 'p': {
550 if (!platform_dir.empty()) {
551 usage();
552 }
553
554 platform_dir = optarg;
555
556 struct stat st;
557 if (stat(platform_dir.c_str(), &st) != 0) {
558 err(1, "failed to stat platform directory '%s'", platform_dir.c_str());
559 }
560 if (!S_ISDIR(st.st_mode)) {
561 errx(1, "'%s' is not a directory", optarg);
562 }
563 break;
564 }
565
566 case 'v':
567 verbose = true;
568 break;
569
Josh Gao62aaf8f2016-06-02 14:27:21 -0700570 case 'h':
571 usage(true);
572 break;
573
Josh Gaobf8a2852016-05-27 11:59:09 -0700574 default:
575 usage();
576 break;
577 }
578 }
579
Josh Gao9b5af7a2016-06-02 14:29:13 -0700580 if (argc - optind > 2 || optind > argc) {
Josh Gaobf8a2852016-05-27 11:59:09 -0700581 usage();
582 }
583
Josh Gao9b5af7a2016-06-02 14:29:13 -0700584 std::string header_dir;
585 std::string dependency_dir;
586
587 if (optind == argc) {
588 // Neither HEADER_PATH nor DEPS_PATH were specified, so try to figure them out.
589 const char* top = getenv("ANDROID_BUILD_TOP");
590 if (!top) {
591 fprintf(stderr, "versioner: failed to autodetect bionic paths. Is ANDROID_BUILD_TOP set?\n");
592 usage();
593 }
594
595 std::string versioner_dir = std::to_string(top) + "/bionic/tools/versioner";
596 header_dir = versioner_dir + "/current";
597 dependency_dir = versioner_dir + "/dependencies";
598 if (platform_dir.empty()) {
599 platform_dir = versioner_dir + "/platforms";
600 }
601 } else {
602 header_dir = argv[optind];
603
604 if (argc - optind == 2) {
605 dependency_dir = argv[optind + 1];
606 }
607 }
608
Josh Gaobf8a2852016-05-27 11:59:09 -0700609 if (selected_levels.empty()) {
610 selected_levels = supported_levels;
611 }
612
613 if (selected_architectures.empty()) {
614 selected_architectures = supported_archs;
615 }
616
Josh Gaobf8a2852016-05-27 11:59:09 -0700617
618 struct stat st;
Josh Gao9b5af7a2016-06-02 14:29:13 -0700619 if (stat(header_dir.c_str(), &st) != 0) {
620 err(1, "failed to stat '%s'", header_dir.c_str());
Josh Gaobf8a2852016-05-27 11:59:09 -0700621 } else if (!S_ISDIR(st.st_mode)) {
Josh Gao9b5af7a2016-06-02 14:29:13 -0700622 errx(1, "'%s' is not a directory", header_dir.c_str());
Josh Gaobf8a2852016-05-27 11:59:09 -0700623 }
624
625 std::set<CompilationType> compilation_types;
626 DeclarationDatabase declaration_database;
627 NdkSymbolDatabase symbol_database;
628
629 compilation_types = generateCompilationTypes(selected_architectures, selected_levels);
630
631 // Do this before compiling so that we can early exit if the platforms don't match what we
632 // expect.
633 if (!platform_dir.empty()) {
634 symbol_database = parsePlatforms(compilation_types, platform_dir);
635 }
636
637 bool failed = false;
Josh Gao9b5af7a2016-06-02 14:29:13 -0700638 declaration_database = compileHeaders(compilation_types, header_dir, dependency_dir, &failed);
Josh Gaobf8a2852016-05-27 11:59:09 -0700639
640 if (!sanityCheck(compilation_types, declaration_database)) {
641 printf("versioner: sanity check failed\n");
642 failed = true;
643 }
644
645 if (!platform_dir.empty()) {
646 if (!checkVersions(compilation_types, declaration_database, symbol_database)) {
647 printf("versioner: version check failed\n");
648 failed = true;
649 }
650 }
651
652 return failed;
653}