1 /* 2 * Copyright (C) 2015, 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 "aidl.h" 18 19 #include <fcntl.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #include <sys/param.h> 24 #include <sys/stat.h> 25 #include <unistd.h> 26 #include <algorithm> 27 #include <iostream> 28 #include <map> 29 #include <memory> 30 31 #ifdef _WIN32 32 #include <io.h> 33 #include <direct.h> 34 #include <sys/stat.h> 35 #endif 36 37 #include <android-base/strings.h> 38 39 #include "aidl_checkapi.h" 40 #include "aidl_dumpapi.h" 41 #include "aidl_language.h" 42 #include "aidl_typenames.h" 43 #include "generate_aidl_mappings.h" 44 #include "generate_cpp.h" 45 #include "generate_java.h" 46 #include "generate_ndk.h" 47 #include "generate_rust.h" 48 #include "import_resolver.h" 49 #include "logging.h" 50 #include "options.h" 51 #include "os.h" 52 #include "parser.h" 53 54 #ifndef O_BINARY 55 # define O_BINARY 0 56 #endif 57 58 using android::base::Join; 59 using android::base::Split; 60 using std::set; 61 using std::string; 62 using std::unique_ptr; 63 using std::unordered_set; 64 using std::vector; 65 66 namespace android { 67 namespace aidl { 68 namespace { 69 70 // Copied from android.is.IBinder.[FIRST|LAST]_CALL_TRANSACTION 71 const int kFirstCallTransaction = 1; 72 const int kLastCallTransaction = 0x00ffffff; 73 74 // Following IDs are all offsets from kFirstCallTransaction 75 76 // IDs for meta transactions. Most of the meta transactions are implemented in 77 // the framework side (Binder.java or Binder.cpp). But these are the ones that 78 // are auto-implemented by the AIDL compiler. 79 const int kFirstMetaMethodId = kLastCallTransaction - kFirstCallTransaction; 80 const int kGetInterfaceVersionId = kFirstMetaMethodId; 81 const int kGetInterfaceHashId = kFirstMetaMethodId - 1; 82 // Additional meta transactions implemented by AIDL should use 83 // kFirstMetaMethodId -1, -2, ...and so on. 84 85 // Reserve 100 IDs for meta methods, which is more than enough. If we don't reserve, 86 // in the future, a newly added meta transaction ID will have a chance to 87 // collide with the user-defined methods that were added in the past. So, 88 // let's prevent users from using IDs in this range from the beginning. 89 const int kLastMetaMethodId = kFirstMetaMethodId - 99; 90 91 // Range of IDs that is allowed for user-defined methods. 92 const int kMinUserSetMethodId = 0; 93 const int kMaxUserSetMethodId = kLastMetaMethodId - 1; 94 95 bool check_filename(const std::string& filename, const AidlDefinedType& defined_type) { 96 const char* p; 97 string expected; 98 string fn; 99 size_t len; 100 bool valid = false; 101 102 if (!IoDelegate::GetAbsolutePath(filename, &fn)) { 103 return false; 104 } 105 106 const std::string package = defined_type.GetPackage(); 107 if (!package.empty()) { 108 expected = package; 109 expected += '.'; 110 } 111 112 len = expected.length(); 113 for (size_t i=0; i<len; i++) { 114 if (expected[i] == '.') { 115 expected[i] = OS_PATH_SEPARATOR; 116 } 117 } 118 119 const std::string name = defined_type.GetName(); 120 expected.append(name, 0, name.find('.')); 121 122 expected += ".aidl"; 123 124 len = fn.length(); 125 valid = (len >= expected.length()); 126 127 if (valid) { 128 p = fn.c_str() + (len - expected.length()); 129 130 #ifdef _WIN32 131 if (OS_PATH_SEPARATOR != '/') { 132 // Input filename under cygwin most likely has / separators 133 // whereas the expected string uses \\ separators. Adjust 134 // them accordingly. 135 for (char *c = const_cast<char *>(p); *c; ++c) { 136 if (*c == '/') *c = OS_PATH_SEPARATOR; 137 } 138 } 139 #endif 140 141 // aidl assumes case-insensitivity on Mac Os and Windows. 142 #if defined(__linux__) 143 valid = (expected == p); 144 #else 145 valid = !strcasecmp(expected.c_str(), p); 146 #endif 147 } 148 149 if (!valid) { 150 AIDL_ERROR(defined_type) << name << " should be declared in a file called " << expected; 151 } 152 153 return valid; 154 } 155 156 bool write_dep_file(const Options& options, const AidlDefinedType& defined_type, 157 const vector<string>& imports, const IoDelegate& io_delegate, 158 const string& input_file, const string& output_file) { 159 string dep_file_name = options.DependencyFile(); 160 if (dep_file_name.empty() && options.AutoDepFile()) { 161 dep_file_name = output_file + ".d"; 162 } 163 164 if (dep_file_name.empty()) { 165 return true; // nothing to do 166 } 167 168 CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name); 169 if (!writer) { 170 AIDL_ERROR(dep_file_name) << "Could not open dependency file."; 171 return false; 172 } 173 174 vector<string> source_aidl = {input_file}; 175 for (const auto& import : imports) { 176 source_aidl.push_back(import); 177 } 178 179 // Encode that the output file depends on aidl input files. 180 if (defined_type.AsUnstructuredParcelable() != nullptr && 181 options.TargetLanguage() == Options::Language::JAVA) { 182 // Legacy behavior. For parcelable declarations in Java, don't emit output file as 183 // the dependency target. b/141372861 184 writer->Write(" : \\\n"); 185 } else { 186 writer->Write("%s : \\\n", output_file.c_str()); 187 } 188 writer->Write(" %s", Join(source_aidl, " \\\n ").c_str()); 189 writer->Write("\n"); 190 191 if (!options.DependencyFileNinja()) { 192 writer->Write("\n"); 193 // Output "<input_aidl_file>: " so make won't fail if the input .aidl file 194 // has been deleted, moved or renamed in incremental build. 195 for (const auto& src : source_aidl) { 196 writer->Write("%s :\n", src.c_str()); 197 } 198 } 199 200 if (options.IsCppOutput()) { 201 if (!options.DependencyFileNinja()) { 202 using ::android::aidl::cpp::ClassNames; 203 using ::android::aidl::cpp::HeaderFile; 204 vector<string> headers; 205 for (ClassNames c : {ClassNames::CLIENT, ClassNames::SERVER, ClassNames::RAW}) { 206 headers.push_back(options.OutputHeaderDir() + 207 HeaderFile(defined_type, c, false /* use_os_sep */)); 208 } 209 210 writer->Write("\n"); 211 212 // Generated headers also depend on the source aidl files. 213 writer->Write("%s : \\\n %s\n", Join(headers, " \\\n ").c_str(), 214 Join(source_aidl, " \\\n ").c_str()); 215 } 216 } 217 218 return true; 219 } 220 221 // Returns the path to the destination file of `defined_type`. 222 string GetOutputFilePath(const Options& options, const AidlDefinedType& defined_type) { 223 string result = options.OutputDir(); 224 225 // add the package 226 string package = defined_type.GetPackage(); 227 if (!package.empty()) { 228 for (auto& c : package) { 229 if (c == '.') { 230 c = OS_PATH_SEPARATOR; 231 } 232 } 233 result += package; 234 result += OS_PATH_SEPARATOR; 235 } 236 237 // add the filename 238 result += defined_type.GetName(); 239 if (options.TargetLanguage() == Options::Language::JAVA) { 240 result += ".java"; 241 } else if (options.IsCppOutput()) { 242 result += ".cpp"; 243 } else if (options.TargetLanguage() == Options::Language::RUST) { 244 result += ".rs"; 245 } else { 246 AIDL_FATAL("Unknown target language"); 247 return ""; 248 } 249 250 return result; 251 } 252 253 bool check_and_assign_method_ids(const std::vector<std::unique_ptr<AidlMethod>>& items) { 254 // Check whether there are any methods with manually assigned id's and any 255 // that are not. Either all method id's must be manually assigned or all of 256 // them must not. Also, check for uplicates of user set ID's and that the 257 // ID's are within the proper bounds. 258 set<int> usedIds; 259 bool hasUnassignedIds = false; 260 bool hasAssignedIds = false; 261 int newId = kMinUserSetMethodId; 262 for (const auto& item : items) { 263 // However, meta transactions that are added by the AIDL compiler are 264 // exceptions. They have fixed IDs but allowed to be with user-defined 265 // methods having auto-assigned IDs. This is because the Ids of the meta 266 // transactions must be stable during the entire lifetime of an interface. 267 // In other words, their IDs must be the same even when new user-defined 268 // methods are added. 269 if (!item->IsUserDefined()) { 270 continue; 271 } 272 if (item->HasId()) { 273 hasAssignedIds = true; 274 } else { 275 item->SetId(newId++); 276 hasUnassignedIds = true; 277 } 278 279 if (hasAssignedIds && hasUnassignedIds) { 280 AIDL_ERROR(item) << "You must either assign id's to all methods or to none of them."; 281 return false; 282 } 283 284 // Ensure that the user set id is not duplicated. 285 if (usedIds.find(item->GetId()) != usedIds.end()) { 286 // We found a duplicate id, so throw an error. 287 AIDL_ERROR(item) << "Found duplicate method id (" << item->GetId() << ") for method " 288 << item->GetName(); 289 return false; 290 } 291 usedIds.insert(item->GetId()); 292 293 // Ensure that the user set id is within the appropriate limits 294 if (item->GetId() < kMinUserSetMethodId || item->GetId() > kMaxUserSetMethodId) { 295 AIDL_ERROR(item) << "Found out of bounds id (" << item->GetId() << ") for method " 296 << item->GetName() << ". Value for id must be between " 297 << kMinUserSetMethodId << " and " << kMaxUserSetMethodId << " inclusive."; 298 return false; 299 } 300 } 301 302 return true; 303 } 304 305 // TODO: Remove this in favor of using the YACC parser b/25479378 306 bool ParsePreprocessedLine(const string& line, string* decl, std::string* package, 307 string* class_name) { 308 // erase all trailing whitespace and semicolons 309 const size_t end = line.find_last_not_of(" ;\t"); 310 if (end == string::npos) { 311 return false; 312 } 313 if (line.rfind(';', end) != string::npos) { 314 return false; 315 } 316 317 decl->clear(); 318 string type; 319 vector<string> pieces = Split(line.substr(0, end + 1), " \t"); 320 for (const string& piece : pieces) { 321 if (piece.empty()) { 322 continue; 323 } 324 if (decl->empty()) { 325 *decl = std::move(piece); 326 } else if (type.empty()) { 327 type = std::move(piece); 328 } else { 329 return false; 330 } 331 } 332 333 // Note that this logic is absolutely wrong. Given a parcelable 334 // org.some.Foo.Bar, the class name is Foo.Bar, but this code will claim that 335 // the class is just Bar. However, this was the way it was done in the past. 336 // 337 // See b/17415692 338 size_t dot_pos = type.rfind('.'); 339 if (dot_pos != string::npos) { 340 *class_name = type.substr(dot_pos + 1); 341 *package = type.substr(0, dot_pos); 342 } else { 343 *class_name = type; 344 package->clear(); 345 } 346 347 return true; 348 } 349 350 bool ValidateAnnotationContext(const AidlDocument& doc) { 351 struct AnnotationValidator : AidlVisitor { 352 bool success = true; 353 354 void Check(const AidlAnnotatable& annotatable, AidlAnnotation::TargetContext context) { 355 for (const auto& annot : annotatable.GetAnnotations()) { 356 if (!annot.CheckContext(context)) { 357 success = false; 358 } 359 } 360 } 361 void Visit(const AidlInterface& m) override { 362 Check(m, AidlAnnotation::CONTEXT_TYPE_INTERFACE); 363 } 364 void Visit(const AidlParcelable& m) override { 365 Check(m, AidlAnnotation::CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE); 366 } 367 void Visit(const AidlStructuredParcelable& m) override { 368 Check(m, AidlAnnotation::CONTEXT_TYPE_STRUCTURED_PARCELABLE); 369 } 370 void Visit(const AidlEnumDeclaration& m) override { 371 Check(m, AidlAnnotation::CONTEXT_TYPE_ENUM); 372 } 373 void Visit(const AidlUnionDecl& m) override { Check(m, AidlAnnotation::CONTEXT_TYPE_UNION); } 374 void Visit(const AidlMethod& m) override { 375 Check(m.GetType(), AidlAnnotation::CONTEXT_TYPE_SPECIFIER | AidlAnnotation::CONTEXT_METHOD); 376 for (const auto& arg : m.GetArguments()) { 377 Check(arg->GetType(), AidlAnnotation::CONTEXT_TYPE_SPECIFIER); 378 } 379 } 380 void Visit(const AidlConstantDeclaration& m) override { 381 Check(m.GetType(), AidlAnnotation::CONTEXT_TYPE_SPECIFIER | AidlAnnotation::CONTEXT_CONST); 382 } 383 void Visit(const AidlVariableDeclaration& m) override { 384 Check(m.GetType(), AidlAnnotation::CONTEXT_TYPE_SPECIFIER | AidlAnnotation::CONTEXT_FIELD); 385 } 386 void Visit(const AidlTypeSpecifier& m) override { 387 // nested generic type parameters are checked as well 388 if (m.IsGeneric()) { 389 for (const auto& tp : m.GetTypeParameters()) { 390 Check(*tp, AidlAnnotation::CONTEXT_TYPE_SPECIFIER); 391 } 392 } 393 } 394 }; 395 396 AnnotationValidator validator; 397 VisitTopDown(validator, doc); 398 return validator.success; 399 } 400 401 } // namespace 402 403 namespace internals { 404 405 bool parse_preprocessed_file(const IoDelegate& io_delegate, const string& filename, 406 AidlTypenames* typenames) { 407 bool success = true; 408 unique_ptr<LineReader> line_reader = io_delegate.GetLineReader(filename); 409 if (!line_reader) { 410 AIDL_ERROR(filename) << "cannot open preprocessed file"; 411 success = false; 412 return success; 413 } 414 415 string line; 416 int lineno = 1; 417 for ( ; line_reader->ReadLine(&line); ++lineno) { 418 if (line.empty() || line.compare(0, 2, "//") == 0) { 419 // skip comments and empty lines 420 continue; 421 } 422 423 string decl; 424 std::string package; 425 string class_name; 426 if (!ParsePreprocessedLine(line, &decl, &package, &class_name)) { 427 success = false; 428 break; 429 } 430 431 AidlLocation::Point point = {.line = lineno, .column = 0 /*column*/}; 432 AidlLocation location = AidlLocation(filename, point, point, AidlLocation::Source::EXTERNAL); 433 434 if (decl == "parcelable") { 435 // ParcelFileDescriptor is treated as a built-in type, but it's also in the framework.aidl. 436 // So aidl should ignore built-in types in framework.aidl to prevent duplication. 437 // (b/130899491) 438 if (AidlTypenames::IsBuiltinTypename(class_name)) { 439 continue; 440 } 441 AidlParcelable* doc = new AidlParcelable(location, class_name, package, Comments{}); 442 typenames->AddPreprocessedType(unique_ptr<AidlParcelable>(doc)); 443 } else if (decl == "structured_parcelable") { 444 AidlStructuredParcelable* doc = 445 new AidlStructuredParcelable(location, class_name, package, Comments{}, nullptr, nullptr); 446 typenames->AddPreprocessedType(unique_ptr<AidlStructuredParcelable>(doc)); 447 } else if (decl == "interface") { 448 AidlInterface* doc = 449 new AidlInterface(location, class_name, Comments{}, false, package, nullptr); 450 typenames->AddPreprocessedType(unique_ptr<AidlInterface>(doc)); 451 } else { 452 success = false; 453 break; 454 } 455 } 456 if (!success) { 457 AIDL_ERROR(filename) << " on line " << lineno << " malformed preprocessed file line: '" << line 458 << "'"; 459 } 460 461 return success; 462 } 463 464 AidlError load_and_validate_aidl(const std::string& input_file_name, const Options& options, 465 const IoDelegate& io_delegate, AidlTypenames* typenames, 466 vector<string>* imported_files) { 467 AidlError err = AidlError::OK; 468 469 ////////////////////////////////////////////////////////////////////////// 470 // Loading phase 471 ////////////////////////////////////////////////////////////////////////// 472 473 // Parse the main input file 474 std::unique_ptr<Parser> main_parser = Parser::Parse(input_file_name, io_delegate, *typenames); 475 if (main_parser == nullptr) { 476 return AidlError::PARSE_ERROR; 477 } 478 int num_top_level_decls = 0; 479 for (const auto& type : main_parser->ParsedDocument().DefinedTypes()) { 480 if (type->AsUnstructuredParcelable() == nullptr) { 481 num_top_level_decls++; 482 if (num_top_level_decls > 1) { 483 AIDL_ERROR(*type) << "You must declare only one type per file."; 484 return AidlError::BAD_TYPE; 485 } 486 } 487 } 488 489 // Import the preprocessed file 490 for (const string& s : options.PreprocessedFiles()) { 491 if (!parse_preprocessed_file(io_delegate, s, typenames)) { 492 err = AidlError::BAD_PRE_PROCESSED_FILE; 493 } 494 } 495 if (err != AidlError::OK) { 496 return err; 497 } 498 499 // Find files to import and parse them 500 vector<string> import_paths; 501 ImportResolver import_resolver{io_delegate, input_file_name, options.ImportDirs(), 502 options.InputFiles()}; 503 for (const auto& import : main_parser->ParsedDocument().Imports()) { 504 if (AidlTypenames::IsBuiltinTypename(import->GetNeededClass())) { 505 continue; 506 } 507 if (typenames->IsIgnorableImport(import->GetNeededClass())) { 508 // There are places in the Android tree where an import doesn't resolve, 509 // but we'll pick the type up through the preprocessed types. 510 // This seems like an error, but legacy support demands we support it... 511 continue; 512 } 513 string import_path = import_resolver.FindImportFile(import->GetNeededClass()); 514 if (import_path.empty()) { 515 if (typenames->ResolveTypename(import->GetNeededClass()).is_resolved) { 516 // This could happen when the type is from the preprocessed aidl file. 517 // In that case, use the type from preprocessed aidl file 518 continue; 519 } 520 AIDL_ERROR(input_file_name) << "Couldn't find import for class " << import->GetNeededClass(); 521 err = AidlError::BAD_IMPORT; 522 continue; 523 } 524 525 import_paths.emplace_back(import_path); 526 527 std::unique_ptr<Parser> import_parser = Parser::Parse(import_path, io_delegate, *typenames); 528 if (import_parser == nullptr) { 529 AIDL_ERROR(import_path) << "error while importing " << import_path << " for " << import; 530 err = AidlError::BAD_IMPORT; 531 continue; 532 } 533 } 534 if (err != AidlError::OK) { 535 return err; 536 } 537 538 for (const auto& imported_file : options.ImportFiles()) { 539 import_paths.emplace_back(imported_file); 540 541 std::unique_ptr<Parser> import_parser = Parser::Parse(imported_file, io_delegate, *typenames); 542 if (import_parser == nullptr) { 543 AIDL_ERROR(imported_file) << "error while importing " << imported_file; 544 err = AidlError::BAD_IMPORT; 545 continue; 546 } 547 } 548 if (err != AidlError::OK) { 549 return err; 550 } 551 552 TypeResolver resolver = [&](const AidlDocument* doc, AidlTypeSpecifier* type) { 553 if (type->Resolve(*typenames)) return true; 554 555 const string unresolved_name = type->GetUnresolvedName(); 556 const std::optional<string> canonical_name = doc->ResolveName(unresolved_name); 557 if (!canonical_name) { 558 return false; 559 } 560 const string import_path = import_resolver.FindImportFile(*canonical_name); 561 if (import_path.empty()) { 562 return false; 563 } 564 import_paths.push_back(import_path); 565 566 std::unique_ptr<Parser> import_parser = Parser::Parse(import_path, io_delegate, *typenames); 567 if (import_parser == nullptr) { 568 AIDL_ERROR(import_path) << "error while importing " << import_path << " for " << import_path; 569 return false; 570 } 571 if (!type->Resolve(*typenames)) { 572 AIDL_ERROR(type) << "Can't resolve " << type->GetName(); 573 return false; 574 } 575 return true; 576 }; 577 const bool is_check_api = options.GetTask() == Options::Task::CHECK_API; 578 const bool is_dump_api = options.GetTask() == Options::Task::DUMP_API; 579 580 // Resolve the unresolved type references found from the input file 581 if (!is_check_api && !main_parser->Resolve(resolver)) { 582 // Resolution is not need for check api because all typespecs are 583 // using fully qualified names. 584 return AidlError::BAD_TYPE; 585 } 586 587 if (!typenames->Autofill()) { 588 return AidlError::BAD_TYPE; 589 } 590 591 ////////////////////////////////////////////////////////////////////////// 592 // Validation phase 593 ////////////////////////////////////////////////////////////////////////// 594 595 // For legacy reasons, by default, compiling an unstructured parcelable (which contains no output) 596 // is allowed. This must not be returned as an error until the very end of this procedure since 597 // this may be considered a success, and we should first check that there are not other, more 598 // serious failures. 599 bool contains_unstructured_parcelable = false; 600 601 const auto& types = main_parser->ParsedDocument().DefinedTypes(); 602 const int num_defined_types = types.size(); 603 for (const auto& defined_type : types) { 604 AIDL_FATAL_IF(defined_type == nullptr, main_parser->FileName()); 605 606 // Ensure type is exactly one of the following: 607 AidlInterface* interface = defined_type->AsInterface(); 608 AidlStructuredParcelable* parcelable = defined_type->AsStructuredParcelable(); 609 AidlParcelable* unstructured_parcelable = defined_type->AsUnstructuredParcelable(); 610 AidlEnumDeclaration* enum_decl = defined_type->AsEnumDeclaration(); 611 AidlUnionDecl* union_decl = defined_type->AsUnionDeclaration(); 612 AIDL_FATAL_IF( 613 !!interface + !!parcelable + !!unstructured_parcelable + !!enum_decl + !!union_decl != 1, 614 defined_type); 615 616 // Ensure that foo.bar.IFoo is defined in <some_path>/foo/bar/IFoo.aidl 617 if (num_defined_types == 1 && !check_filename(input_file_name, *defined_type)) { 618 return AidlError::BAD_PACKAGE; 619 } 620 621 { 622 bool valid_type = true; 623 624 if (!is_check_api) { 625 // Ideally, we could do this for check api, but we can't resolve imports 626 if (!defined_type->CheckValid(*typenames)) { 627 valid_type = false; 628 } 629 } 630 631 if (!is_dump_api && !is_check_api) { 632 if (!defined_type->LanguageSpecificCheckValid(*typenames, options.TargetLanguage())) { 633 valid_type = false; 634 } 635 } 636 637 if (!valid_type) { 638 return AidlError::BAD_TYPE; 639 } 640 } 641 642 if (unstructured_parcelable != nullptr) { 643 bool isStable = unstructured_parcelable->IsStableApiParcelable(options.TargetLanguage()); 644 if (options.IsStructured() && !isStable) { 645 AIDL_ERROR(unstructured_parcelable) 646 << "Cannot declared parcelable in a --structured interface. Parcelable must be defined " 647 "in AIDL directly."; 648 return AidlError::NOT_STRUCTURED; 649 } 650 if (options.FailOnParcelable()) { 651 AIDL_ERROR(unstructured_parcelable) 652 << "Refusing to generate code with unstructured parcelables. Declared parcelables " 653 "should be in their own file and/or cannot be used with --structured interfaces."; 654 // Continue parsing for more errors 655 } 656 657 contains_unstructured_parcelable = true; 658 } 659 660 if (defined_type->IsVintfStability()) { 661 bool success = true; 662 if (options.GetStability() != Options::Stability::VINTF) { 663 AIDL_ERROR(defined_type) 664 << "Must compile @VintfStability type w/ aidl_interface 'stability: \"vintf\"'"; 665 success = false; 666 } 667 if (!options.IsStructured()) { 668 AIDL_ERROR(defined_type) 669 << "Must compile @VintfStability type w/ aidl_interface --structured"; 670 success = false; 671 } 672 if (!success) return AidlError::NOT_STRUCTURED; 673 } 674 675 if (interface != nullptr) { 676 // add the meta-method 'int getInterfaceVersion()' if version is specified. 677 if (options.Version() > 0) { 678 AidlTypeSpecifier* ret = 679 new AidlTypeSpecifier(AIDL_LOCATION_HERE, "int", false, nullptr, Comments{}); 680 ret->Resolve(*typenames); 681 vector<unique_ptr<AidlArgument>>* args = new vector<unique_ptr<AidlArgument>>(); 682 auto method = std::make_unique<AidlMethod>( 683 AIDL_LOCATION_HERE, false, ret, "getInterfaceVersion", args, Comments{}, 684 kGetInterfaceVersionId, false /* is_user_defined */); 685 interface->AddMethod(std::move(method)); 686 } 687 // add the meta-method 'string getInterfaceHash()' if hash is specified. 688 if (!options.Hash().empty()) { 689 AidlTypeSpecifier* ret = 690 new AidlTypeSpecifier(AIDL_LOCATION_HERE, "String", false, nullptr, Comments{}); 691 ret->Resolve(*typenames); 692 vector<unique_ptr<AidlArgument>>* args = new vector<unique_ptr<AidlArgument>>(); 693 auto method = std::make_unique<AidlMethod>( 694 AIDL_LOCATION_HERE, false, ret, kGetInterfaceHash, args, Comments{}, 695 kGetInterfaceHashId, false /* is_user_defined */); 696 interface->AddMethod(std::move(method)); 697 } 698 if (!check_and_assign_method_ids(interface->GetMethods())) { 699 return AidlError::BAD_METHOD_ID; 700 } 701 } 702 // Verify the var/const declarations. 703 // const expressions should be non-empty when evaluated with the var/const type. 704 if (!is_check_api) { 705 for (const auto& constant : defined_type->GetConstantDeclarations()) { 706 if (constant->ValueString(AidlConstantValueDecorator).empty()) { 707 return AidlError::BAD_TYPE; 708 } 709 } 710 for (const auto& var : defined_type->GetFields()) { 711 if (var->GetDefaultValue() && var->ValueString(AidlConstantValueDecorator).empty()) { 712 return AidlError::BAD_TYPE; 713 } 714 } 715 } 716 } 717 718 if (!ValidateAnnotationContext(main_parser->ParsedDocument())) { 719 return AidlError::BAD_TYPE; 720 } 721 722 if (!is_check_api && !Diagnose(main_parser->ParsedDocument(), options.GetDiagnosticMapping())) { 723 return AidlError::BAD_TYPE; 724 } 725 726 typenames->IterateTypes([&](const AidlDefinedType& type) { 727 if (options.IsStructured() && type.AsUnstructuredParcelable() != nullptr && 728 !type.AsUnstructuredParcelable()->IsStableApiParcelable(options.TargetLanguage())) { 729 err = AidlError::NOT_STRUCTURED; 730 AIDL_ERROR(type) << type.GetCanonicalName() 731 << " is not structured, but this is a structured interface."; 732 } 733 if (options.GetStability() == Options::Stability::VINTF && !type.IsVintfStability()) { 734 err = AidlError::NOT_STRUCTURED; 735 AIDL_ERROR(type) << type.GetCanonicalName() 736 << " does not have VINTF level stability, but this interface requires it."; 737 } 738 739 // Ensure that untyped List/Map is not used in a parcelable, a union and a stable interface. 740 741 std::function<void(const AidlTypeSpecifier&, const AidlNode*)> check_untyped_container = 742 [&err, &check_untyped_container](const AidlTypeSpecifier& type, const AidlNode* node) { 743 if (type.IsGeneric()) { 744 std::for_each(type.GetTypeParameters().begin(), type.GetTypeParameters().end(), 745 [&node, &check_untyped_container](auto& nested) { 746 check_untyped_container(*nested, node); 747 }); 748 return; 749 } 750 if (type.GetName() == "List" || type.GetName() == "Map") { 751 err = AidlError::BAD_TYPE; 752 AIDL_ERROR(node) 753 << "Encountered an untyped List or Map. The use of untyped List/Map is prohibited " 754 << "because it is not guaranteed that the objects in the list are recognizable in " 755 << "the receiving side. Consider switching to an array or a generic List/Map."; 756 } 757 }; 758 759 if (type.AsInterface() && options.IsStructured()) { 760 for (const auto& method : type.GetMethods()) { 761 check_untyped_container(method->GetType(), method.get()); 762 for (const auto& arg : method->GetArguments()) { 763 check_untyped_container(arg->GetType(), method.get()); 764 } 765 } 766 } 767 for (const auto& field : type.GetFields()) { 768 check_untyped_container(field->GetType(), field.get()); 769 } 770 }); 771 772 if (err != AidlError::OK) { 773 return err; 774 } 775 776 if (imported_files != nullptr) { 777 *imported_files = import_paths; 778 } 779 780 if (contains_unstructured_parcelable) { 781 // Considered a success for the legacy case, so this must be returned last. 782 return AidlError::FOUND_PARCELABLE; 783 } 784 785 return AidlError::OK; 786 } 787 788 } // namespace internals 789 790 int compile_aidl(const Options& options, const IoDelegate& io_delegate) { 791 const Options::Language lang = options.TargetLanguage(); 792 for (const string& input_file : options.InputFiles()) { 793 AidlTypenames typenames; 794 795 vector<string> imported_files; 796 797 AidlError aidl_err = internals::load_and_validate_aidl(input_file, options, io_delegate, 798 &typenames, &imported_files); 799 bool allowError = aidl_err == AidlError::FOUND_PARCELABLE && !options.FailOnParcelable(); 800 if (aidl_err != AidlError::OK && !allowError) { 801 return 1; 802 } 803 804 for (const auto& defined_type : typenames.MainDocument().DefinedTypes()) { 805 AIDL_FATAL_IF(defined_type == nullptr, input_file); 806 807 string output_file_name = options.OutputFile(); 808 // if needed, generate the output file name from the base folder 809 if (output_file_name.empty() && !options.OutputDir().empty()) { 810 output_file_name = GetOutputFilePath(options, *defined_type); 811 if (output_file_name.empty()) { 812 return 1; 813 } 814 } 815 816 if (!write_dep_file(options, *defined_type, imported_files, io_delegate, input_file, 817 output_file_name)) { 818 return 1; 819 } 820 821 bool success = false; 822 if (lang == Options::Language::CPP) { 823 success = 824 cpp::GenerateCpp(output_file_name, options, typenames, *defined_type, io_delegate); 825 } else if (lang == Options::Language::NDK) { 826 ndk::GenerateNdk(output_file_name, options, typenames, *defined_type, io_delegate); 827 success = true; 828 } else if (lang == Options::Language::JAVA) { 829 if (defined_type->AsUnstructuredParcelable() != nullptr) { 830 // Legacy behavior. For parcelable declarations in Java, don't generate output file. 831 success = true; 832 } else { 833 success = java::generate_java(output_file_name, defined_type.get(), typenames, 834 io_delegate, options); 835 } 836 } else if (lang == Options::Language::RUST) { 837 success = rust::GenerateRust(output_file_name, defined_type.get(), typenames, io_delegate, 838 options); 839 } else { 840 AIDL_FATAL(input_file) << "Should not reach here."; 841 } 842 if (!success) { 843 return 1; 844 } 845 } 846 } 847 return 0; 848 } 849 850 bool dump_mappings(const Options& options, const IoDelegate& io_delegate) { 851 android::aidl::mappings::SignatureMap all_mappings; 852 for (const string& input_file : options.InputFiles()) { 853 AidlTypenames typenames; 854 vector<string> imported_files; 855 856 AidlError aidl_err = internals::load_and_validate_aidl(input_file, options, io_delegate, 857 &typenames, &imported_files); 858 if (aidl_err != AidlError::OK) { 859 return false; 860 } 861 for (const auto& defined_type : typenames.MainDocument().DefinedTypes()) { 862 auto mappings = mappings::generate_mappings(defined_type.get(), typenames); 863 all_mappings.insert(mappings.begin(), mappings.end()); 864 } 865 } 866 std::stringstream mappings_str; 867 for (const auto& mapping : all_mappings) { 868 mappings_str << mapping.first << "\n" << mapping.second << "\n"; 869 } 870 auto code_writer = io_delegate.GetCodeWriter(options.OutputFile()); 871 code_writer->Write("%s", mappings_str.str().c_str()); 872 return true; 873 } 874 875 bool preprocess_aidl(const Options& options, const IoDelegate& io_delegate) { 876 unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(options.OutputFile()); 877 878 for (const auto& file : options.InputFiles()) { 879 AidlTypenames typenames; 880 std::unique_ptr<Parser> p = Parser::Parse(file, io_delegate, typenames); 881 if (p == nullptr) return false; 882 883 for (const auto& defined_type : p->ParsedDocument().DefinedTypes()) { 884 if (!writer->Write("%s %s;\n", defined_type->GetPreprocessDeclarationName().c_str(), 885 defined_type->GetCanonicalName().c_str())) { 886 return false; 887 } 888 } 889 } 890 891 return writer->Close(); 892 } 893 894 int aidl_entry(const Options& options, const IoDelegate& io_delegate) { 895 AidlErrorLog::clearError(); 896 897 int ret = 1; 898 switch (options.GetTask()) { 899 case Options::Task::COMPILE: 900 ret = android::aidl::compile_aidl(options, io_delegate); 901 break; 902 case Options::Task::PREPROCESS: 903 ret = android::aidl::preprocess_aidl(options, io_delegate) ? 0 : 1; 904 break; 905 case Options::Task::DUMP_API: 906 ret = android::aidl::dump_api(options, io_delegate) ? 0 : 1; 907 break; 908 case Options::Task::CHECK_API: 909 ret = android::aidl::check_api(options, io_delegate) ? 0 : 1; 910 break; 911 case Options::Task::DUMP_MAPPINGS: 912 ret = android::aidl::dump_mappings(options, io_delegate) ? 0 : 1; 913 break; 914 default: 915 AIDL_FATAL(AIDL_LOCATION_HERE) 916 << "Unrecognized task: " << static_cast<size_t>(options.GetTask()); 917 } 918 919 // compiler invariants 920 const bool shouldReportError = ret != 0; 921 const bool reportedError = AidlErrorLog::hadError(); 922 AIDL_FATAL_IF(shouldReportError != reportedError, AIDL_LOCATION_HERE) 923 << "Compiler returned error " << ret << " but did" << (reportedError ? "" : " not") 924 << " emit error logs"; 925 926 return ret; 927 } 928 929 } // namespace aidl 930 } // namespace android 931