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