blob: 94e8387145e84517e4cc9d35991c19b6f694933c [file] [log] [blame]
Christopher Wiley89eaab52015-09-15 14:46:46 -07001/*
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 */
Adam Lesinskiffa16862014-01-23 18:17:42 -080016
Christopher Wileyf690be52015-09-14 15:19:10 -070017#include "aidl.h"
Adam Lesinskiffa16862014-01-23 18:17:42 -080018
Christopher Wileyf690be52015-09-14 15:19:10 -070019#include <fcntl.h>
Adam Lesinskiffa16862014-01-23 18:17:42 -080020#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
Christopher Wileyf690be52015-09-14 15:19:10 -070023#include <sys/param.h>
24#include <sys/stat.h>
25#include <unistd.h>
Jiyong Park02da7422018-07-16 16:00:26 +090026#include <algorithm>
Jiyong Park1deecc32018-07-17 01:14:41 +090027#include <iostream>
28#include <map>
29#include <memory>
Adam Lesinskiffa16862014-01-23 18:17:42 -080030
Elliott Hughes549b6e22015-08-17 12:41:46 -070031#ifdef _WIN32
Adam Lesinskiffa16862014-01-23 18:17:42 -080032#include <io.h>
Andrew Hsieh15ce9942014-05-07 20:14:30 +080033#include <direct.h>
Adam Lesinskiffa16862014-01-23 18:17:42 -080034#include <sys/stat.h>
35#endif
36
Elliott Hughes0a620672015-12-04 13:53:18 -080037#include <android-base/strings.h>
Christopher Wileyf690be52015-09-14 15:19:10 -070038
Steven Moreland3981d9e2020-03-31 14:11:44 -070039#include "aidl_checkapi.h"
Christopher Wileyf690be52015-09-14 15:19:10 -070040#include "aidl_language.h"
Jiyong Parke05195e2018-10-08 18:24:23 +090041#include "aidl_typenames.h"
Andrei Onea8714b022019-02-01 18:55:54 +000042#include "generate_aidl_mappings.h"
Christopher Wileyeb1acc12015-09-16 11:25:13 -070043#include "generate_cpp.h"
Christopher Wileyf690be52015-09-14 15:19:10 -070044#include "generate_java.h"
Steven Morelandc26d8142018-09-17 14:25:33 -070045#include "generate_ndk.h"
Andrei Homescub62afd92020-05-11 19:24:59 -070046#include "generate_rust.h"
Christopher Wiley72877ac2015-10-06 14:41:42 -070047#include "import_resolver.h"
Christopher Wileyf690be52015-09-14 15:19:10 -070048#include "logging.h"
49#include "options.h"
50#include "os.h"
Jiyong Parke5c45292020-05-26 19:06:24 +090051#include "parser.h"
Christopher Wileyf690be52015-09-14 15:19:10 -070052
Adam Lesinskiffa16862014-01-23 18:17:42 -080053#ifndef O_BINARY
54# define O_BINARY 0
55#endif
56
Christopher Wiley3a9911c2016-01-19 12:59:09 -080057using android::base::Join;
Christopher Wileyd76067c2015-10-19 17:00:13 -070058using android::base::Split;
Christopher Wiley9f4c7ae2015-08-24 14:07:32 -070059using std::set;
60using std::string;
Christopher Wiley84c1eac2015-09-23 13:29:28 -070061using std::unique_ptr;
Christopher Wiley9f4c7ae2015-08-24 14:07:32 -070062using std::vector;
Adam Lesinskiffa16862014-01-23 18:17:42 -080063
Christopher Wileyf690be52015-09-14 15:19:10 -070064namespace android {
65namespace aidl {
66namespace {
Adam Lesinskiffa16862014-01-23 18:17:42 -080067
Jiyong Park965c5b92018-11-21 13:37:15 +090068// Copied from android.is.IBinder.[FIRST|LAST]_CALL_TRANSACTION
69const int kFirstCallTransaction = 1;
70const int kLastCallTransaction = 0x00ffffff;
71
72// Following IDs are all offsets from kFirstCallTransaction
Jiyong Park309668e2018-07-28 16:55:44 +090073
74// IDs for meta transactions. Most of the meta transactions are implemented in
75// the framework side (Binder.java or Binder.cpp). But these are the ones that
76// are auto-implemented by the AIDL compiler.
Jiyong Park965c5b92018-11-21 13:37:15 +090077const int kFirstMetaMethodId = kLastCallTransaction - kFirstCallTransaction;
78const int kGetInterfaceVersionId = kFirstMetaMethodId;
Paul Trautrimb77048c2020-01-21 16:39:32 +090079const int kGetInterfaceHashId = kFirstMetaMethodId - 1;
Jiyong Park965c5b92018-11-21 13:37:15 +090080// Additional meta transactions implemented by AIDL should use
81// kFirstMetaMethodId -1, -2, ...and so on.
82
83// Reserve 100 IDs for meta methods, which is more than enough. If we don't reserve,
84// in the future, a newly added meta transaction ID will have a chance to
85// collide with the user-defined methods that were added in the past. So,
86// let's prevent users from using IDs in this range from the beginning.
87const int kLastMetaMethodId = kFirstMetaMethodId - 99;
88
89// Range of IDs that is allowed for user-defined methods.
90const int kMinUserSetMethodId = 0;
91const int kMaxUserSetMethodId = kLastMetaMethodId - 1;
Adam Lesinskiffa16862014-01-23 18:17:42 -080092
Steven Moreland92c55f12018-07-31 14:08:37 -070093bool check_filename(const std::string& filename, const AidlDefinedType& defined_type) {
Adam Lesinskiffa16862014-01-23 18:17:42 -080094 const char* p;
95 string expected;
96 string fn;
97 size_t len;
Adam Lesinskiffa16862014-01-23 18:17:42 -080098 bool valid = false;
99
Christopher Wileybc2df692016-06-02 16:27:26 -0700100 if (!IoDelegate::GetAbsolutePath(filename, &fn)) {
101 return false;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800102 }
103
Steven Moreland92c55f12018-07-31 14:08:37 -0700104 const std::string package = defined_type.GetPackage();
Casey Dahlinfb7da2e2015-10-08 17:26:09 -0700105 if (!package.empty()) {
Adam Lesinskiffa16862014-01-23 18:17:42 -0800106 expected = package;
107 expected += '.';
108 }
109
110 len = expected.length();
111 for (size_t i=0; i<len; i++) {
112 if (expected[i] == '.') {
113 expected[i] = OS_PATH_SEPARATOR;
114 }
115 }
116
Steven Moreland92c55f12018-07-31 14:08:37 -0700117 const std::string name = defined_type.GetName();
Casey Dahlinfb7da2e2015-10-08 17:26:09 -0700118 expected.append(name, 0, name.find('.'));
Christopher Wiley8f8cc9b2015-09-14 13:47:40 -0700119
Adam Lesinskiffa16862014-01-23 18:17:42 -0800120 expected += ".aidl";
121
122 len = fn.length();
123 valid = (len >= expected.length());
124
125 if (valid) {
126 p = fn.c_str() + (len - expected.length());
127
Elliott Hughesce310da2015-07-29 08:44:17 -0700128#ifdef _WIN32
Adam Lesinskiffa16862014-01-23 18:17:42 -0800129 if (OS_PATH_SEPARATOR != '/') {
130 // Input filename under cygwin most likely has / separators
131 // whereas the expected string uses \\ separators. Adjust
132 // them accordingly.
133 for (char *c = const_cast<char *>(p); *c; ++c) {
134 if (*c == '/') *c = OS_PATH_SEPARATOR;
135 }
136 }
137#endif
138
Yabin Cui482eefb2014-11-10 15:01:43 -0800139 // aidl assumes case-insensitivity on Mac Os and Windows.
140#if defined(__linux__)
Adam Lesinskiffa16862014-01-23 18:17:42 -0800141 valid = (expected == p);
142#else
143 valid = !strcasecmp(expected.c_str(), p);
144#endif
145 }
146
147 if (!valid) {
Steven Moreland92c55f12018-07-31 14:08:37 -0700148 AIDL_ERROR(defined_type) << name << " should be declared in a file called " << expected;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800149 }
150
Casey Dahlin42727f82015-10-12 19:23:40 -0700151 return valid;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800152}
153
Jiyong Park74595c12018-07-23 15:22:50 +0900154bool write_dep_file(const Options& options, const AidlDefinedType& defined_type,
Jiyong Parkb034bf02018-07-30 17:44:33 +0900155 const vector<string>& imports, const IoDelegate& io_delegate,
Jiyong Park74595c12018-07-23 15:22:50 +0900156 const string& input_file, const string& output_file) {
157 string dep_file_name = options.DependencyFile();
158 if (dep_file_name.empty() && options.AutoDepFile()) {
159 dep_file_name = output_file + ".d";
160 }
161
162 if (dep_file_name.empty()) {
163 return true; // nothing to do
164 }
Jiyong Park05463732018-08-09 16:03:02 +0900165
Jiyong Park74595c12018-07-23 15:22:50 +0900166 CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name);
167 if (!writer) {
Steven Moreland21780812020-09-11 01:29:45 +0000168 AIDL_ERROR(dep_file_name) << "Could not open dependency file.";
Jiyong Park74595c12018-07-23 15:22:50 +0900169 return false;
170 }
171
172 vector<string> source_aidl = {input_file};
173 for (const auto& import : imports) {
Jiyong Parkb034bf02018-07-30 17:44:33 +0900174 source_aidl.push_back(import);
Jiyong Park74595c12018-07-23 15:22:50 +0900175 }
176
Christopher Wiley3a9911c2016-01-19 12:59:09 -0800177 // Encode that the output file depends on aidl input files.
Jiyong Parkdf202122019-09-30 20:48:35 +0900178 if (defined_type.AsUnstructuredParcelable() != nullptr &&
179 options.TargetLanguage() == Options::Language::JAVA) {
180 // Legacy behavior. For parcelable declarations in Java, don't emit output file as
181 // the dependency target. b/141372861
182 writer->Write(" : \\\n");
183 } else {
184 writer->Write("%s : \\\n", output_file.c_str());
185 }
Jiyong Park74595c12018-07-23 15:22:50 +0900186 writer->Write(" %s", Join(source_aidl, " \\\n ").c_str());
Dan Willemsen93298ee2016-11-10 23:55:55 -0800187 writer->Write("\n");
Christopher Wileya30a45e2015-10-17 10:56:59 -0700188
Jiyong Park74595c12018-07-23 15:22:50 +0900189 if (!options.DependencyFileNinja()) {
Dan Willemsen93298ee2016-11-10 23:55:55 -0800190 writer->Write("\n");
191 // Output "<input_aidl_file>: " so make won't fail if the input .aidl file
192 // has been deleted, moved or renamed in incremental build.
Jiyong Park74595c12018-07-23 15:22:50 +0900193 for (const auto& src : source_aidl) {
Dan Willemsen93298ee2016-11-10 23:55:55 -0800194 writer->Write("%s :\n", src.c_str());
195 }
Christopher Wiley3a9911c2016-01-19 12:59:09 -0800196 }
Christopher Wileya30a45e2015-10-17 10:56:59 -0700197
Steven Morelandc26d8142018-09-17 14:25:33 -0700198 if (options.IsCppOutput()) {
Jiyong Park74595c12018-07-23 15:22:50 +0900199 if (!options.DependencyFileNinja()) {
200 using ::android::aidl::cpp::ClassNames;
201 using ::android::aidl::cpp::HeaderFile;
202 vector<string> headers;
Jiyong Park5b7e5322019-04-03 20:05:01 +0900203 for (ClassNames c : {ClassNames::CLIENT, ClassNames::SERVER, ClassNames::RAW}) {
Jiyong Park05463732018-08-09 16:03:02 +0900204 headers.push_back(options.OutputHeaderDir() +
Jiyong Park74595c12018-07-23 15:22:50 +0900205 HeaderFile(defined_type, c, false /* use_os_sep */));
206 }
Christopher Wiley3a9911c2016-01-19 12:59:09 -0800207
Jiyong Park74595c12018-07-23 15:22:50 +0900208 writer->Write("\n");
209
210 // Generated headers also depend on the source aidl files.
211 writer->Write("%s : \\\n %s\n", Join(headers, " \\\n ").c_str(),
212 Join(source_aidl, " \\\n ").c_str());
Adam Lesinskiffa16862014-01-23 18:17:42 -0800213 }
Christopher Wileya30a45e2015-10-17 10:56:59 -0700214 }
Christopher Wiley3a9911c2016-01-19 12:59:09 -0800215
Christopher Wiley3a9911c2016-01-19 12:59:09 -0800216 return true;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800217}
218
Jiyong Park74595c12018-07-23 15:22:50 +0900219string generate_outputFileName(const Options& options, const AidlDefinedType& defined_type) {
Steven Moreland5557f1c2018-07-02 13:50:23 -0700220 // create the path to the destination folder based on the
221 // defined_type package name
Jiyong Park74595c12018-07-23 15:22:50 +0900222 string result = options.OutputDir();
Adam Lesinskiffa16862014-01-23 18:17:42 -0800223
Jiyong Park74595c12018-07-23 15:22:50 +0900224 string package = defined_type.GetPackage();
225 size_t len = package.length();
Steven Moreland5557f1c2018-07-02 13:50:23 -0700226 for (size_t i = 0; i < len; i++) {
Jiyong Park74595c12018-07-23 15:22:50 +0900227 if (package[i] == '.') {
228 package[i] = OS_PATH_SEPARATOR;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800229 }
Steven Moreland5557f1c2018-07-02 13:50:23 -0700230 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800231
Jiyong Park74595c12018-07-23 15:22:50 +0900232 result += package;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800233
Steven Moreland5557f1c2018-07-02 13:50:23 -0700234 // add the filename by replacing the .aidl extension to .java
Jiyong Park74595c12018-07-23 15:22:50 +0900235 const string& name = defined_type.GetName();
Steven Moreland5557f1c2018-07-02 13:50:23 -0700236 result += OS_PATH_SEPARATOR;
237 result.append(name, 0, name.find('.'));
Jiyong Parkb03551f2018-08-06 19:20:51 +0900238 if (options.TargetLanguage() == Options::Language::JAVA) {
239 result += ".java";
Steven Morelandc26d8142018-09-17 14:25:33 -0700240 } else if (options.IsCppOutput()) {
Jiyong Parkb03551f2018-08-06 19:20:51 +0900241 result += ".cpp";
Andrei Homescub62afd92020-05-11 19:24:59 -0700242 } else if (options.TargetLanguage() == Options::Language::RUST) {
243 result += ".rs";
Jiyong Parkb03551f2018-08-06 19:20:51 +0900244 } else {
Steven Moreland21780812020-09-11 01:29:45 +0000245 AIDL_FATAL("Unknown target language");
Jiyong Parkb03551f2018-08-06 19:20:51 +0900246 return "";
247 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800248
Steven Moreland5557f1c2018-07-02 13:50:23 -0700249 return result;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800250}
251
Jiyong Parkb034bf02018-07-30 17:44:33 +0900252bool check_and_assign_method_ids(const std::vector<std::unique_ptr<AidlMethod>>& items) {
Jiyong Park309668e2018-07-28 16:55:44 +0900253 // Check whether there are any methods with manually assigned id's and any
254 // that are not. Either all method id's must be manually assigned or all of
255 // them must not. Also, check for uplicates of user set ID's and that the
256 // ID's are within the proper bounds.
257 set<int> usedIds;
258 bool hasUnassignedIds = false;
259 bool hasAssignedIds = false;
Steven Morelandec6f4692019-08-13 10:03:24 -0700260 int newId = kMinUserSetMethodId;
Jiyong Park309668e2018-07-28 16:55:44 +0900261 for (const auto& item : items) {
262 // However, meta transactions that are added by the AIDL compiler are
263 // exceptions. They have fixed IDs but allowed to be with user-defined
264 // methods having auto-assigned IDs. This is because the Ids of the meta
265 // transactions must be stable during the entire lifetime of an interface.
266 // In other words, their IDs must be the same even when new user-defined
267 // methods are added.
Jiyong Park3633b722019-04-11 15:38:26 +0900268 if (!item->IsUserDefined()) {
269 continue;
270 }
271 if (item->HasId()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900272 hasAssignedIds = true;
Jiyong Park309668e2018-07-28 16:55:44 +0900273 } else {
Steven Morelandec6f4692019-08-13 10:03:24 -0700274 item->SetId(newId++);
Jiyong Park309668e2018-07-28 16:55:44 +0900275 hasUnassignedIds = true;
276 }
Steven Morelandec6f4692019-08-13 10:03:24 -0700277
Jiyong Park309668e2018-07-28 16:55:44 +0900278 if (hasAssignedIds && hasUnassignedIds) {
Jiyong Parkb034bf02018-07-30 17:44:33 +0900279 AIDL_ERROR(item) << "You must either assign id's to all methods or to none of them.";
Jiyong Park309668e2018-07-28 16:55:44 +0900280 return false;
281 }
Jiyong Park309668e2018-07-28 16:55:44 +0900282
Steven Morelandec6f4692019-08-13 10:03:24 -0700283 // Ensure that the user set id is not duplicated.
284 if (usedIds.find(item->GetId()) != usedIds.end()) {
285 // We found a duplicate id, so throw an error.
286 AIDL_ERROR(item) << "Found duplicate method id (" << item->GetId() << ") for method "
287 << item->GetName();
288 return false;
289 }
290 usedIds.insert(item->GetId());
291
292 // Ensure that the user set id is within the appropriate limits
293 if (item->GetId() < kMinUserSetMethodId || item->GetId() > kMaxUserSetMethodId) {
294 AIDL_ERROR(item) << "Found out of bounds id (" << item->GetId() << ") for method "
295 << item->GetName() << ". Value for id must be between "
296 << kMinUserSetMethodId << " and " << kMaxUserSetMethodId << " inclusive.";
297 return false;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800298 }
Jiyong Park309668e2018-07-28 16:55:44 +0900299 }
Steven Morelandec6f4692019-08-13 10:03:24 -0700300
Jiyong Park309668e2018-07-28 16:55:44 +0900301 return true;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800302}
303
Christopher Wileyef140932015-11-03 09:29:19 -0800304// TODO: Remove this in favor of using the YACC parser b/25479378
Jiyong Park18132182020-06-08 20:24:40 +0900305bool ParsePreprocessedLine(const string& line, string* decl, std::string* package,
306 string* class_name) {
Christopher Wileyef140932015-11-03 09:29:19 -0800307 // erase all trailing whitespace and semicolons
308 const size_t end = line.find_last_not_of(" ;\t");
309 if (end == string::npos) {
310 return false;
311 }
312 if (line.rfind(';', end) != string::npos) {
313 return false;
314 }
315
316 decl->clear();
317 string type;
318 vector<string> pieces = Split(line.substr(0, end + 1), " \t");
319 for (const string& piece : pieces) {
320 if (piece.empty()) {
321 continue;
322 }
323 if (decl->empty()) {
324 *decl = std::move(piece);
325 } else if (type.empty()) {
326 type = std::move(piece);
327 } else {
328 return false;
329 }
330 }
331
332 // Note that this logic is absolutely wrong. Given a parcelable
333 // org.some.Foo.Bar, the class name is Foo.Bar, but this code will claim that
334 // the class is just Bar. However, this was the way it was done in the past.
335 //
336 // See b/17415692
337 size_t dot_pos = type.rfind('.');
338 if (dot_pos != string::npos) {
339 *class_name = type.substr(dot_pos + 1);
Jiyong Park18132182020-06-08 20:24:40 +0900340 *package = type.substr(0, dot_pos);
Christopher Wileyef140932015-11-03 09:29:19 -0800341 } else {
342 *class_name = type;
343 package->clear();
344 }
345
346 return true;
347}
348
Christopher Wiley4a2884b2015-10-07 11:27:45 -0700349} // namespace
350
351namespace internals {
352
Jiyong Park1deecc32018-07-17 01:14:41 +0900353bool parse_preprocessed_file(const IoDelegate& io_delegate, const string& filename,
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900354 AidlTypenames* typenames) {
Christopher Wileyef140932015-11-03 09:29:19 -0800355 bool success = true;
356 unique_ptr<LineReader> line_reader = io_delegate.GetLineReader(filename);
357 if (!line_reader) {
Steven Moreland21780812020-09-11 01:29:45 +0000358 AIDL_ERROR(filename) << "cannot open preprocessed file";
Christopher Wileyef140932015-11-03 09:29:19 -0800359 success = false;
360 return success;
361 }
362
363 string line;
Dan Willemsen609ba6d2019-12-30 10:44:00 -0800364 int lineno = 1;
Christopher Wileyef140932015-11-03 09:29:19 -0800365 for ( ; line_reader->ReadLine(&line); ++lineno) {
366 if (line.empty() || line.compare(0, 2, "//") == 0) {
367 // skip comments and empty lines
368 continue;
369 }
370
371 string decl;
Jiyong Park18132182020-06-08 20:24:40 +0900372 std::string package;
Christopher Wileyef140932015-11-03 09:29:19 -0800373 string class_name;
374 if (!ParsePreprocessedLine(line, &decl, &package, &class_name)) {
375 success = false;
376 break;
377 }
378
Steven Moreland46e9da82018-07-27 15:45:29 -0700379 AidlLocation::Point point = {.line = lineno, .column = 0 /*column*/};
Devin Mooredf93ebb2020-03-25 14:03:35 -0700380 AidlLocation location = AidlLocation(filename, point, point, AidlLocation::Source::EXTERNAL);
Steven Moreland46e9da82018-07-27 15:45:29 -0700381
Christopher Wileyef140932015-11-03 09:29:19 -0800382 if (decl == "parcelable") {
Jeongik Chace58bc62019-04-22 13:30:39 +0900383 // ParcelFileDescriptor is treated as a built-in type, but it's also in the framework.aidl.
384 // So aidl should ignore built-in types in framework.aidl to prevent duplication.
385 // (b/130899491)
386 if (AidlTypenames::IsBuiltinTypename(class_name)) {
387 continue;
388 }
Jiyong Park18132182020-06-08 20:24:40 +0900389 AidlParcelable* doc = new AidlParcelable(location, class_name, package, "" /* comments */);
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900390 typenames->AddPreprocessedType(unique_ptr<AidlParcelable>(doc));
Steven Morelanded83a282018-07-17 13:27:29 -0700391 } else if (decl == "structured_parcelable") {
392 auto temp = new std::vector<std::unique_ptr<AidlVariableDeclaration>>();
Devin Moore53fc99c2020-08-12 08:07:52 -0700393 AidlStructuredParcelable* doc = new AidlStructuredParcelable(
394 location, class_name, package, "" /* comments */, temp, nullptr);
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900395 typenames->AddPreprocessedType(unique_ptr<AidlStructuredParcelable>(doc));
Christopher Wileyef140932015-11-03 09:29:19 -0800396 } else if (decl == "interface") {
Casey Dahlind40e2fe2015-11-24 14:06:52 -0800397 auto temp = new std::vector<std::unique_ptr<AidlMember>>();
Steven Moreland46e9da82018-07-27 15:45:29 -0700398 AidlInterface* doc = new AidlInterface(location, class_name, "", false, temp, package);
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900399 typenames->AddPreprocessedType(unique_ptr<AidlInterface>(doc));
Christopher Wileyef140932015-11-03 09:29:19 -0800400 } else {
401 success = false;
402 break;
403 }
404 }
405 if (!success) {
Steven Moreland21780812020-09-11 01:29:45 +0000406 AIDL_ERROR(filename) << " on line " << lineno << " malformed preprocessed file line: '" << line
407 << "'";
Christopher Wileyef140932015-11-03 09:29:19 -0800408 }
409
410 return success;
411}
412
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900413AidlError load_and_validate_aidl(const std::string& input_file_name, const Options& options,
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900414 const IoDelegate& io_delegate, AidlTypenames* typenames,
Jiyong Parkb034bf02018-07-30 17:44:33 +0900415 vector<string>* imported_files) {
Christopher Wiley632801d2015-11-05 14:15:49 -0800416 AidlError err = AidlError::OK;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800417
Jiyong Parkb034bf02018-07-30 17:44:33 +0900418 //////////////////////////////////////////////////////////////////////////
419 // Loading phase
420 //////////////////////////////////////////////////////////////////////////
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900421
Jiyong Parkb034bf02018-07-30 17:44:33 +0900422 // Parse the main input file
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900423 std::unique_ptr<Parser> main_parser = Parser::Parse(input_file_name, io_delegate, *typenames);
Steven Moreland64e29be2018-08-08 18:52:19 -0700424 if (main_parser == nullptr) {
Jiyong Parkb034bf02018-07-30 17:44:33 +0900425 return AidlError::PARSE_ERROR;
426 }
Jooyung Han2946afc2020-10-05 20:29:16 +0900427 int num_top_level_decls = 0;
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900428 for (const auto& type : main_parser->ParsedDocument().DefinedTypes()) {
Jooyung Han2946afc2020-10-05 20:29:16 +0900429 if (type->AsUnstructuredParcelable() == nullptr) {
430 num_top_level_decls++;
431 if (num_top_level_decls > 1) {
Devin Moore5de18ed2020-04-02 13:52:29 -0700432 AIDL_ERROR(*type) << "You must declare only one type per file.";
433 return AidlError::BAD_TYPE;
434 }
Jiyong Parkda8c6932019-08-12 19:56:08 +0900435 }
436 }
Jiyong Parkb034bf02018-07-30 17:44:33 +0900437
438 // Import the preprocessed file
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900439 for (const string& s : options.PreprocessedFiles()) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900440 if (!parse_preprocessed_file(io_delegate, s, typenames)) {
Christopher Wiley632801d2015-11-05 14:15:49 -0800441 err = AidlError::BAD_PRE_PROCESSED_FILE;
Christopher Wileyef140932015-11-03 09:29:19 -0800442 }
Christopher Wiley3a9d1582015-09-16 12:42:14 -0700443 }
Christopher Wiley632801d2015-11-05 14:15:49 -0800444 if (err != AidlError::OK) {
Christopher Wiley3a9d1582015-09-16 12:42:14 -0700445 return err;
446 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800447
Jiyong Parkb034bf02018-07-30 17:44:33 +0900448 // Find files to import and parse them
Jiyong Parke59c3682018-09-11 23:10:25 +0900449 vector<string> import_paths;
Jiyong Park8c380532018-08-30 14:55:26 +0900450 ImportResolver import_resolver{io_delegate, input_file_name, options.ImportDirs(),
451 options.InputFiles()};
Jiyong Parke59c3682018-09-11 23:10:25 +0900452
Jiyong Park8f6ec462020-01-19 20:52:47 +0900453 vector<string> type_from_import_statements;
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900454 for (const auto& import : main_parser->ParsedDocument().Imports()) {
Jiyong Parke05195e2018-10-08 18:24:23 +0900455 if (!AidlTypenames::IsBuiltinTypename(import->GetNeededClass())) {
Jiyong Park8f6ec462020-01-19 20:52:47 +0900456 type_from_import_statements.emplace_back(import->GetNeededClass());
Jiyong Parke05195e2018-10-08 18:24:23 +0900457 }
Jiyong Parke59c3682018-09-11 23:10:25 +0900458 }
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 }
Jiyong Park8f6ec462020-01-19 20:52:47 +0900471 vector<string> import_candidates(type_from_import_statements);
472 import_candidates.insert(import_candidates.end(), unresolved_types.begin(),
473 unresolved_types.end());
Jiyong Parke59c3682018-09-11 23:10:25 +0900474 for (const auto& import : import_candidates) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900475 if (typenames->IsIgnorableImport(import)) {
Christopher Wileyfb4b22d2015-09-25 15:16:13 -0700476 // 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...
Christopher Wileyc16e5e72015-09-16 10:49:40 -0700479 continue;
480 }
Jiyong Parke59c3682018-09-11 23:10:25 +0900481 string import_path = import_resolver.FindImportFile(import);
Christopher Wiley72877ac2015-10-06 14:41:42 -0700482 if (import_path.empty()) {
Steven Morelandcb1bcd72020-04-29 16:30:35 -0700483 if (typenames->ResolveTypename(import).is_resolved) {
Jiyong Park8f6ec462020-01-19 20:52:47 +0900484 // 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()) {
Jiyong Parke59c3682018-09-11 23:10:25 +0900493 // Complain only when the import from the import statement has failed.
Devin Moore5de18ed2020-04-02 13:52:29 -0700494 AIDL_ERROR(input_file_name) << "Couldn't find import for class " << import;
Jiyong Parke59c3682018-09-11 23:10:25 +0900495 err = AidlError::BAD_IMPORT;
496 }
Christopher Wileyc16e5e72015-09-16 10:49:40 -0700497 continue;
498 }
Casey Dahlin2cc93162015-10-02 16:14:17 -0700499
Jiyong Parke59c3682018-09-11 23:10:25 +0900500 import_paths.emplace_back(import_path);
Jiyong Parkb034bf02018-07-30 17:44:33 +0900501
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900502 std::unique_ptr<Parser> import_parser = Parser::Parse(import_path, io_delegate, *typenames);
Steven Moreland64e29be2018-08-08 18:52:19 -0700503 if (import_parser == nullptr) {
Devin Moore2a088902020-09-17 10:51:19 -0700504 AIDL_ERROR(import_path) << "error while importing " << import_path << " for " << import;
Christopher Wiley632801d2015-11-05 14:15:49 -0800505 err = AidlError::BAD_IMPORT;
Christopher Wileyc16e5e72015-09-16 10:49:40 -0700506 continue;
507 }
Christopher Wileyc16e5e72015-09-16 10:49:40 -0700508 }
Christopher Wiley632801d2015-11-05 14:15:49 -0800509 if (err != AidlError::OK) {
Christopher Wileyc16e5e72015-09-16 10:49:40 -0700510 return err;
Christopher Wiley3a9d1582015-09-16 12:42:14 -0700511 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800512
Jiyong Park3c35e392018-08-30 13:10:30 +0900513 for (const auto& imported_file : options.ImportFiles()) {
Jiyong Parke59c3682018-09-11 23:10:25 +0900514 import_paths.emplace_back(imported_file);
Jiyong Park3c35e392018-08-30 13:10:30 +0900515
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900516 std::unique_ptr<Parser> import_parser = Parser::Parse(imported_file, io_delegate, *typenames);
Jiyong Park3c35e392018-08-30 13:10:30 +0900517 if (import_parser == nullptr) {
518 AIDL_ERROR(imported_file) << "error while importing " << imported_file;
519 err = AidlError::BAD_IMPORT;
520 continue;
521 }
Jiyong Park3c35e392018-08-30 13:10:30 +0900522 }
523 if (err != AidlError::OK) {
524 return err;
525 }
Jiyong Park96c16a92018-08-16 16:37:09 +0900526 const bool is_check_api = options.GetTask() == Options::Task::CHECK_API;
Jiyong Parkb034bf02018-07-30 17:44:33 +0900527
528 // Resolve the unresolved type references found from the input file
Jiyong Park96c16a92018-08-16 16:37:09 +0900529 if (!is_check_api && !main_parser->Resolve()) {
530 // Resolution is not need for check api because all typespecs are
531 // using fully qualified names.
Jiyong Park1deecc32018-07-17 01:14:41 +0900532 return AidlError::BAD_TYPE;
533 }
Daniel Norman85aed542019-08-21 12:01:14 -0700534
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.
Daniel Norman716d3112019-09-10 13:11:56 -0700542 if (auto backing_type = enum_decl->BackingType(*typenames); backing_type != nullptr) {
Daniel Norman85aed542019-08-21 12:01:14 -0700543 enum_decl->SetBackingType(std::unique_ptr<const AidlTypeSpecifier>(backing_type));
544 } else {
545 // Default to byte type for enums.
Daniel Norman716d3112019-09-10 13:11:56 -0700546 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));
Daniel Norman85aed542019-08-21 12:01:14 -0700550 }
551
Steven Moreland59e53e42019-11-26 20:38:08 -0800552 if (!enum_decl->Autofill()) {
553 err = AidlError::BAD_TYPE;
554 }
Daniel Norman85aed542019-08-21 12:01:14 -0700555 }
556 });
Steven Moreland59e53e42019-11-26 20:38:08 -0800557 if (err != AidlError::OK) {
558 return err;
559 }
Daniel Norman85aed542019-08-21 12:01:14 -0700560
Jeongik Chadb0f59e2018-11-01 18:11:21 +0900561 //////////////////////////////////////////////////////////////////////////
562 // Validation phase
563 //////////////////////////////////////////////////////////////////////////
564
Steven Morelande2c64b42018-09-18 15:06:37 -0700565 // 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;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800570
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900571 const auto& types = main_parser->ParsedDocument().DefinedTypes();
Jiyong Park62515512020-06-08 15:57:11 +0900572 const int num_defined_types = types.size();
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900573 for (const auto& defined_type : types) {
Steven Moreland21780812020-09-11 01:29:45 +0000574 AIDL_FATAL_IF(defined_type == nullptr, main_parser->FileName());
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900575
Steven Morelandebc3c5d2020-09-30 23:40:33 +0000576 // Ensure type is exactly one of the following:
577 AidlInterface* interface = defined_type->AsInterface();
578 AidlStructuredParcelable* parcelable = defined_type->AsStructuredParcelable();
579 AidlParcelable* unstructured_parcelable = defined_type->AsUnstructuredParcelable();
580 AidlEnumDeclaration* enum_decl = defined_type->AsEnumDeclaration();
Jooyung Han2946afc2020-10-05 20:29:16 +0900581 AidlUnionDecl* union_decl = defined_type->AsUnionDeclaration();
582 AIDL_FATAL_IF(
583 !!interface + !!parcelable + !!unstructured_parcelable + !!enum_decl + !!union_decl != 1,
584 defined_type);
Steven Morelandebc3c5d2020-09-30 23:40:33 +0000585
586 // Ensure that foo.bar.IFoo is defined in <some_path>/foo/bar/IFoo.aidl
587 if (num_defined_types == 1 && !check_filename(input_file_name, *defined_type)) {
588 return AidlError::BAD_PACKAGE;
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900589 }
590
Steven Morelandebc3c5d2020-09-30 23:40:33 +0000591 {
592 bool valid_type = true;
593
594 if (!is_check_api) {
595 // Ideally, we could do this for check api, but we can't resolve imports
596 if (!defined_type->CheckValid(*typenames)) {
597 valid_type = false;
598 }
599 }
600
601 if (!defined_type->LanguageSpecificCheckValid(*typenames, options.TargetLanguage())) {
602 valid_type = false;
603 }
604
605 if (!valid_type) {
Jeongik Cha82317dd2019-02-27 20:26:11 +0900606 return AidlError::BAD_TYPE;
607 }
Steven Morelandebc3c5d2020-09-30 23:40:33 +0000608 }
609
610 if (unstructured_parcelable != nullptr) {
611 bool isStable = unstructured_parcelable->IsStableApiParcelable(options.TargetLanguage());
Jeongik Cha82317dd2019-02-27 20:26:11 +0900612 if (options.IsStructured() && !isStable) {
Steven Morelandebc3c5d2020-09-30 23:40:33 +0000613 AIDL_ERROR(unstructured_parcelable)
Steven Moreland2a9a7d62019-02-05 16:11:54 -0800614 << "Cannot declared parcelable in a --structured interface. Parcelable must be defined "
615 "in AIDL directly.";
616 return AidlError::NOT_STRUCTURED;
617 }
618 if (options.FailOnParcelable()) {
Steven Morelandebc3c5d2020-09-30 23:40:33 +0000619 AIDL_ERROR(unstructured_parcelable)
Steven Moreland2a9a7d62019-02-05 16:11:54 -0800620 << "Refusing to generate code with unstructured parcelables. Declared parcelables "
621 "should be in their own file and/or cannot be used with --structured interfaces.";
622 // Continue parsing for more errors
623 }
624
Steven Morelande2c64b42018-09-18 15:06:37 -0700625 contains_unstructured_parcelable = true;
Steven Morelande2c64b42018-09-18 15:06:37 -0700626 }
627
Devin Moore0d0e3f62020-03-30 17:45:39 -0700628 if (defined_type->IsVintfStability()) {
629 bool success = true;
630 if (options.GetStability() != Options::Stability::VINTF) {
631 AIDL_ERROR(defined_type)
632 << "Must compile @VintfStability type w/ aidl_interface 'stability: \"vintf\"'";
633 success = false;
634 }
635 if (!options.IsStructured()) {
636 AIDL_ERROR(defined_type)
637 << "Must compile @VintfStability type w/ aidl_interface --structured";
638 success = false;
639 }
640 if (!success) return AidlError::NOT_STRUCTURED;
Steven Morelanda57d0a62019-07-30 09:41:14 -0700641 }
642
Jiyong Parkb034bf02018-07-30 17:44:33 +0900643 if (interface != nullptr) {
644 // add the meta-method 'int getInterfaceVersion()' if version is specified.
645 if (options.Version() > 0) {
646 AidlTypeSpecifier* ret =
Steven Moreland02e012e2018-08-02 14:58:10 -0700647 new AidlTypeSpecifier(AIDL_LOCATION_HERE, "int", false, nullptr, "");
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900648 ret->Resolve(*typenames);
Jiyong Parkb034bf02018-07-30 17:44:33 +0900649 vector<unique_ptr<AidlArgument>>* args = new vector<unique_ptr<AidlArgument>>();
650 AidlMethod* method =
Steven Moreland02e012e2018-08-02 14:58:10 -0700651 new AidlMethod(AIDL_LOCATION_HERE, false, ret, "getInterfaceVersion", args, "",
Jiyong Parkb034bf02018-07-30 17:44:33 +0900652 kGetInterfaceVersionId, false /* is_user_defined */);
653 interface->GetMutableMethods().emplace_back(method);
654 }
Paul Trautrimb77048c2020-01-21 16:39:32 +0900655 // add the meta-method 'string getInterfaceHash()' if hash is specified.
656 if (!options.Hash().empty()) {
657 AidlTypeSpecifier* ret =
658 new AidlTypeSpecifier(AIDL_LOCATION_HERE, "String", false, nullptr, "");
659 ret->Resolve(*typenames);
660 vector<unique_ptr<AidlArgument>>* args = new vector<unique_ptr<AidlArgument>>();
661 AidlMethod* method = new AidlMethod(AIDL_LOCATION_HERE, false, ret, kGetInterfaceHash, args,
662 "", kGetInterfaceHashId, false /* is_user_defined */);
663 interface->GetMutableMethods().emplace_back(method);
664 }
Jiyong Parkb034bf02018-07-30 17:44:33 +0900665 if (!check_and_assign_method_ids(interface->GetMethods())) {
666 return AidlError::BAD_METHOD_ID;
667 }
Will McVickerd7d18df2019-09-12 13:40:50 -0700668
669 // Verify and resolve the constant declarations
670 for (const auto& constant : interface->GetConstantDeclarations()) {
671 switch (constant->GetValue().GetType()) {
672 case AidlConstantValue::Type::STRING: // fall-through
673 case AidlConstantValue::Type::INT8: // fall-through
674 case AidlConstantValue::Type::INT32: // fall-through
675 case AidlConstantValue::Type::INT64: // fall-through
676 case AidlConstantValue::Type::FLOATING: // fall-through
677 case AidlConstantValue::Type::UNARY: // fall-through
678 case AidlConstantValue::Type::BINARY: {
679 bool success = constant->CheckValid(*typenames);
680 if (!success) {
681 return AidlError::BAD_TYPE;
682 }
683 if (constant->ValueString(cpp::ConstantValueDecorator).empty()) {
684 return AidlError::BAD_TYPE;
685 }
686 break;
687 }
688 default:
Steven Moreland21780812020-09-11 01:29:45 +0000689 AIDL_FATAL(constant) << "Unrecognized constant type: "
690 << static_cast<int>(constant->GetValue().GetType());
Will McVickerd7d18df2019-09-12 13:40:50 -0700691 break;
692 }
693 }
Jiyong Parkb034bf02018-07-30 17:44:33 +0900694 }
Christopher Wiley632801d2015-11-05 14:15:49 -0800695 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800696
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900697 typenames->IterateTypes([&](const AidlDefinedType& type) {
Steven Morelanda57d0a62019-07-30 09:41:14 -0700698 if (options.IsStructured() && type.AsUnstructuredParcelable() != nullptr &&
Jeongik Cha88f95a82020-01-15 13:02:16 +0900699 !type.AsUnstructuredParcelable()->IsStableApiParcelable(options.TargetLanguage())) {
Steven Morelanda57d0a62019-07-30 09:41:14 -0700700 err = AidlError::NOT_STRUCTURED;
Devin Moore097a3ab2020-03-11 16:08:44 -0700701 AIDL_ERROR(type) << type.GetCanonicalName()
702 << " is not structured, but this is a structured interface.";
Steven Morelanda57d0a62019-07-30 09:41:14 -0700703 }
704 if (options.GetStability() == Options::Stability::VINTF && !type.IsVintfStability()) {
705 err = AidlError::NOT_STRUCTURED;
Devin Moore097a3ab2020-03-11 16:08:44 -0700706 AIDL_ERROR(type) << type.GetCanonicalName()
707 << " does not have VINTF level stability, but this interface requires it.";
Steven Morelanda57d0a62019-07-30 09:41:14 -0700708 }
Jiyong Parkf8d53612020-05-04 14:06:13 +0900709
Jeongik Chaef44e622020-10-23 16:00:52 +0900710 // Ensure that untyped List/Map is not used in a parcelable, a union and a stable interface.
Jiyong Parkf8d53612020-05-04 14:06:13 +0900711
Jeongik Chaef44e622020-10-23 16:00:52 +0900712 std::function<void(const AidlTypeSpecifier&, const AidlNode*)> check_untyped_container =
713 [&err, &check_untyped_container](const AidlTypeSpecifier& type, const AidlNode* node) {
714 if (type.IsGeneric()) {
715 std::for_each(type.GetTypeParameters().begin(), type.GetTypeParameters().end(),
716 [&node, &check_untyped_container](auto& nested) {
717 check_untyped_container(*nested, node);
718 });
719 return;
Jiyong Parkf8d53612020-05-04 14:06:13 +0900720 }
Jeongik Chaef44e622020-10-23 16:00:52 +0900721 if (type.GetName() == "List" || type.GetName() == "Map") {
722 err = AidlError::BAD_TYPE;
723 AIDL_ERROR(node)
724 << "Encountered an untyped List or Map. The use of untyped List/Map is prohibited "
725 << "because it is not guaranteed that the objects in the list are recognizable in "
726 << "the receiving side. Consider switching to an array or a generic List/Map.";
727 }
728 };
729 const AidlInterface* iface = type.AsInterface();
730 const AidlWithFields* data_structure = type.AsStructuredParcelable();
731 if (!data_structure) {
732 data_structure = type.AsUnionDeclaration();
733 }
734
735 if (iface != nullptr && options.IsStructured()) {
736 for (const auto& method : iface->GetMethods()) {
737 check_untyped_container(method->GetType(), method.get());
738 for (const auto& arg : method->GetArguments()) {
739 check_untyped_container(arg->GetType(), method.get());
Jiyong Parkf8d53612020-05-04 14:06:13 +0900740 }
Jeongik Chaef44e622020-10-23 16:00:52 +0900741 }
742 } else if (data_structure != nullptr) {
743 for (const auto& field : data_structure->GetFields()) {
744 check_untyped_container(field->GetType(), field.get());
Jiyong Parkf8d53612020-05-04 14:06:13 +0900745 }
746 }
Steven Morelanda57d0a62019-07-30 09:41:14 -0700747 });
748
Steven Moreland6cee3482018-07-18 14:39:58 -0700749 if (err != AidlError::OK) {
750 return err;
751 }
752
Jiyong Parkb034bf02018-07-30 17:44:33 +0900753 if (imported_files != nullptr) {
Jiyong Parke59c3682018-09-11 23:10:25 +0900754 *imported_files = import_paths;
Christopher Wiley3a9d1582015-09-16 12:42:14 -0700755 }
Casey Dahlin0edf3422015-10-07 12:34:59 -0700756
Steven Morelande2c64b42018-09-18 15:06:37 -0700757 if (contains_unstructured_parcelable) {
758 // Considered a success for the legacy case, so this must be returned last.
759 return AidlError::FOUND_PARCELABLE;
760 }
761
Christopher Wiley632801d2015-11-05 14:15:49 -0800762 return AidlError::OK;
Christopher Wileyeb1acc12015-09-16 11:25:13 -0700763}
764
Casey Dahlin2cc93162015-10-02 16:14:17 -0700765} // namespace internals
766
Jiyong Parkb034bf02018-07-30 17:44:33 +0900767int compile_aidl(const Options& options, const IoDelegate& io_delegate) {
768 const Options::Language lang = options.TargetLanguage();
Jiyong Park74595c12018-07-23 15:22:50 +0900769 for (const string& input_file : options.InputFiles()) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900770 AidlTypenames typenames;
Jiyong Park74595c12018-07-23 15:22:50 +0900771
Jiyong Parkb034bf02018-07-30 17:44:33 +0900772 vector<string> imported_files;
Jiyong Park74595c12018-07-23 15:22:50 +0900773
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900774 AidlError aidl_err = internals::load_and_validate_aidl(input_file, options, io_delegate,
775 &typenames, &imported_files);
Steven Moreland2a9a7d62019-02-05 16:11:54 -0800776 bool allowError = aidl_err == AidlError::FOUND_PARCELABLE && !options.FailOnParcelable();
777 if (aidl_err != AidlError::OK && !allowError) {
Jiyong Park74595c12018-07-23 15:22:50 +0900778 return 1;
779 }
Christopher Wileyeb1acc12015-09-16 11:25:13 -0700780
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900781 for (const auto& defined_type : typenames.MainDocument().DefinedTypes()) {
Steven Moreland21780812020-09-11 01:29:45 +0000782 AIDL_FATAL_IF(defined_type == nullptr, input_file);
Steven Moreland5557f1c2018-07-02 13:50:23 -0700783
Jiyong Parkb034bf02018-07-30 17:44:33 +0900784 string output_file_name = options.OutputFile();
785 // if needed, generate the output file name from the base folder
786 if (output_file_name.empty() && !options.OutputDir().empty()) {
Jiyong Parkb03551f2018-08-06 19:20:51 +0900787 output_file_name = generate_outputFileName(options, *defined_type);
788 if (output_file_name.empty()) {
Jiyong Parkb034bf02018-07-30 17:44:33 +0900789 return 1;
790 }
791 }
Jiyong Park74595c12018-07-23 15:22:50 +0900792
Jiyong Parkb034bf02018-07-30 17:44:33 +0900793 if (!write_dep_file(options, *defined_type, imported_files, io_delegate, input_file,
794 output_file_name)) {
795 return 1;
796 }
Jiyong Park74595c12018-07-23 15:22:50 +0900797
Jiyong Parkb034bf02018-07-30 17:44:33 +0900798 bool success = false;
799 if (lang == Options::Language::CPP) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900800 success =
801 cpp::GenerateCpp(output_file_name, options, typenames, *defined_type, io_delegate);
Steven Morelandc26d8142018-09-17 14:25:33 -0700802 } else if (lang == Options::Language::NDK) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900803 ndk::GenerateNdk(output_file_name, options, typenames, *defined_type, io_delegate);
Steven Morelandc26d8142018-09-17 14:25:33 -0700804 success = true;
Jiyong Parkb034bf02018-07-30 17:44:33 +0900805 } else if (lang == Options::Language::JAVA) {
Jiyong Park9ca5c7e2019-10-17 15:01:14 +0900806 if (defined_type->AsUnstructuredParcelable() != nullptr) {
807 // Legacy behavior. For parcelable declarations in Java, don't generate output file.
808 success = true;
809 } else {
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900810 success = java::generate_java(output_file_name, defined_type.get(), typenames,
811 io_delegate, options);
Jiyong Park9ca5c7e2019-10-17 15:01:14 +0900812 }
Andrei Homescub62afd92020-05-11 19:24:59 -0700813 } else if (lang == Options::Language::RUST) {
814 success = rust::GenerateRust(output_file_name, defined_type.get(), typenames, io_delegate,
815 options);
Jiyong Parkb034bf02018-07-30 17:44:33 +0900816 } else {
Steven Moreland21780812020-09-11 01:29:45 +0000817 AIDL_FATAL(input_file) << "Should not reach here.";
Jiyong Parkb034bf02018-07-30 17:44:33 +0900818 }
819 if (!success) {
820 return 1;
821 }
Jiyong Park74595c12018-07-23 15:22:50 +0900822 }
Christopher Wiley3a9d1582015-09-16 12:42:14 -0700823 }
Jiyong Park74595c12018-07-23 15:22:50 +0900824 return 0;
Adam Lesinskiffa16862014-01-23 18:17:42 -0800825}
826
Andrei Onea8714b022019-02-01 18:55:54 +0000827bool dump_mappings(const Options& options, const IoDelegate& io_delegate) {
828 android::aidl::mappings::SignatureMap all_mappings;
829 for (const string& input_file : options.InputFiles()) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900830 AidlTypenames typenames;
Andrei Onea8714b022019-02-01 18:55:54 +0000831 vector<string> imported_files;
832
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900833 AidlError aidl_err = internals::load_and_validate_aidl(input_file, options, io_delegate,
834 &typenames, &imported_files);
Andrei Onea8714b022019-02-01 18:55:54 +0000835 if (aidl_err != AidlError::OK) {
Jiyong Park3a060392020-04-11 21:02:19 +0900836 return false;
Andrei Onea8714b022019-02-01 18:55:54 +0000837 }
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900838 for (const auto& defined_type : typenames.MainDocument().DefinedTypes()) {
839 auto mappings = mappings::generate_mappings(defined_type.get(), typenames);
Andrei Onea8714b022019-02-01 18:55:54 +0000840 all_mappings.insert(mappings.begin(), mappings.end());
841 }
842 }
843 std::stringstream mappings_str;
844 for (const auto& mapping : all_mappings) {
845 mappings_str << mapping.first << "\n" << mapping.second << "\n";
846 }
847 auto code_writer = io_delegate.GetCodeWriter(options.OutputFile());
848 code_writer->Write("%s", mappings_str.str().c_str());
849 return true;
850}
851
Jiyong Park74595c12018-07-23 15:22:50 +0900852bool preprocess_aidl(const Options& options, const IoDelegate& io_delegate) {
853 unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(options.OutputFile());
Adam Lesinskiffa16862014-01-23 18:17:42 -0800854
Jiyong Park74595c12018-07-23 15:22:50 +0900855 for (const auto& file : options.InputFiles()) {
Jiyong Park1deecc32018-07-17 01:14:41 +0900856 AidlTypenames typenames;
Steven Moreland64e29be2018-08-08 18:52:19 -0700857 std::unique_ptr<Parser> p = Parser::Parse(file, io_delegate, typenames);
858 if (p == nullptr) return false;
Casey Dahlin59401da2015-10-09 18:16:45 -0700859
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900860 for (const auto& defined_type : p->ParsedDocument().DefinedTypes()) {
Steven Morelanded83a282018-07-17 13:27:29 -0700861 if (!writer->Write("%s %s;\n", defined_type->GetPreprocessDeclarationName().c_str(),
Steven Morelandc258abc2018-07-10 14:03:38 -0700862 defined_type->GetCanonicalName().c_str())) {
Casey Dahlinc1f39b42015-11-24 10:34:34 -0800863 return false;
864 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800865 }
Casey Dahlinc1f39b42015-11-24 10:34:34 -0800866 }
Adam Lesinskiffa16862014-01-23 18:17:42 -0800867
Casey Dahlinc1f39b42015-11-24 10:34:34 -0800868 return writer->Close();
Adam Lesinskiffa16862014-01-23 18:17:42 -0800869}
Christopher Wileyfdeb0f42015-09-11 15:38:22 -0700870
Jiyong Parke59c3682018-09-11 23:10:25 +0900871static string GetApiDumpPathFor(const AidlDefinedType& defined_type, const Options& options) {
872 string package_as_path = Join(Split(defined_type.GetPackage(), "."), OS_PATH_SEPARATOR);
Steven Moreland21780812020-09-11 01:29:45 +0000873 AIDL_FATAL_IF(options.OutputDir().empty() || options.OutputDir().back() != '/', defined_type);
Jiyong Parke59c3682018-09-11 23:10:25 +0900874 return options.OutputDir() + package_as_path + OS_PATH_SEPARATOR + defined_type.GetName() +
875 ".aidl";
876}
Jiyong Parkb034bf02018-07-30 17:44:33 +0900877
Jiyong Parke59c3682018-09-11 23:10:25 +0900878bool dump_api(const Options& options, const IoDelegate& io_delegate) {
Jiyong Park74595c12018-07-23 15:22:50 +0900879 for (const auto& file : options.InputFiles()) {
Jeongik Cha047c5ee2019-08-07 23:16:49 +0900880 AidlTypenames typenames;
Jiyong Park8e79b7f2020-07-20 20:52:38 +0900881 if (internals::load_and_validate_aidl(file, options, io_delegate, &typenames, nullptr) ==
882 AidlError::OK) {
883 for (const auto& type : typenames.MainDocument().DefinedTypes()) {
Jiyong Parke59c3682018-09-11 23:10:25 +0900884 unique_ptr<CodeWriter> writer =
885 io_delegate.GetCodeWriter(GetApiDumpPathFor(*type, options));
Steven Morelandec0531d2018-09-20 11:11:20 -0700886 if (!type->GetPackage().empty()) {
Paul Trautrimb01451d2020-02-27 13:10:16 +0900887 (*writer) << kPreamble << "package " << type->GetPackage() << ";\n";
Steven Morelandec0531d2018-09-20 11:11:20 -0700888 }
Jeongik Cha997281d2020-01-16 15:23:59 +0900889 type->Dump(writer.get());
Jiyong Parkb034bf02018-07-30 17:44:33 +0900890 }
Jiyong Park02da7422018-07-16 16:00:26 +0900891 } else {
892 return false;
893 }
894 }
Jiyong Parke59c3682018-09-11 23:10:25 +0900895 return true;
Jiyong Park02da7422018-07-16 16:00:26 +0900896}
897
Steven Moreland3981d9e2020-03-31 14:11:44 -0700898int aidl_entry(const Options& options, const IoDelegate& io_delegate) {
Steven Moreland33efcf62020-04-10 16:40:43 -0700899 AidlErrorLog::clearError();
900
Steven Moreland3981d9e2020-03-31 14:11:44 -0700901 int ret = 1;
902 switch (options.GetTask()) {
903 case Options::Task::COMPILE:
904 ret = android::aidl::compile_aidl(options, io_delegate);
905 break;
906 case Options::Task::PREPROCESS:
907 ret = android::aidl::preprocess_aidl(options, io_delegate) ? 0 : 1;
908 break;
909 case Options::Task::DUMP_API:
910 ret = android::aidl::dump_api(options, io_delegate) ? 0 : 1;
911 break;
912 case Options::Task::CHECK_API:
913 ret = android::aidl::check_api(options, io_delegate) ? 0 : 1;
914 break;
915 case Options::Task::DUMP_MAPPINGS:
916 ret = android::aidl::dump_mappings(options, io_delegate) ? 0 : 1;
917 break;
918 default:
919 AIDL_FATAL(AIDL_LOCATION_HERE)
920 << "Unrecognized task: " << static_cast<size_t>(options.GetTask());
921 }
922
923 // compiler invariants
Steven Moreland21780812020-09-11 01:29:45 +0000924 const bool shouldReportError = ret != 0;
925 const bool reportedError = AidlErrorLog::hadError();
926 AIDL_FATAL_IF(shouldReportError != reportedError, AIDL_LOCATION_HERE)
927 << "Compiler returned error " << ret << " but did" << (reportedError ? "" : " not")
928 << " emit error logs";
Steven Moreland3981d9e2020-03-31 14:11:44 -0700929
930 return ret;
931}
932
Christopher Wileyfdeb0f42015-09-11 15:38:22 -0700933} // namespace aidl
Steven Morelandf4c64df2019-07-29 19:54:04 -0700934} // namespace android