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