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