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