blob: 5068a4e80af354109c66b4908ce877aa89c5aaa5 [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
344 for (const auto& outer : declaration_database) {
345 const std::string& symbol_name = outer.first;
346 const auto& compilations = outer.second;
347
348 auto platform_availability_it = symbol_database.find(symbol_name);
349 if (platform_availability_it == symbol_database.end()) {
350 // This currently has lots of false positives (__INTRODUCED_IN_FUTURE, __errordecl, functions
351 // that come from crtbegin, etc.). Only print them with verbose, because of this.
352 if (verbose) {
353 printf("%s: not available in any platform\n", symbol_name.c_str());
354 }
355 continue;
356 }
357
358 const auto& platform_availability = platform_availability_it->second;
359 std::set<CompilationType> missing_symbol;
360 std::set<CompilationType> missing_decl;
361
362 for (const CompilationType& type : types) {
363 auto it = compilations.find(type);
364 if (it == compilations.end()) {
365 missing_decl.insert(type);
366 continue;
367 }
368
369 const Declaration& declaration = it->second;
370
371 // sanityCheck ensured that the availability declarations for a given arch match.
372 DeclarationAvailability availability = declaration.locations.begin()->availability;
373 int api_level = type.api_level;
374
375 int introduced = std::max(0, availability.introduced);
376 int obsoleted = availability.obsoleted == 0 ? INT_MAX : availability.obsoleted;
377 bool decl_available = api_level >= introduced && api_level < obsoleted;
378
379 auto symbol_availability_it = platform_availability.find(type);
380 bool symbol_available = symbol_availability_it != platform_availability.end();
381 if (decl_available) {
382 if (!symbol_available) {
383 // Make sure that either it exists in the platform, or an inline definition is visible.
384 if (!declaration.hasDefinition()) {
385 missing_symbol.insert(type);
386 continue;
387 }
388 } else {
389 // Make sure that symbols declared as functions/variables actually are.
390 switch (declaration.type()) {
391 case DeclarationType::inconsistent:
392 printf("%s: inconsistent declaration type\n", symbol_name.c_str());
393 declaration.dump();
394 exit(1);
395
396 case DeclarationType::variable:
397 if (symbol_availability_it->second != NdkSymbolType::variable) {
398 printf("%s: declared as variable, exists in platform as function\n",
399 symbol_name.c_str());
400 failed = true;
401 }
402 break;
403
404 case DeclarationType::function:
405 if (symbol_availability_it->second != NdkSymbolType::function) {
406 printf("%s: declared as function, exists in platform as variable\n",
407 symbol_name.c_str());
408 failed = true;
409 }
410 break;
411 }
412 }
413 } else {
414 // Make sure it's not available in the platform.
415 if (symbol_availability_it != platform_availability.end()) {
416 printf("%s: symbol should be unavailable in %s (declared with availability %s)\n",
417 symbol_name.c_str(), type.describe().c_str(), availability.describe().c_str());
418 failed = true;
419 }
420 }
421 }
422
423 // Allow declarations to be missing from an entire architecture.
424 for (const auto& arch_type : arch_types) {
425 const std::string& arch = arch_type.first;
426 bool found_all = true;
427 for (const auto& type : arch_type.second) {
428 if (missing_decl.find(type) == missing_decl.end()) {
429 found_all = false;
430 break;
431 }
432 }
433
434 if (!found_all) {
435 continue;
436 }
437
438 for (auto it = missing_decl.begin(); it != missing_decl.end();) {
439 if (it->arch == arch) {
440 it = missing_decl.erase(it);
441 } else {
442 ++it;
443 }
444 }
445 }
446
447 auto types_to_string = [](const std::set<CompilationType>& types) {
448 std::string result;
449 for (const CompilationType& type : types) {
450 result += type.describe();
451 result += ", ";
452 }
453 result.resize(result.length() - 2);
454 return result;
455 };
456
457 if (!missing_decl.empty()) {
458 printf("%s: declaration missing in %s\n", symbol_name.c_str(),
459 types_to_string(missing_decl).c_str());
460 failed = true;
461 }
462
463 if (!missing_symbol.empty()) {
464 printf("%s: declaration marked available but symbol missing in [%s]\n", symbol_name.c_str(),
465 types_to_string(missing_symbol).c_str());
466 failed = true;
467 }
468 }
469
470 return !failed;
471}
472
Josh Gao62aaf8f2016-06-02 14:27:21 -0700473static void usage(bool help = false) {
474 fprintf(stderr, "Usage: versioner [OPTION]... [HEADER_PATH] [DEPS_PATH]\n");
475 if (!help) {
476 printf("Try 'versioner -h' for more information.\n");
477 exit(1);
478 } else {
479 fprintf(stderr, "Version headers at HEADER_PATH, with DEPS_PATH/ARCH/* on the include path\n");
480 fprintf(stderr, "\n");
481 fprintf(stderr, "Target specification (defaults to all):\n");
482 fprintf(stderr, " -a API_LEVEL\tbuild with specified API level (can be repeated)\n");
483 fprintf(stderr, " \t\tvalid levels are %s\n", Join(supported_levels).c_str());
484 fprintf(stderr, " -r ARCH\tbuild with specified architecture (can be repeated)\n");
485 fprintf(stderr, " \t\tvalid architectures are %s\n", Join(supported_archs).c_str());
486 fprintf(stderr, "\n");
487 fprintf(stderr, "Validation:\n");
488 fprintf(stderr, " -p PATH\tcompare against NDK platform at PATH\n");
489 fprintf(stderr, " -v\t\tenable verbose warnings\n");
490 fprintf(stderr, "\n");
491 fprintf(stderr, "Miscellaneous:\n");
492 fprintf(stderr, " -h\t\tdisplay this message\n");
493 exit(0);
494 }
Josh Gaobf8a2852016-05-27 11:59:09 -0700495}
496
497int main(int argc, char** argv) {
498 std::string cwd = getWorkingDir() + "/";
499 bool default_args = true;
500 std::string platform_dir;
501 std::set<std::string> selected_architectures;
502 std::set<int> selected_levels;
503
504 int c;
Josh Gao62aaf8f2016-06-02 14:27:21 -0700505 while ((c = getopt(argc, argv, "a:r:p:vh")) != -1) {
Josh Gaobf8a2852016-05-27 11:59:09 -0700506 default_args = false;
507 switch (c) {
508 case 'a': {
509 char* end;
510 int api_level = strtol(optarg, &end, 10);
511 if (end == optarg || strlen(end) > 0) {
512 usage();
513 }
514
515 if (supported_levels.count(api_level) == 0) {
516 errx(1, "unsupported API level %d", api_level);
517 }
518
519 selected_levels.insert(api_level);
520 break;
521 }
522
523 case 'r': {
524 if (supported_archs.count(optarg) == 0) {
525 errx(1, "unsupported architecture: %s", optarg);
526 }
527 selected_architectures.insert(optarg);
528 break;
529 }
530
531 case 'p': {
532 if (!platform_dir.empty()) {
533 usage();
534 }
535
536 platform_dir = optarg;
537
538 struct stat st;
539 if (stat(platform_dir.c_str(), &st) != 0) {
540 err(1, "failed to stat platform directory '%s'", platform_dir.c_str());
541 }
542 if (!S_ISDIR(st.st_mode)) {
543 errx(1, "'%s' is not a directory", optarg);
544 }
545 break;
546 }
547
548 case 'v':
549 verbose = true;
550 break;
551
Josh Gao62aaf8f2016-06-02 14:27:21 -0700552 case 'h':
553 usage(true);
554 break;
555
Josh Gaobf8a2852016-05-27 11:59:09 -0700556 default:
557 usage();
558 break;
559 }
560 }
561
562 if (argc - optind > 2 || optind >= argc) {
563 usage();
564 }
565
566 if (selected_levels.empty()) {
567 selected_levels = supported_levels;
568 }
569
570 if (selected_architectures.empty()) {
571 selected_architectures = supported_archs;
572 }
573
574 std::string dependencies = (argc - optind == 2) ? argv[optind + 1] : "";
575 const char* header_dir = argv[optind];
576
577 struct stat st;
578 if (stat(header_dir, &st) != 0) {
579 err(1, "failed to stat '%s'", header_dir);
580 } else if (!S_ISDIR(st.st_mode)) {
581 errx(1, "'%s' is not a directory", header_dir);
582 }
583
584 std::set<CompilationType> compilation_types;
585 DeclarationDatabase declaration_database;
586 NdkSymbolDatabase symbol_database;
587
588 compilation_types = generateCompilationTypes(selected_architectures, selected_levels);
589
590 // Do this before compiling so that we can early exit if the platforms don't match what we
591 // expect.
592 if (!platform_dir.empty()) {
593 symbol_database = parsePlatforms(compilation_types, platform_dir);
594 }
595
596 bool failed = false;
597 declaration_database = compileHeaders(compilation_types, header_dir, dependencies, &failed);
598
599 if (!sanityCheck(compilation_types, declaration_database)) {
600 printf("versioner: sanity check failed\n");
601 failed = true;
602 }
603
604 if (!platform_dir.empty()) {
605 if (!checkVersions(compilation_types, declaration_database, symbol_database)) {
606 printf("versioner: version check failed\n");
607 failed = true;
608 }
609 }
610
611 return failed;
612}