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