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 #include "type_cpp.h"
50 #include "type_java.h"
51 #include "type_namespace.h"
52
53 #ifndef O_BINARY
54 # define O_BINARY 0
55 #endif
56
57 using android::base::Join;
58 using android::base::Split;
59 using std::cerr;
60 using std::endl;
61 using std::set;
62 using std::string;
63 using std::unique_ptr;
64 using std::vector;
65
66 namespace android {
67 namespace aidl {
68 namespace {
69
70 // Copied from android.is.IBinder.[FIRST|LAST]_CALL_TRANSACTION
71 const int kFirstCallTransaction = 1;
72 const int kLastCallTransaction = 0x00ffffff;
73
74 // Following IDs are all offsets from kFirstCallTransaction
75
76 // IDs for meta transactions. Most of the meta transactions are implemented in
77 // the framework side (Binder.java or Binder.cpp). But these are the ones that
78 // are auto-implemented by the AIDL compiler.
79 const int kFirstMetaMethodId = kLastCallTransaction - kFirstCallTransaction;
80 const int kGetInterfaceVersionId = kFirstMetaMethodId;
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
register_types(const AidlStructuredParcelable * parcel,TypeNamespace * types)155 bool register_types(const AidlStructuredParcelable* parcel, TypeNamespace* types) {
156 for (const auto& v : parcel->GetFields()) {
157 if (!types->MaybeAddContainerType(v->GetType())) {
158 return false;
159 }
160
161 const ValidatableType* type = types->GetReturnType(v->GetType(), *parcel);
162 if (type == nullptr) {
163 return false;
164 }
165 v->GetMutableType()->SetLanguageType(type);
166 }
167 return true;
168 }
169
register_types(const AidlInterface * c,TypeNamespace * types)170 bool register_types(const AidlInterface* c, TypeNamespace* types) {
171 for (const auto& m : c->GetMethods()) {
172 if (!types->MaybeAddContainerType(m->GetType())) {
173 return false;
174 }
175
176 const ValidatableType* return_type = types->GetReturnType(m->GetType(), *c);
177
178 if (return_type == nullptr) {
179 return false;
180 }
181 m->GetMutableType()->SetLanguageType(return_type);
182
183 set<string> argument_names;
184
185 int index = 1;
186 for (const auto& arg : m->GetArguments()) {
187 if (!types->MaybeAddContainerType(arg->GetType())) {
188 return false;
189 }
190
191 const ValidatableType* arg_type = types->GetArgType(*arg, index, *c);
192 if (arg_type == nullptr) {
193 return false;
194 }
195 arg->GetMutableType()->SetLanguageType(arg_type);
196 }
197 }
198
199 for (const std::unique_ptr<AidlConstantDeclaration>& constant : c->GetConstantDeclarations()) {
200 AidlTypeSpecifier* specifier = constant->GetMutableType();
201 const ValidatableType* return_type = types->GetReturnType(*specifier, *c);
202 if (return_type == nullptr) {
203 return false;
204 }
205 specifier->SetLanguageType(return_type);
206 }
207
208 return true;
209 }
210
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)211 bool write_dep_file(const Options& options, const AidlDefinedType& defined_type,
212 const vector<string>& imports, const IoDelegate& io_delegate,
213 const string& input_file, const string& output_file) {
214 string dep_file_name = options.DependencyFile();
215 if (dep_file_name.empty() && options.AutoDepFile()) {
216 dep_file_name = output_file + ".d";
217 }
218
219 if (dep_file_name.empty()) {
220 return true; // nothing to do
221 }
222
223 CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name);
224 if (!writer) {
225 LOG(ERROR) << "Could not open dependency file: " << dep_file_name;
226 return false;
227 }
228
229 vector<string> source_aidl = {input_file};
230 for (const auto& import : imports) {
231 source_aidl.push_back(import);
232 }
233
234 // Encode that the output file depends on aidl input files.
235 writer->Write("%s : \\\n", output_file.c_str());
236 writer->Write(" %s", Join(source_aidl, " \\\n ").c_str());
237 writer->Write("\n");
238
239 if (!options.DependencyFileNinja()) {
240 writer->Write("\n");
241 // Output "<input_aidl_file>: " so make won't fail if the input .aidl file
242 // has been deleted, moved or renamed in incremental build.
243 for (const auto& src : source_aidl) {
244 writer->Write("%s :\n", src.c_str());
245 }
246 }
247
248 if (options.IsCppOutput()) {
249 if (!options.DependencyFileNinja()) {
250 using ::android::aidl::cpp::ClassNames;
251 using ::android::aidl::cpp::HeaderFile;
252 vector<string> headers;
253 for (ClassNames c : {ClassNames::CLIENT, ClassNames::SERVER, ClassNames::RAW}) {
254 headers.push_back(options.OutputHeaderDir() +
255 HeaderFile(defined_type, c, false /* use_os_sep */));
256 }
257
258 writer->Write("\n");
259
260 // Generated headers also depend on the source aidl files.
261 writer->Write("%s : \\\n %s\n", Join(headers, " \\\n ").c_str(),
262 Join(source_aidl, " \\\n ").c_str());
263 }
264 }
265
266 return true;
267 }
268
generate_outputFileName(const Options & options,const AidlDefinedType & defined_type)269 string generate_outputFileName(const Options& options, const AidlDefinedType& defined_type) {
270 // create the path to the destination folder based on the
271 // defined_type package name
272 string result = options.OutputDir();
273
274 string package = defined_type.GetPackage();
275 size_t len = package.length();
276 for (size_t i = 0; i < len; i++) {
277 if (package[i] == '.') {
278 package[i] = OS_PATH_SEPARATOR;
279 }
280 }
281
282 result += package;
283
284 // add the filename by replacing the .aidl extension to .java
285 const string& name = defined_type.GetName();
286 result += OS_PATH_SEPARATOR;
287 result.append(name, 0, name.find('.'));
288 if (options.TargetLanguage() == Options::Language::JAVA) {
289 result += ".java";
290 } else if (options.IsCppOutput()) {
291 result += ".cpp";
292 } else {
293 LOG(FATAL) << "Should not reach here" << endl;
294 return "";
295 }
296
297 return result;
298 }
299
check_and_assign_method_ids(const std::vector<std::unique_ptr<AidlMethod>> & items)300 bool check_and_assign_method_ids(const std::vector<std::unique_ptr<AidlMethod>>& items) {
301 // Check whether there are any methods with manually assigned id's and any
302 // that are not. Either all method id's must be manually assigned or all of
303 // them must not. Also, check for uplicates of user set ID's and that the
304 // ID's are within the proper bounds.
305 set<int> usedIds;
306 bool hasUnassignedIds = false;
307 bool hasAssignedIds = false;
308 for (const auto& item : items) {
309 // However, meta transactions that are added by the AIDL compiler are
310 // exceptions. They have fixed IDs but allowed to be with user-defined
311 // methods having auto-assigned IDs. This is because the Ids of the meta
312 // transactions must be stable during the entire lifetime of an interface.
313 // In other words, their IDs must be the same even when new user-defined
314 // methods are added.
315 if (!item->IsUserDefined()) {
316 continue;
317 }
318 if (item->HasId()) {
319 hasAssignedIds = true;
320 // Ensure that the user set id is not duplicated.
321 if (usedIds.find(item->GetId()) != usedIds.end()) {
322 // We found a duplicate id, so throw an error.
323 AIDL_ERROR(item) << "Found duplicate method id (" << item->GetId() << ") for method "
324 << item->GetName();
325 return false;
326 }
327 // Ensure that the user set id is within the appropriate limits
328 if (item->GetId() < kMinUserSetMethodId || item->GetId() > kMaxUserSetMethodId) {
329 AIDL_ERROR(item) << "Found out of bounds id (" << item->GetId() << ") for method "
330 << item->GetName() << ". Value for id must be between "
331 << kMinUserSetMethodId << " and " << kMaxUserSetMethodId << " inclusive.";
332 return false;
333 }
334 usedIds.insert(item->GetId());
335 } else {
336 hasUnassignedIds = true;
337 }
338 if (hasAssignedIds && hasUnassignedIds) {
339 AIDL_ERROR(item) << "You must either assign id's to all methods or to none of them.";
340 return false;
341 }
342 }
343
344 // In the case that all methods have unassigned id's, set a unique id for them.
345 if (hasUnassignedIds) {
346 int newId = kMinUserSetMethodId;
347 for (const auto& item : items) {
348 assert(newId <= kMaxUserSetMethoId);
349 if (item->IsUserDefined()) {
350 item->SetId(newId++);
351 }
352 }
353 }
354 return true;
355 }
356
357 // TODO: Remove this in favor of using the YACC parser b/25479378
ParsePreprocessedLine(const string & line,string * decl,vector<string> * package,string * class_name)358 bool ParsePreprocessedLine(const string& line, string* decl,
359 vector<string>* package, string* class_name) {
360 // erase all trailing whitespace and semicolons
361 const size_t end = line.find_last_not_of(" ;\t");
362 if (end == string::npos) {
363 return false;
364 }
365 if (line.rfind(';', end) != string::npos) {
366 return false;
367 }
368
369 decl->clear();
370 string type;
371 vector<string> pieces = Split(line.substr(0, end + 1), " \t");
372 for (const string& piece : pieces) {
373 if (piece.empty()) {
374 continue;
375 }
376 if (decl->empty()) {
377 *decl = std::move(piece);
378 } else if (type.empty()) {
379 type = std::move(piece);
380 } else {
381 return false;
382 }
383 }
384
385 // Note that this logic is absolutely wrong. Given a parcelable
386 // org.some.Foo.Bar, the class name is Foo.Bar, but this code will claim that
387 // the class is just Bar. However, this was the way it was done in the past.
388 //
389 // See b/17415692
390 size_t dot_pos = type.rfind('.');
391 if (dot_pos != string::npos) {
392 *class_name = type.substr(dot_pos + 1);
393 *package = Split(type.substr(0, dot_pos), ".");
394 } else {
395 *class_name = type;
396 package->clear();
397 }
398
399 return true;
400 }
401
402 } // namespace
403
404 namespace internals {
405
parse_preprocessed_file(const IoDelegate & io_delegate,const string & filename,TypeNamespace * types,AidlTypenames & typenames)406 bool parse_preprocessed_file(const IoDelegate& io_delegate, const string& filename,
407 TypeNamespace* types, AidlTypenames& typenames) {
408 bool success = true;
409 unique_ptr<LineReader> line_reader = io_delegate.GetLineReader(filename);
410 if (!line_reader) {
411 LOG(ERROR) << "cannot open preprocessed file: " << filename;
412 success = false;
413 return success;
414 }
415
416 string line;
417 unsigned lineno = 1;
418 for ( ; line_reader->ReadLine(&line); ++lineno) {
419 if (line.empty() || line.compare(0, 2, "//") == 0) {
420 // skip comments and empty lines
421 continue;
422 }
423
424 string decl;
425 vector<string> package;
426 string class_name;
427 if (!ParsePreprocessedLine(line, &decl, &package, &class_name)) {
428 success = false;
429 break;
430 }
431
432 AidlLocation::Point point = {.line = lineno, .column = 0 /*column*/};
433 AidlLocation location = AidlLocation(filename, point, point);
434
435 if (decl == "parcelable") {
436 // ParcelFileDescriptor is treated as a built-in type, but it's also in the framework.aidl.
437 // So aidl should ignore built-in types in framework.aidl to prevent duplication.
438 // (b/130899491)
439 if (AidlTypenames::IsBuiltinTypename(class_name)) {
440 continue;
441 }
442 AidlParcelable* doc = new AidlParcelable(
443 location, new AidlQualifiedName(location, class_name, ""), package, "" /* comments */);
444 types->AddParcelableType(*doc, filename);
445 typenames.AddPreprocessedType(unique_ptr<AidlParcelable>(doc));
446 } else if (decl == "structured_parcelable") {
447 auto temp = new std::vector<std::unique_ptr<AidlVariableDeclaration>>();
448 AidlStructuredParcelable* doc =
449 new AidlStructuredParcelable(location, new AidlQualifiedName(location, class_name, ""),
450 package, "" /* comments */, temp);
451 types->AddParcelableType(*doc, filename);
452 typenames.AddPreprocessedType(unique_ptr<AidlStructuredParcelable>(doc));
453 } else if (decl == "interface") {
454 auto temp = new std::vector<std::unique_ptr<AidlMember>>();
455 AidlInterface* doc = new AidlInterface(location, class_name, "", false, temp, package);
456 types->AddBinderType(*doc, filename);
457 typenames.AddPreprocessedType(unique_ptr<AidlInterface>(doc));
458 } else {
459 success = false;
460 break;
461 }
462 }
463 if (!success) {
464 LOG(ERROR) << filename << ':' << lineno
465 << " malformed preprocessed file line: '" << line << "'";
466 }
467
468 return success;
469 }
470
load_and_validate_aidl(const std::string & input_file_name,const Options & options,const IoDelegate & io_delegate,TypeNamespace * types,vector<AidlDefinedType * > * defined_types,vector<string> * imported_files)471 AidlError load_and_validate_aidl(const std::string& input_file_name, const Options& options,
472 const IoDelegate& io_delegate, TypeNamespace* types,
473 vector<AidlDefinedType*>* defined_types,
474 vector<string>* imported_files) {
475 AidlError err = AidlError::OK;
476
477 //////////////////////////////////////////////////////////////////////////
478 // Loading phase
479 //////////////////////////////////////////////////////////////////////////
480
481 // Parse the main input file
482 std::unique_ptr<Parser> main_parser =
483 Parser::Parse(input_file_name, io_delegate, types->typenames_);
484 if (main_parser == nullptr) {
485 return AidlError::PARSE_ERROR;
486 }
487 if (!types->AddDefinedTypes(main_parser->GetDefinedTypes(), input_file_name)) {
488 return AidlError::BAD_TYPE;
489 }
490
491 // Import the preprocessed file
492 for (const string& s : options.PreprocessedFiles()) {
493 if (!parse_preprocessed_file(io_delegate, s, types, types->typenames_)) {
494 err = AidlError::BAD_PRE_PROCESSED_FILE;
495 }
496 }
497 if (err != AidlError::OK) {
498 return err;
499 }
500
501 // Find files to import and parse them
502 vector<string> import_paths;
503 ImportResolver import_resolver{io_delegate, input_file_name, options.ImportDirs(),
504 options.InputFiles()};
505
506 set<string> type_from_import_statements;
507 for (const auto& import : main_parser->GetImports()) {
508 if (!AidlTypenames::IsBuiltinTypename(import->GetNeededClass())) {
509 type_from_import_statements.emplace(import->GetNeededClass());
510 }
511 }
512
513 // When referencing a type using fully qualified name it should be imported
514 // without the import statement. To support that, add all unresolved
515 // typespecs encountered during the parsing to the import_candidates list.
516 // Note that there is no guarantee that the typespecs are all fully qualified.
517 // It will be determined by calling FindImportFile().
518 set<string> unresolved_types;
519 for (const auto type : main_parser->GetUnresolvedTypespecs()) {
520 if (!AidlTypenames::IsBuiltinTypename(type->GetName())) {
521 unresolved_types.emplace(type->GetName());
522 }
523 }
524 set<string> import_candidates(type_from_import_statements);
525 import_candidates.insert(unresolved_types.begin(), unresolved_types.end());
526 for (const auto& import : import_candidates) {
527 if (types->HasImportType(import)) {
528 // There are places in the Android tree where an import doesn't resolve,
529 // but we'll pick the type up through the preprocessed types.
530 // This seems like an error, but legacy support demands we support it...
531 continue;
532 }
533 string import_path = import_resolver.FindImportFile(import);
534 if (import_path.empty()) {
535 if (type_from_import_statements.find(import) != type_from_import_statements.end()) {
536 // Complain only when the import from the import statement has failed.
537 AIDL_ERROR(import) << "couldn't find import for class " << import;
538 err = AidlError::BAD_IMPORT;
539 }
540 continue;
541 }
542
543 import_paths.emplace_back(import_path);
544
545 std::unique_ptr<Parser> import_parser =
546 Parser::Parse(import_path, io_delegate, types->typenames_);
547 if (import_parser == nullptr) {
548 cerr << "error while importing " << import_path << " for " << import << endl;
549 err = AidlError::BAD_IMPORT;
550 continue;
551 }
552 if (!types->AddDefinedTypes(import_parser->GetDefinedTypes(), import_path)) {
553 return AidlError::BAD_TYPE;
554 }
555 }
556 if (err != AidlError::OK) {
557 return err;
558 }
559
560 for (const auto& imported_file : options.ImportFiles()) {
561 import_paths.emplace_back(imported_file);
562
563 std::unique_ptr<Parser> import_parser =
564 Parser::Parse(imported_file, io_delegate, types->typenames_);
565 if (import_parser == nullptr) {
566 AIDL_ERROR(imported_file) << "error while importing " << imported_file;
567 err = AidlError::BAD_IMPORT;
568 continue;
569 }
570 if (!types->AddDefinedTypes(import_parser->GetDefinedTypes(), imported_file)) {
571 return AidlError::BAD_TYPE;
572 }
573 }
574 if (err != AidlError::OK) {
575 return err;
576 }
577 const bool is_check_api = options.GetTask() == Options::Task::CHECK_API;
578
579 // Resolve the unresolved type references found from the input file
580 if (!is_check_api && !main_parser->Resolve()) {
581 // Resolution is not need for check api because all typespecs are
582 // using fully qualified names.
583 return AidlError::BAD_TYPE;
584 }
585 if (!is_check_api) {
586 for (const auto defined_type : main_parser->GetDefinedTypes()) {
587 AidlInterface* interface = defined_type->AsInterface();
588 AidlStructuredParcelable* parcelable = defined_type->AsStructuredParcelable();
589
590 // Link the AIDL type with the type of the target language. This will
591 // be removed when the migration to AidlTypenames is done.
592 defined_type->SetLanguageType(types->GetDefinedType(*defined_type));
593
594 if (interface != nullptr) {
595 if (!register_types(interface, types)) {
596 return AidlError::BAD_TYPE;
597 }
598 }
599 if (parcelable != nullptr) {
600 if (!register_types(parcelable, types)) {
601 return AidlError::BAD_TYPE;
602 }
603 }
604 }
605 }
606
607 //////////////////////////////////////////////////////////////////////////
608 // Validation phase
609 //////////////////////////////////////////////////////////////////////////
610
611 AidlTypenames& typenames = types->typenames_;
612
613 // For legacy reasons, by default, compiling an unstructured parcelable (which contains no output)
614 // is allowed. This must not be returned as an error until the very end of this procedure since
615 // this may be considered a success, and we should first check that there are not other, more
616 // serious failures.
617 bool contains_unstructured_parcelable = false;
618
619 const int num_defined_types = main_parser->GetDefinedTypes().size();
620 for (const auto defined_type : main_parser->GetDefinedTypes()) {
621 CHECK(defined_type != nullptr);
622 AidlParcelable* unstructuredParcelable = defined_type->AsUnstructuredParcelable();
623 if (unstructuredParcelable != nullptr) {
624 if (!unstructuredParcelable->CheckValid(typenames)) {
625 return AidlError::BAD_TYPE;
626 }
627 bool isStable = unstructuredParcelable->IsStableParcelable();
628 if (options.IsStructured() && !isStable) {
629 AIDL_ERROR(unstructuredParcelable)
630 << "Cannot declared parcelable in a --structured interface. Parcelable must be defined "
631 "in AIDL directly.";
632 return AidlError::NOT_STRUCTURED;
633 }
634 if (options.FailOnParcelable()) {
635 AIDL_ERROR(unstructuredParcelable)
636 << "Refusing to generate code with unstructured parcelables. Declared parcelables "
637 "should be in their own file and/or cannot be used with --structured interfaces.";
638 // Continue parsing for more errors
639 }
640
641 contains_unstructured_parcelable = true;
642 continue;
643 }
644
645 // Ensure that a type is either an interface or a structured parcelable
646 AidlInterface* interface = defined_type->AsInterface();
647 AidlStructuredParcelable* parcelable = defined_type->AsStructuredParcelable();
648 CHECK(interface != nullptr || parcelable != nullptr);
649
650 // Ensure that foo.bar.IFoo is defined in <some_path>/foo/bar/IFoo.aidl
651 if (num_defined_types == 1 && !check_filename(input_file_name, *defined_type)) {
652 return AidlError::BAD_PACKAGE;
653 }
654
655 // Check the referenced types in parsed_doc to make sure we've imported them
656 if (!is_check_api) {
657 // No need to do this for check api because all typespecs are already
658 // using fully qualified name and we don't import in AIDL files.
659 if (!defined_type->CheckValid(typenames)) {
660 return AidlError::BAD_TYPE;
661 }
662 }
663
664 if (interface != nullptr) {
665 // add the meta-method 'int getInterfaceVersion()' if version is specified.
666 if (options.Version() > 0) {
667 AidlTypeSpecifier* ret =
668 new AidlTypeSpecifier(AIDL_LOCATION_HERE, "int", false, nullptr, "");
669 ret->Resolve(typenames);
670 vector<unique_ptr<AidlArgument>>* args = new vector<unique_ptr<AidlArgument>>();
671 AidlMethod* method =
672 new AidlMethod(AIDL_LOCATION_HERE, false, ret, "getInterfaceVersion", args, "",
673 kGetInterfaceVersionId, false /* is_user_defined */);
674 interface->GetMutableMethods().emplace_back(method);
675 }
676 if (!check_and_assign_method_ids(interface->GetMethods())) {
677 return AidlError::BAD_METHOD_ID;
678 }
679 }
680 }
681
682 if (options.IsStructured()) {
683 typenames.IterateTypes([&](const AidlDefinedType& type) {
684 if (type.AsUnstructuredParcelable() != nullptr &&
685 !type.AsUnstructuredParcelable()->IsStableParcelable()) {
686 err = AidlError::NOT_STRUCTURED;
687 LOG(ERROR) << type.GetCanonicalName()
688 << " is not structured, but this is a structured interface.";
689 }
690 });
691 }
692 if (err != AidlError::OK) {
693 return err;
694 }
695
696 if (defined_types != nullptr) {
697 *defined_types = main_parser->GetDefinedTypes();
698 }
699
700 if (imported_files != nullptr) {
701 *imported_files = import_paths;
702 }
703
704 if (contains_unstructured_parcelable) {
705 // Considered a success for the legacy case, so this must be returned last.
706 return AidlError::FOUND_PARCELABLE;
707 }
708
709 return AidlError::OK;
710 }
711
712 } // namespace internals
713
compile_aidl(const Options & options,const IoDelegate & io_delegate)714 int compile_aidl(const Options& options, const IoDelegate& io_delegate) {
715 const Options::Language lang = options.TargetLanguage();
716 for (const string& input_file : options.InputFiles()) {
717 // Create type namespace that will hold the types identified by the parser.
718 // This two namespaces that are specific to the target language will be
719 // unified to AidlTypenames which is agnostic to the target language.
720 cpp::TypeNamespace cpp_types;
721 cpp_types.Init();
722
723 java::JavaTypeNamespace java_types;
724 java_types.Init();
725
726 TypeNamespace* types;
727 if (options.IsCppOutput()) {
728 types = &cpp_types;
729 } else if (lang == Options::Language::JAVA) {
730 types = &java_types;
731 } else {
732 LOG(FATAL) << "Unsupported target language." << endl;
733 return 1;
734 }
735
736 vector<AidlDefinedType*> defined_types;
737 vector<string> imported_files;
738
739 AidlError aidl_err = internals::load_and_validate_aidl(input_file, options, io_delegate, types,
740 &defined_types, &imported_files);
741 bool allowError = aidl_err == AidlError::FOUND_PARCELABLE && !options.FailOnParcelable();
742 if (aidl_err != AidlError::OK && !allowError) {
743 return 1;
744 }
745
746 for (const auto defined_type : defined_types) {
747 CHECK(defined_type != nullptr);
748
749 string output_file_name = options.OutputFile();
750 // if needed, generate the output file name from the base folder
751 if (output_file_name.empty() && !options.OutputDir().empty()) {
752 output_file_name = generate_outputFileName(options, *defined_type);
753 if (output_file_name.empty()) {
754 return 1;
755 }
756 }
757
758 if (!write_dep_file(options, *defined_type, imported_files, io_delegate, input_file,
759 output_file_name)) {
760 return 1;
761 }
762
763 bool success = false;
764 if (lang == Options::Language::CPP) {
765 success =
766 cpp::GenerateCpp(output_file_name, options, cpp_types, *defined_type, io_delegate);
767 } else if (lang == Options::Language::NDK) {
768 ndk::GenerateNdk(output_file_name, options, cpp_types.typenames_, *defined_type,
769 io_delegate);
770 success = true;
771 } else if (lang == Options::Language::JAVA) {
772 success =
773 java::generate_java(output_file_name, defined_type, &java_types, io_delegate, options);
774 } else {
775 LOG(FATAL) << "Should not reach here" << endl;
776 return 1;
777 }
778 if (!success) {
779 return 1;
780 }
781 }
782 }
783 return 0;
784 }
785
dump_mappings(const Options & options,const IoDelegate & io_delegate)786 bool dump_mappings(const Options& options, const IoDelegate& io_delegate) {
787 android::aidl::mappings::SignatureMap all_mappings;
788 for (const string& input_file : options.InputFiles()) {
789 java::JavaTypeNamespace java_types;
790 java_types.Init();
791 vector<AidlDefinedType*> defined_types;
792 vector<string> imported_files;
793
794 AidlError aidl_err = internals::load_and_validate_aidl(
795 input_file, options, io_delegate, &java_types, &defined_types, &imported_files);
796 if (aidl_err != AidlError::OK) {
797 LOG(WARNING) << "AIDL file is invalid.\n";
798 continue;
799 }
800 for (const auto defined_type : defined_types) {
801 auto mappings = mappings::generate_mappings(defined_type);
802 all_mappings.insert(mappings.begin(), mappings.end());
803 }
804 }
805 std::stringstream mappings_str;
806 for (const auto& mapping : all_mappings) {
807 mappings_str << mapping.first << "\n" << mapping.second << "\n";
808 }
809 auto code_writer = io_delegate.GetCodeWriter(options.OutputFile());
810 code_writer->Write("%s", mappings_str.str().c_str());
811 return true;
812 }
813
preprocess_aidl(const Options & options,const IoDelegate & io_delegate)814 bool preprocess_aidl(const Options& options, const IoDelegate& io_delegate) {
815 unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(options.OutputFile());
816
817 for (const auto& file : options.InputFiles()) {
818 AidlTypenames typenames;
819 std::unique_ptr<Parser> p = Parser::Parse(file, io_delegate, typenames);
820 if (p == nullptr) return false;
821
822 for (const auto& defined_type : p->GetDefinedTypes()) {
823 if (!writer->Write("%s %s;\n", defined_type->GetPreprocessDeclarationName().c_str(),
824 defined_type->GetCanonicalName().c_str())) {
825 return false;
826 }
827 }
828 }
829
830 return writer->Close();
831 }
832
GetApiDumpPathFor(const AidlDefinedType & defined_type,const Options & options)833 static string GetApiDumpPathFor(const AidlDefinedType& defined_type, const Options& options) {
834 string package_as_path = Join(Split(defined_type.GetPackage(), "."), OS_PATH_SEPARATOR);
835 CHECK(!options.OutputDir().empty() && options.OutputDir().back() == '/');
836 return options.OutputDir() + package_as_path + OS_PATH_SEPARATOR + defined_type.GetName() +
837 ".aidl";
838 }
839
dump_api(const Options & options,const IoDelegate & io_delegate)840 bool dump_api(const Options& options, const IoDelegate& io_delegate) {
841 for (const auto& file : options.InputFiles()) {
842 java::JavaTypeNamespace ns;
843 ns.Init();
844 vector<AidlDefinedType*> defined_types;
845 if (internals::load_and_validate_aidl(file, options, io_delegate, &ns, &defined_types,
846 nullptr) == AidlError::OK) {
847 for (const auto type : defined_types) {
848 unique_ptr<CodeWriter> writer =
849 io_delegate.GetCodeWriter(GetApiDumpPathFor(*type, options));
850 if (!type->GetPackage().empty()) {
851 (*writer) << "package " << type->GetPackage() << ";\n";
852 }
853 type->Write(writer.get());
854 }
855 } else {
856 return false;
857 }
858 }
859 return true;
860 }
861
862 } // namespace android
863 } // namespace aidl
864