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