blob: 0a92ae8434c056bce4a23cc1788e3c6cd524cdc8 [file] [log] [blame]
Christopher Wileyeb1acc12015-09-16 11:25:13 -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 */
16
17#include "generate_cpp.h"
Jiyong Park309668e2018-07-28 16:55:44 +090018#include "aidl.h"
Christopher Wiley9a8e1d92015-09-19 10:34:33 -070019
Casey Dahlin082f1d12015-09-21 14:06:25 -070020#include <cctype>
Christopher Wileyad339272015-10-05 19:11:58 -070021#include <cstring>
Christopher Wiley9a8e1d92015-09-19 10:34:33 -070022#include <memory>
Casey Dahlin082f1d12015-09-21 14:06:25 -070023#include <random>
Casey Dahlince776cf2015-10-15 18:45:54 -070024#include <set>
Christopher Wiley9a8e1d92015-09-19 10:34:33 -070025#include <string>
26
Elliott Hughes0a620672015-12-04 13:53:18 -080027#include <android-base/stringprintf.h>
Christopher Wileye3550c62015-09-29 13:26:10 -070028
Casey Dahlina834dd42015-09-23 11:52:15 -070029#include "aidl_language.h"
Jiyong Parkce50e262018-10-29 09:54:20 +090030#include "aidl_to_cpp.h"
Christopher Wiley9a8e1d92015-09-19 10:34:33 -070031#include "ast_cpp.h"
32#include "code_writer.h"
Christopher Wileyeb1acc12015-09-16 11:25:13 -070033#include "logging.h"
Christopher Wiley054afbd2015-10-16 17:08:43 -070034#include "os.h"
Christopher Wileyeb1acc12015-09-16 11:25:13 -070035
Jiyong Park75e1a742018-07-04 12:31:23 +090036using android::base::Join;
Christopher Wileye3550c62015-09-29 13:26:10 -070037using android::base::StringPrintf;
Jiyong Park75e1a742018-07-04 12:31:23 +090038using std::set;
Christopher Wiley9a8e1d92015-09-19 10:34:33 -070039using std::string;
Casey Dahlin082f1d12015-09-21 14:06:25 -070040using std::unique_ptr;
Casey Dahlina834dd42015-09-23 11:52:15 -070041using std::vector;
Christopher Wiley9a8e1d92015-09-19 10:34:33 -070042
Christopher Wileyeb1acc12015-09-16 11:25:13 -070043namespace android {
44namespace aidl {
Christopher Wileyf944e792015-09-29 10:00:46 -070045namespace cpp {
Casey Dahlina834dd42015-09-23 11:52:15 -070046namespace internals {
Christopher Wiley0c732db2015-09-29 14:36:44 -070047namespace {
Christopher Wiley36570f42015-10-08 17:20:11 -070048
Casey Dahlinb8d9e882015-11-24 10:57:23 -080049const char kAndroidStatusVarName[] = "_aidl_ret_status";
50const char kCodeVarName[] = "_aidl_code";
51const char kFlagsVarName[] = "_aidl_flags";
52const char kDataVarName[] = "_aidl_data";
53const char kErrorLabel[] = "_aidl_error";
54const char kImplVarName[] = "_aidl_impl";
55const char kReplyVarName[] = "_aidl_reply";
Christopher Wileyad339272015-10-05 19:11:58 -070056const char kReturnVarName[] = "_aidl_return";
Casey Dahlinb8d9e882015-11-24 10:57:23 -080057const char kStatusVarName[] = "_aidl_status";
Martijn Coenenf1b50782018-02-21 21:06:23 +010058const char kTraceVarName[] = "_aidl_trace";
Casey Dahlinb8d9e882015-11-24 10:57:23 -080059const char kAndroidParcelLiteral[] = "::android::Parcel";
60const char kAndroidStatusLiteral[] = "::android::status_t";
61const char kAndroidStatusOk[] = "::android::OK";
62const char kBinderStatusLiteral[] = "::android::binder::Status";
Christopher Wiley0c732db2015-09-29 14:36:44 -070063const char kIBinderHeader[] = "binder/IBinder.h";
64const char kIInterfaceHeader[] = "binder/IInterface.h";
Christopher Wileyad339272015-10-05 19:11:58 -070065const char kParcelHeader[] = "binder/Parcel.h";
Christopher Wiley433c8bb2015-11-12 14:20:46 -080066const char kStatusHeader[] = "binder/Status.h";
Christopher Wiley69b44cf2016-05-03 13:43:33 -070067const char kString16Header[] = "utils/String16.h";
Martijn Coenenf1b50782018-02-21 21:06:23 +010068const char kTraceHeader[] = "utils/Trace.h";
Casey Dahlin389781f2015-10-22 13:13:21 -070069const char kStrongPointerHeader[] = "utils/StrongPointer.h";
Jiyong Park75e1a742018-07-04 12:31:23 +090070const char kAndroidBaseMacrosHeader[] = "android-base/macros.h";
Casey Dahlin082f1d12015-09-21 14:06:25 -070071
Christopher Wiley0eb903e2015-10-20 17:07:08 -070072unique_ptr<AstNode> BreakOnStatusNotOk() {
73 IfStatement* ret = new IfStatement(new Comparison(
Casey Dahlinb8d9e882015-11-24 10:57:23 -080074 new LiteralExpression(kAndroidStatusVarName), "!=",
75 new LiteralExpression(kAndroidStatusOk)));
Christopher Wiley0eb903e2015-10-20 17:07:08 -070076 ret->OnTrue()->AddLiteral("break");
77 return unique_ptr<AstNode>(ret);
78}
79
Christopher Wiley433c8bb2015-11-12 14:20:46 -080080unique_ptr<AstNode> GotoErrorOnBadStatus() {
81 IfStatement* ret = new IfStatement(new Comparison(
Casey Dahlinb8d9e882015-11-24 10:57:23 -080082 new LiteralExpression(kAndroidStatusVarName), "!=",
83 new LiteralExpression(kAndroidStatusOk)));
84 ret->OnTrue()->AddLiteral(StringPrintf("goto %s", kErrorLabel));
Christopher Wiley433c8bb2015-11-12 14:20:46 -080085 return unique_ptr<AstNode>(ret);
86}
87
Steven Moreland5557f1c2018-07-02 13:50:23 -070088unique_ptr<AstNode> ReturnOnStatusNotOk() {
89 IfStatement* ret = new IfStatement(new Comparison(new LiteralExpression(kAndroidStatusVarName),
90 "!=", new LiteralExpression(kAndroidStatusOk)));
91 ret->OnTrue()->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
92 return unique_ptr<AstNode>(ret);
93}
94
Christopher Wiley0c732db2015-09-29 14:36:44 -070095string UpperCase(const std::string& s) {
96 string result = s;
97 for (char& c : result)
98 c = toupper(c);
99 return result;
Casey Dahlina834dd42015-09-23 11:52:15 -0700100}
Casey Dahlin082f1d12015-09-21 14:06:25 -0700101
Jiyong Park75e1a742018-07-04 12:31:23 +0900102ArgList BuildArgList(const TypeNamespace& types, const AidlMethod& method, bool for_declaration,
103 bool type_name_only = false) {
Christopher Wileyad339272015-10-05 19:11:58 -0700104 // Build up the argument list for the server method call.
105 vector<string> method_arguments;
106 for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
107 string literal;
108 if (for_declaration) {
109 // Method declarations need types, pointers to out params, and variable
110 // names that match the .aidl specification.
Casey Dahlina2f77c42015-12-01 18:26:02 -0800111 const Type* type = a->GetType().GetLanguageType<Type>();
Casey Dahlince776cf2015-10-15 18:45:54 -0700112
Casey Dahlina2f77c42015-12-01 18:26:02 -0800113 literal = type->CppType();
Casey Dahlinb0966612015-10-19 16:35:26 -0700114
Christopher Wileyb8e49a42015-10-27 12:55:18 -0700115 if (a->IsOut()) {
116 literal = literal + "*";
117 } else {
118 // We pass in parameters that are not primitives by const reference.
119 // Arrays of primitives are not primitives.
120 if (!type->IsCppPrimitive() || a->GetType().IsArray()) {
121 literal = "const " + literal + "&";
122 }
123 }
Jiyong Park75e1a742018-07-04 12:31:23 +0900124 if (!type_name_only) {
125 literal += " " + a->GetName();
126 }
Christopher Wileyad339272015-10-05 19:11:58 -0700127 } else {
128 if (a->IsOut()) { literal = "&"; }
129 literal += BuildVarName(*a);
130 }
131 method_arguments.push_back(literal);
132 }
133
Casey Dahlina2f77c42015-12-01 18:26:02 -0800134 const Type* return_type = method.GetType().GetLanguageType<Type>();
Casey Dahlince776cf2015-10-15 18:45:54 -0700135
Christopher Wileyad339272015-10-05 19:11:58 -0700136 if (return_type != types.VoidType()) {
Christopher Wileyade4b452015-10-10 11:06:03 -0700137 string literal;
Christopher Wileyad339272015-10-05 19:11:58 -0700138 if (for_declaration) {
Jiyong Park75e1a742018-07-04 12:31:23 +0900139 literal = StringPrintf("%s* %s", return_type->CppType().c_str(),
140 type_name_only ? "" : kReturnVarName);
Christopher Wileyad339272015-10-05 19:11:58 -0700141 } else {
Christopher Wileyade4b452015-10-10 11:06:03 -0700142 literal = string{"&"} + kReturnVarName;
Christopher Wileyad339272015-10-05 19:11:58 -0700143 }
Christopher Wileyade4b452015-10-10 11:06:03 -0700144 method_arguments.push_back(literal);
Christopher Wileyad339272015-10-05 19:11:58 -0700145 }
146
Christopher Wileyade4b452015-10-10 11:06:03 -0700147 return ArgList(method_arguments);
Casey Dahlina834dd42015-09-23 11:52:15 -0700148}
149
Casey Dahlin5c69deb2015-10-01 14:44:12 -0700150unique_ptr<Declaration> BuildMethodDecl(const AidlMethod& method,
Christopher Wiley0c732db2015-09-29 14:36:44 -0700151 const TypeNamespace& types,
152 bool for_interface) {
Christopher Wiley0c732db2015-09-29 14:36:44 -0700153 uint32_t modifiers = 0;
154 if (for_interface) {
155 modifiers |= MethodDecl::IS_VIRTUAL;
156 modifiers |= MethodDecl::IS_PURE_VIRTUAL;
157 } else {
158 modifiers |= MethodDecl::IS_OVERRIDE;
159 }
160
161 return unique_ptr<Declaration>{
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800162 new MethodDecl{kBinderStatusLiteral,
Casey Dahlinf4a93112015-10-05 16:58:09 -0700163 method.GetName(),
Christopher Wileyad339272015-10-05 19:11:58 -0700164 BuildArgList(types, method, true /* for method decl */),
Christopher Wiley0c732db2015-09-29 14:36:44 -0700165 modifiers}};
166}
167
Jiyong Park309668e2018-07-28 16:55:44 +0900168unique_ptr<Declaration> BuildMetaMethodDecl(const AidlMethod& method, const TypeNamespace&,
169 const Options& options, bool for_interface) {
170 CHECK(!method.IsUserDefined());
171 if (method.GetName() == kGetInterfaceVersion && options.Version()) {
172 std::ostringstream code;
173 if (for_interface) {
174 code << "virtual ";
175 }
176 code << "int32_t " << kGetInterfaceVersion << "()";
177 if (for_interface) {
178 code << " = 0;\n";
179 } else {
180 code << " override;\n";
181 }
182 return unique_ptr<Declaration>(new LiteralDecl(code.str()));
183 }
184 return nullptr;
185}
186
Steven Morelandf3da0892018-10-05 14:52:01 -0700187std::vector<unique_ptr<Declaration>> NestInNamespaces(vector<unique_ptr<Declaration>> decls,
188 const vector<string>& package) {
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700189 auto it = package.crbegin(); // Iterate over the namespaces inner to outer
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700190 for (; it != package.crend(); ++it) {
Steven Morelandf3da0892018-10-05 14:52:01 -0700191 vector<unique_ptr<Declaration>> inner;
192 inner.emplace_back(unique_ptr<Declaration>{new CppNamespace{*it, std::move(decls)}});
193
194 decls = std::move(inner);
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700195 }
Steven Morelandf3da0892018-10-05 14:52:01 -0700196 return decls;
Christopher Wiley0c732db2015-09-29 14:36:44 -0700197}
198
Steven Morelandf3da0892018-10-05 14:52:01 -0700199std::vector<unique_ptr<Declaration>> NestInNamespaces(unique_ptr<Declaration> decl,
200 const vector<string>& package) {
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700201 vector<unique_ptr<Declaration>> decls;
202 decls.push_back(std::move(decl));
203 return NestInNamespaces(std::move(decls), package);
Christopher Wiley36570f42015-10-08 17:20:11 -0700204}
205
Steven Moreland1c41e972018-07-09 16:07:00 -0700206bool DeclareLocalVariable(const AidlArgument& a, StatementBlock* b) {
Casey Dahlina2f77c42015-12-01 18:26:02 -0800207 const Type* cpp_type = a.GetType().GetLanguageType<Type>();
Christopher Wileyad339272015-10-05 19:11:58 -0700208 if (!cpp_type) { return false; }
209
Casey Dahlina2f77c42015-12-01 18:26:02 -0800210 string type = cpp_type->CppType();
Casey Dahlinb0966612015-10-19 16:35:26 -0700211
212 b->AddLiteral(type + " " + BuildVarName(a));
Christopher Wileyad339272015-10-05 19:11:58 -0700213 return true;
214}
215
Steven Moreland5557f1c2018-07-02 13:50:23 -0700216string BuildHeaderGuard(const AidlDefinedType& defined_type, ClassNames header_type) {
217 string class_name = ClassName(defined_type, header_type);
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700218 for (size_t i = 1; i < class_name.size(); ++i) {
219 if (isupper(class_name[i])) {
220 class_name.insert(i, "_");
221 ++i;
222 }
223 }
Steven Moreland5557f1c2018-07-02 13:50:23 -0700224 string ret = StringPrintf("AIDL_GENERATED_%s_%s_H_", defined_type.GetPackage().c_str(),
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700225 class_name.c_str());
226 for (char& c : ret) {
227 if (c == '.') {
228 c = '_';
229 }
230 c = toupper(c);
231 }
232 return ret;
233}
Christopher Wiley36570f42015-10-08 17:20:11 -0700234
235unique_ptr<Declaration> DefineClientTransaction(const TypeNamespace& types,
236 const AidlInterface& interface,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900237 const AidlMethod& method, const Options& options) {
Christopher Wiley36570f42015-10-08 17:20:11 -0700238 const string i_name = ClassName(interface, ClassNames::INTERFACE);
239 const string bp_name = ClassName(interface, ClassNames::CLIENT);
240 unique_ptr<MethodImpl> ret{new MethodImpl{
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800241 kBinderStatusLiteral, bp_name, method.GetName(),
Christopher Wiley36570f42015-10-08 17:20:11 -0700242 ArgList{BuildArgList(types, method, true /* for method decl */)}}};
243 StatementBlock* b = ret->GetStatementBlock();
244
245 // Declare parcels to hold our query and the response.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800246 b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kDataVarName));
Christopher Wiley1227d612015-10-26 16:59:20 -0700247 // Even if we're oneway, the transact method still takes a parcel.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800248 b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kReplyVarName));
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700249
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800250 // Declare the status_t variable we need for error handling.
Christopher Wiley10957122015-12-04 14:35:38 -0800251 b->AddLiteral(StringPrintf("%s %s = %s", kAndroidStatusLiteral,
252 kAndroidStatusVarName,
253 kAndroidStatusOk));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800254 // We unconditionally return a Status object.
255 b->AddLiteral(StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName));
Christopher Wiley36570f42015-10-08 17:20:11 -0700256
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900257 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100258 b->AddLiteral(
259 StringPrintf("ScopedTrace %s(ATRACE_TAG_AIDL, \"%s::%s::cppClient\")",
260 kTraceVarName, interface.GetName().c_str(), method.GetName().c_str()));
261 }
262
Jiyong Parkce50e262018-10-29 09:54:20 +0900263 if (options.GenLog()) {
264 string code;
265 CodeWriterPtr writer = CodeWriter::ForString(&code);
266 (*writer) << "Json::Value _log_input_args(Json::objectValue);\n";
267
268 (*writer) << "if (" << bp_name << "::logFunc != nullptr) {\n";
269 (*writer).Indent();
270
271 for (const auto& a : method.GetArguments()) {
272 if (a->IsIn()) {
273 WriteLogFor({*(writer.get()), types.typenames_, a->GetType(), a->GetName(), a->IsOut(),
274 "_log_input_args"});
275 }
276 }
277
278 (*writer).Dedent();
279 (*writer) << "}\n";
280
281 (*writer) << "auto _log_start = std::chrono::steady_clock::now();\n";
282 writer->Close();
283 b->AddLiteral(code, false /* no semicolon */);
284 }
285
Christopher Wiley8993cb52015-10-21 09:53:24 -0700286 // Add the name of the interface we're hoping to call.
287 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800288 kAndroidStatusVarName,
289 new MethodCall(StringPrintf("%s.writeInterfaceToken",
290 kDataVarName),
291 "getInterfaceDescriptor()")));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800292 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley8993cb52015-10-21 09:53:24 -0700293
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700294 for (const auto& a: method.GetArguments()) {
Casey Dahlina2f77c42015-12-01 18:26:02 -0800295 const Type* type = a->GetType().GetLanguageType<Type>();
Christopher Wiley36570f42015-10-08 17:20:11 -0700296 string var_name = ((a->IsOut()) ? "*" : "") + a->GetName();
Casey Dahlin389781f2015-10-22 13:13:21 -0700297 var_name = type->WriteCast(var_name);
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700298
299 if (a->IsIn()) {
300 // Serialization looks roughly like:
301 // _aidl_ret_status = _aidl_data.WriteInt32(in_param_name);
302 // if (_aidl_ret_status != ::android::OK) { goto error; }
303 const string& method = type->WriteToParcelMethod();
304 b->AddStatement(new Assignment(
305 kAndroidStatusVarName,
306 new MethodCall(StringPrintf("%s.%s", kDataVarName, method.c_str()),
307 ArgList(var_name))));
308 b->AddStatement(GotoErrorOnBadStatus());
309 } else if (a->IsOut() && a->GetType().IsArray()) {
310 // Special case, the length of the out array is written into the parcel.
311 // _aidl_ret_status = _aidl_data.writeVectorSize(&out_param_name);
312 // if (_aidl_ret_status != ::android::OK) { goto error; }
313 b->AddStatement(new Assignment(
314 kAndroidStatusVarName,
315 new MethodCall(StringPrintf("%s.writeVectorSize", kDataVarName),
316 ArgList(var_name))));
317 b->AddStatement(GotoErrorOnBadStatus());
318 }
Christopher Wiley36570f42015-10-08 17:20:11 -0700319 }
320
321 // Invoke the transaction on the remote binder and confirm status.
322 string transaction_code = StringPrintf(
323 "%s::%s", i_name.c_str(), UpperCase(method.GetName()).c_str());
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700324
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800325 vector<string> args = {transaction_code, kDataVarName,
326 StringPrintf("&%s", kReplyVarName)};
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700327
328 if (interface.IsOneway() || method.IsOneway()) {
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800329 args.push_back("::android::IBinder::FLAG_ONEWAY");
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700330 }
331
Christopher Wiley36570f42015-10-08 17:20:11 -0700332 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800333 kAndroidStatusVarName,
Christopher Wiley36570f42015-10-08 17:20:11 -0700334 new MethodCall("remote()->transact",
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700335 ArgList(args))));
Jiyong Park75e1a742018-07-04 12:31:23 +0900336
337 // If the method is not implemented in the remote side, try to call the
338 // default implementation, if provided.
339 vector<string> arg_names;
340 for (const auto& a : method.GetArguments()) {
341 arg_names.emplace_back(a->GetName());
342 }
343 if (method.GetType().GetLanguageType<Type>() != types.VoidType()) {
344 arg_names.emplace_back(kReturnVarName);
345 }
346 b->AddLiteral(StringPrintf("if (UNLIKELY(_aidl_ret_status == ::android::UNKNOWN_TRANSACTION && "
347 "%s::getDefaultImpl())) {\n"
348 " return %s::getDefaultImpl()->%s(%s);\n"
349 "}\n",
350 i_name.c_str(), i_name.c_str(), method.GetName().c_str(),
351 Join(arg_names, ", ").c_str()),
352 false /* no semicolon */);
353
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800354 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley36570f42015-10-08 17:20:11 -0700355
Christopher Wiley1227d612015-10-26 16:59:20 -0700356 if (!interface.IsOneway() && !method.IsOneway()) {
357 // Strip off the exception header and fail if we see a remote exception.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800358 // _aidl_ret_status = _aidl_status.readFromParcel(_aidl_reply);
359 // if (_aidl_ret_status != ::android::OK) { goto error; }
360 // if (!_aidl_status.isOk()) { return _aidl_ret_status; }
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800361 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800362 kAndroidStatusVarName,
363 StringPrintf("%s.readFromParcel(%s)", kStatusVarName, kReplyVarName)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800364 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley1227d612015-10-26 16:59:20 -0700365 IfStatement* exception_check = new IfStatement(
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800366 new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
Christopher Wiley1227d612015-10-26 16:59:20 -0700367 b->AddStatement(exception_check);
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800368 exception_check->OnTrue()->AddLiteral(
369 StringPrintf("return %s", kStatusVarName));
Christopher Wiley1227d612015-10-26 16:59:20 -0700370 }
371
372 // Type checking should guarantee that nothing below emits code until "return
373 // status" if we are a oneway method, so no more fear of accessing reply.
Christopher Wiley2aaeda82015-10-19 15:16:49 -0700374
Christopher Wiley36570f42015-10-08 17:20:11 -0700375 // If the method is expected to return something, read it first by convention.
Casey Dahlina2f77c42015-12-01 18:26:02 -0800376 const Type* return_type = method.GetType().GetLanguageType<Type>();
Christopher Wiley36570f42015-10-08 17:20:11 -0700377 if (return_type != types.VoidType()) {
Chih-Hung Hsiehf05cc262016-07-27 11:42:51 -0700378 const string& method_call = return_type->ReadFromParcelMethod();
Christopher Wiley36570f42015-10-08 17:20:11 -0700379 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800380 kAndroidStatusVarName,
381 new MethodCall(StringPrintf("%s.%s", kReplyVarName,
382 method_call.c_str()),
383 ArgList(kReturnVarName))));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800384 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley36570f42015-10-08 17:20:11 -0700385 }
386
387 for (const AidlArgument* a : method.GetOutArguments()) {
388 // Deserialization looks roughly like:
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800389 // _aidl_ret_status = _aidl_reply.ReadInt32(out_param_name);
390 // if (_aidl_status != ::android::OK) { goto _aidl_error; }
Casey Dahlinb0966612015-10-19 16:35:26 -0700391 string method =
Casey Dahlina2f77c42015-12-01 18:26:02 -0800392 a->GetType().GetLanguageType<Type>()->ReadFromParcelMethod();
Casey Dahlinb0966612015-10-19 16:35:26 -0700393
Christopher Wiley36570f42015-10-08 17:20:11 -0700394 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800395 kAndroidStatusVarName,
396 new MethodCall(StringPrintf("%s.%s", kReplyVarName,
397 method.c_str()),
398 ArgList(a->GetName()))));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800399 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley36570f42015-10-08 17:20:11 -0700400 }
401
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800402 // If we've gotten to here, one of two things is true:
403 // 1) We've read some bad status_t
404 // 2) We've only read status_t == OK and there was no exception in the
405 // response.
406 // In both cases, we're free to set Status from the status_t and return.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800407 b->AddLiteral(StringPrintf("%s:\n", kErrorLabel), false /* no semicolon */);
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800408 b->AddLiteral(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800409 StringPrintf("%s.setFromStatusT(%s)", kStatusVarName,
410 kAndroidStatusVarName));
Martijn Coenenf1b50782018-02-21 21:06:23 +0100411
Jiyong Parkce50e262018-10-29 09:54:20 +0900412 if (options.GenLog()) {
413 string code;
414 CodeWriterPtr writer = CodeWriter::ForString(&code);
415
416 (*writer) << "if (" << bp_name << "::logFunc != nullptr) {\n";
417 (*writer).Indent();
418
419 // Write the log as a Json object. For example,
420 //
421 // Json log object for following interface description
422 //
423 // package foo.bar;
424 // interface IFoo {
425 // String TestMethod(int arg1, inout String[] arg2, out double arg3);
426 // }
427 //
428 // would be:
429 //
430 // {
431 // duration_ms: 100,
432 // interface_name: "foo.bar.IFoo",
433 // method_name: "TestMethod",
434 // proxy_address: "0x12345678",
435 // input_args: {
436 // arg1: 30,
437 // arg2: ["apple", "grape"],
438 // },
439 // output_args: {
440 // arg2: ["mango", "banana"],
441 // arg3: "10.5",
442 // },
443 // _aidl_return: "ok",
444 // }
445 (*writer) << "auto _log_end = std::chrono::steady_clock::now();\n";
446 (*writer) << "Json::Value _log_transaction(Json::objectValue);\n";
447 (*writer) << "_log_transaction[\"duration_ms\"] = "
448 << "std::chrono::duration_cast<std::chrono::milliseconds>(_log_end - "
449 "_log_start).count();\n";
450 (*writer) << "_log_transaction[\"interface_name\"] = "
451 << "Json::Value(\"" << interface.GetCanonicalName() << "\");\n";
452 (*writer) << "_log_transaction[\"method_name\"] = "
453 << "Json::Value(\"" << method.GetName() << "\");\n";
454 (*writer) << "_log_transaction[\"proxy_address\"] = "
455 << "Json::Value(android::base::StringPrintf(\"0x%%p\", this));\n";
456 (*writer) << "_log_transaction[\"input_args\"] = _log_input_args;\n";
457 (*writer) << "Json::Value _log_output_args(Json::objectValue);\n";
458
459 for (const auto& a : method.GetOutArguments()) {
460 WriteLogFor({*(writer.get()), types.typenames_, a->GetType(), a->GetName(), true,
461 "_log_output_args"});
462 }
463
464 (*writer) << "_log_transaction[\"output_args\"] = _log_output_args;\n";
465
466 if (method.GetType().GetName() != "void") {
467 WriteLogFor({*(writer.get()), types.typenames_, method.GetType(), kReturnVarName, true,
468 "_log_transaction"});
469 }
470
471 // call the user-provided function with the Json object for the entire
472 // transaction
473 (*writer) << bp_name << "::logFunc(_log_transaction);\n";
474
475 (*writer).Dedent();
476 (*writer) << "}\n";
477
478 writer->Close();
479 b->AddLiteral(code, false /* no semicolon */);
480 }
481
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800482 b->AddLiteral(StringPrintf("return %s", kStatusVarName));
Christopher Wiley36570f42015-10-08 17:20:11 -0700483
484 return unique_ptr<Declaration>(ret.release());
485}
486
Jiyong Park309668e2018-07-28 16:55:44 +0900487unique_ptr<Declaration> DefineClientMetaTransaction(const TypeNamespace&,
488 const AidlInterface& interface,
489 const AidlMethod& method,
490 const Options& options) {
491 CHECK(!method.IsUserDefined());
492 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
493 const string iface = ClassName(interface, ClassNames::INTERFACE);
494 const string proxy = ClassName(interface, ClassNames::CLIENT);
495 // Note: race condition can happen here, but no locking is required
496 // because 1) writing an interger is atomic and 2) this transaction
497 // will always return the same value, i.e., competing threads will
498 // give write the same value to cached_version_.
499 std::ostringstream code;
500 code << "int32_t " << proxy << "::" << kGetInterfaceVersion << "() {\n"
501 << " if (cached_version_ != -1) {\n"
502 << " ::android::Parcel data;\n"
503 << " ::android::Parcel reply;\n"
504 << " ::android::status_t err = remote()->transact(" << iface
505 << "::" << UpperCase(kGetInterfaceVersion) << ", data, &reply);\n"
506 << " if (err == ::android::OK) {\n"
507 << " cached_version_ = reply.readInt32();\n"
508 << " }\n"
509 << " }\n"
510 << " return cached_version_;\n"
511 << "}\n";
512 return unique_ptr<Declaration>(new LiteralDecl(code.str()));
513 }
514 return nullptr;
515}
516
Christopher Wiley36570f42015-10-08 17:20:11 -0700517} // namespace
518
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900519unique_ptr<Document> BuildClientSource(const TypeNamespace& types, const AidlInterface& interface,
520 const Options& options) {
Christopher Wiley054afbd2015-10-16 17:08:43 -0700521 vector<string> include_list = {
522 HeaderFile(interface, ClassNames::CLIENT, false),
Jiyong Park75e1a742018-07-04 12:31:23 +0900523 kParcelHeader,
524 kAndroidBaseMacrosHeader
Christopher Wiley054afbd2015-10-16 17:08:43 -0700525 };
Jiyong Parkce50e262018-10-29 09:54:20 +0900526 if (options.GenLog()) {
527 include_list.emplace_back("chrono");
528 include_list.emplace_back("functional");
529 include_list.emplace_back("json/value.h");
530 include_list.emplace_back("android-base/stringprintf.h");
531 }
Christopher Wiley36570f42015-10-08 17:20:11 -0700532 vector<unique_ptr<Declaration>> file_decls;
533
534 // The constructor just passes the IBinder instance up to the super
535 // class.
Christopher Wiley1db03482015-10-22 11:42:02 -0700536 const string i_name = ClassName(interface, ClassNames::INTERFACE);
Christopher Wiley36570f42015-10-08 17:20:11 -0700537 file_decls.push_back(unique_ptr<Declaration>{new ConstructorImpl{
Christopher Wiley054afbd2015-10-16 17:08:43 -0700538 ClassName(interface, ClassNames::CLIENT),
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800539 ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
540 kImplVarName)},
541 { "BpInterface<" + i_name + ">(" + kImplVarName + ")" }}});
Christopher Wiley36570f42015-10-08 17:20:11 -0700542
Jiyong Parkce50e262018-10-29 09:54:20 +0900543 if (options.GenLog()) {
544 string code;
545 ClassName(interface, ClassNames::CLIENT);
546 CodeWriterPtr writer = CodeWriter::ForString(&code);
547 (*writer) << "std::function<void(const Json::Value&)> "
548 << ClassName(interface, ClassNames::CLIENT) << "::logFunc;\n";
549 writer->Close();
550 file_decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
551 }
552
Christopher Wiley36570f42015-10-08 17:20:11 -0700553 // Clients define a method per transaction.
554 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900555 unique_ptr<Declaration> m;
556 if (method->IsUserDefined()) {
557 m = DefineClientTransaction(types, interface, *method, options);
558 } else {
559 m = DefineClientMetaTransaction(types, interface, *method, options);
560 }
Christopher Wiley36570f42015-10-08 17:20:11 -0700561 if (!m) { return nullptr; }
562 file_decls.push_back(std::move(m));
563 }
564 return unique_ptr<Document>{new CppSource{
565 include_list,
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700566 NestInNamespaces(std::move(file_decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700567}
568
Christopher Wileyad339272015-10-05 19:11:58 -0700569namespace {
570
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900571bool HandleServerTransaction(const TypeNamespace& types, const AidlInterface& interface,
572 const AidlMethod& method, const Options& options, StatementBlock* b) {
Christopher Wileyad339272015-10-05 19:11:58 -0700573 // Declare all the parameters now. In the common case, we expect no errors
574 // in serialization.
575 for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
Steven Moreland1c41e972018-07-09 16:07:00 -0700576 if (!DeclareLocalVariable(*a, b)) {
577 return false;
578 }
Christopher Wileyad339272015-10-05 19:11:58 -0700579 }
580
581 // Declare a variable to hold the return value.
Casey Dahlina2f77c42015-12-01 18:26:02 -0800582 const Type* return_type = method.GetType().GetLanguageType<Type>();
Christopher Wileyad339272015-10-05 19:11:58 -0700583 if (return_type != types.VoidType()) {
584 b->AddLiteral(StringPrintf(
Casey Dahlina2f77c42015-12-01 18:26:02 -0800585 "%s %s", return_type->CppType().c_str(),
Casey Dahlinb0966612015-10-19 16:35:26 -0700586 kReturnVarName));
Christopher Wileyad339272015-10-05 19:11:58 -0700587 }
588
Christopher Wiley8993cb52015-10-21 09:53:24 -0700589 // Check that the client is calling the correct interface.
590 IfStatement* interface_check = new IfStatement(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800591 new MethodCall(StringPrintf("%s.checkInterface",
592 kDataVarName), "this"),
Christopher Wiley8993cb52015-10-21 09:53:24 -0700593 true /* invert the check */);
594 b->AddStatement(interface_check);
595 interface_check->OnTrue()->AddStatement(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800596 new Assignment(kAndroidStatusVarName, "::android::BAD_TYPE"));
Christopher Wiley8993cb52015-10-21 09:53:24 -0700597 interface_check->OnTrue()->AddLiteral("break");
598
Christopher Wileyad339272015-10-05 19:11:58 -0700599 // Deserialize each "in" parameter to the transaction.
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700600 for (const auto& a: method.GetArguments()) {
Christopher Wileyad339272015-10-05 19:11:58 -0700601 // Deserialization looks roughly like:
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800602 // _aidl_ret_status = _aidl_data.ReadInt32(&in_param_name);
603 // if (_aidl_ret_status != ::android::OK) { break; }
Casey Dahlina2f77c42015-12-01 18:26:02 -0800604 const Type* type = a->GetType().GetLanguageType<Type>();
Chih-Hung Hsiehf05cc262016-07-27 11:42:51 -0700605 const string& readMethod = type->ReadFromParcelMethod();
Casey Dahlinb0966612015-10-19 16:35:26 -0700606
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700607 if (a->IsIn()) {
608 b->AddStatement(new Assignment{
609 kAndroidStatusVarName,
610 new MethodCall{string(kDataVarName) + "." + readMethod,
611 "&" + BuildVarName(*a)}});
612 b->AddStatement(BreakOnStatusNotOk());
613 } else if (a->IsOut() && a->GetType().IsArray()) {
614 // Special case, the length of the out array is written into the parcel.
615 // _aidl_ret_status = _aidl_data.resizeOutVector(&out_param_name);
616 // if (_aidl_ret_status != ::android::OK) { break; }
617 b->AddStatement(new Assignment{
618 kAndroidStatusVarName,
619 new MethodCall{string(kDataVarName) + ".resizeOutVector",
620 "&" + BuildVarName(*a)}});
621 b->AddStatement(BreakOnStatusNotOk());
622 }
Christopher Wileyad339272015-10-05 19:11:58 -0700623 }
624
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900625 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100626 b->AddStatement(new Statement(new MethodCall("atrace_begin",
627 ArgList{{"ATRACE_TAG_AIDL",
628 StringPrintf("\"%s::%s::cppServer\"",
629 interface.GetName().c_str(),
630 method.GetName().c_str())}})));
631 }
632
Christopher Wileyad339272015-10-05 19:11:58 -0700633 // Call the actual method. This is implemented by the subclass.
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800634 vector<unique_ptr<AstNode>> status_args;
635 status_args.emplace_back(new MethodCall(
Christopher Wileyad339272015-10-05 19:11:58 -0700636 method.GetName(),
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800637 BuildArgList(types, method, false /* not for method decl */)));
638 b->AddStatement(new Statement(new MethodCall(
639 StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName),
640 ArgList(std::move(status_args)))));
Christopher Wileyad339272015-10-05 19:11:58 -0700641
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900642 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100643 b->AddStatement(new Statement(new MethodCall("atrace_end",
644 "ATRACE_TAG_AIDL")));
645 }
646
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800647 // Write exceptions during transaction handling to parcel.
648 if (!method.IsOneway()) {
649 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800650 kAndroidStatusVarName,
651 StringPrintf("%s.writeToParcel(%s)", kStatusVarName, kReplyVarName)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800652 b->AddStatement(BreakOnStatusNotOk());
653 IfStatement* exception_check = new IfStatement(
654 new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
655 b->AddStatement(exception_check);
656 exception_check->OnTrue()->AddLiteral("break");
657 }
Casey Dahlinb0966612015-10-19 16:35:26 -0700658
Christopher Wiley36570f42015-10-08 17:20:11 -0700659 // If we have a return value, write it first.
660 if (return_type != types.VoidType()) {
Christopher Wiley2aaeda82015-10-19 15:16:49 -0700661 string writeMethod =
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800662 string(kReplyVarName) + "->" +
Casey Dahlina2f77c42015-12-01 18:26:02 -0800663 return_type->WriteToParcelMethod();
Christopher Wiley36570f42015-10-08 17:20:11 -0700664 b->AddStatement(new Assignment{
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800665 kAndroidStatusVarName, new MethodCall{writeMethod,
Casey Dahlin389781f2015-10-22 13:13:21 -0700666 ArgList{return_type->WriteCast(kReturnVarName)}}});
Christopher Wiley0eb903e2015-10-20 17:07:08 -0700667 b->AddStatement(BreakOnStatusNotOk());
Christopher Wiley36570f42015-10-08 17:20:11 -0700668 }
669
Christopher Wileyad339272015-10-05 19:11:58 -0700670 // Write each out parameter to the reply parcel.
671 for (const AidlArgument* a : method.GetOutArguments()) {
672 // Serialization looks roughly like:
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800673 // _aidl_ret_status = data.WriteInt32(out_param_name);
674 // if (_aidl_ret_status != ::android::OK) { break; }
Casey Dahlina2f77c42015-12-01 18:26:02 -0800675 const Type* type = a->GetType().GetLanguageType<Type>();
Chih-Hung Hsiehf05cc262016-07-27 11:42:51 -0700676 const string& writeMethod = type->WriteToParcelMethod();
Casey Dahlinb0966612015-10-19 16:35:26 -0700677
Christopher Wileyad339272015-10-05 19:11:58 -0700678 b->AddStatement(new Assignment{
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800679 kAndroidStatusVarName,
680 new MethodCall{string(kReplyVarName) + "->" + writeMethod,
Casey Dahlin389781f2015-10-22 13:13:21 -0700681 type->WriteCast(BuildVarName(*a))}});
Christopher Wiley0eb903e2015-10-20 17:07:08 -0700682 b->AddStatement(BreakOnStatusNotOk());
Christopher Wileyad339272015-10-05 19:11:58 -0700683 }
684
685 return true;
686}
687
Jiyong Park309668e2018-07-28 16:55:44 +0900688bool HandleServerMetaTransaction(const TypeNamespace&, const AidlInterface& interface,
689 const AidlMethod& method, const Options& options,
690 StatementBlock* b) {
691 CHECK(!method.IsUserDefined());
692
693 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
694 std::ostringstream code;
695 code << "_aidl_reply->writeInt32(" << ClassName(interface, ClassNames::INTERFACE)
696 << "::VERSION)";
697 b->AddLiteral(code.str());
698 return true;
699 }
700 return false;
701}
702
Christopher Wileyad339272015-10-05 19:11:58 -0700703} // namespace
704
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900705unique_ptr<Document> BuildServerSource(const TypeNamespace& types, const AidlInterface& interface,
706 const Options& options) {
Christopher Wiley054afbd2015-10-16 17:08:43 -0700707 const string bn_name = ClassName(interface, ClassNames::SERVER);
708 vector<string> include_list{
709 HeaderFile(interface, ClassNames::SERVER, false),
710 kParcelHeader
711 };
Christopher Wileyad339272015-10-05 19:11:58 -0700712 unique_ptr<MethodImpl> on_transact{new MethodImpl{
713 kAndroidStatusLiteral, bn_name, "onTransact",
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800714 ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
715 StringPrintf("const %s& %s", kAndroidParcelLiteral,
716 kDataVarName),
717 StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
718 StringPrintf("uint32_t %s", kFlagsVarName)}}
Christopher Wiley36570f42015-10-08 17:20:11 -0700719 }};
Christopher Wileyad339272015-10-05 19:11:58 -0700720
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800721 // Declare the status_t variable
Christopher Wiley05f4f892015-10-14 13:30:43 -0700722 on_transact->GetStatementBlock()->AddLiteral(
Christopher Wiley10957122015-12-04 14:35:38 -0800723 StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName,
724 kAndroidStatusOk));
Christopher Wiley05f4f892015-10-14 13:30:43 -0700725
Christopher Wileyad339272015-10-05 19:11:58 -0700726 // Add the all important switch statement, but retain a pointer to it.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800727 SwitchStatement* s = new SwitchStatement{kCodeVarName};
Christopher Wileyf9688b02015-10-08 17:17:50 -0700728 on_transact->GetStatementBlock()->AddStatement(s);
Christopher Wileyad339272015-10-05 19:11:58 -0700729
730 // The switch statement has a case statement for each transaction code.
Christopher Wiley054afbd2015-10-16 17:08:43 -0700731 for (const auto& method : interface.GetMethods()) {
Christopher Wileyad339272015-10-05 19:11:58 -0700732 StatementBlock* b = s->AddCase("Call::" + UpperCase(method->GetName()));
733 if (!b) { return nullptr; }
734
Jiyong Park309668e2018-07-28 16:55:44 +0900735 bool success = false;
736 if (method->IsUserDefined()) {
737 success = HandleServerTransaction(types, interface, *method, options, b);
738 } else {
739 success = HandleServerMetaTransaction(types, interface, *method, options, b);
740 }
741 if (!success) {
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900742 return nullptr;
743 }
Christopher Wileyad339272015-10-05 19:11:58 -0700744 }
745
746 // The switch statement has a default case which defers to the super class.
747 // The superclass handles a few pre-defined transactions.
748 StatementBlock* b = s->AddCase("");
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800749 b->AddLiteral(StringPrintf(
750 "%s = ::android::BBinder::onTransact(%s, %s, "
751 "%s, %s)", kAndroidStatusVarName, kCodeVarName,
752 kDataVarName, kReplyVarName, kFlagsVarName));
Christopher Wileyad339272015-10-05 19:11:58 -0700753
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800754 // If we saw a null reference, we can map that to an appropriate exception.
755 IfStatement* null_check = new IfStatement(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800756 new LiteralExpression(string(kAndroidStatusVarName) +
757 " == ::android::UNEXPECTED_NULL"));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800758 on_transact->GetStatementBlock()->AddStatement(null_check);
759 null_check->OnTrue()->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800760 kAndroidStatusVarName,
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800761 StringPrintf("%s::fromExceptionCode(%s::EX_NULL_POINTER)"
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800762 ".writeToParcel(%s)",
763 kBinderStatusLiteral, kBinderStatusLiteral,
764 kReplyVarName)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800765
Christopher Wileyad339272015-10-05 19:11:58 -0700766 // Finally, the server's onTransact method just returns a status code.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800767 on_transact->GetStatementBlock()->AddLiteral(
768 StringPrintf("return %s", kAndroidStatusVarName));
Christopher Wileyad339272015-10-05 19:11:58 -0700769
770 return unique_ptr<Document>{new CppSource{
771 include_list,
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700772 NestInNamespaces(std::move(on_transact), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700773}
774
Jiyong Park75e1a742018-07-04 12:31:23 +0900775unique_ptr<Document> BuildInterfaceSource(const TypeNamespace& types,
Jiyong Park309668e2018-07-28 16:55:44 +0900776 const AidlInterface& interface, const Options& options) {
Christopher Wiley054afbd2015-10-16 17:08:43 -0700777 vector<string> include_list{
778 HeaderFile(interface, ClassNames::INTERFACE, false),
779 HeaderFile(interface, ClassNames::CLIENT, false),
780 };
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700781
Christopher Wiley054afbd2015-10-16 17:08:43 -0700782 string fq_name = ClassName(interface, ClassNames::INTERFACE);
783 if (!interface.GetPackage().empty()) {
784 fq_name = interface.GetPackage() + "." + fq_name;
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700785 }
786
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700787 vector<unique_ptr<Declaration>> decls;
788
Christopher Wiley11a9d792016-02-24 17:20:33 -0800789 unique_ptr<MacroDecl> meta_if{new MacroDecl{
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700790 "IMPLEMENT_META_INTERFACE",
Christopher Wiley054afbd2015-10-16 17:08:43 -0700791 ArgList{vector<string>{ClassName(interface, ClassNames::BASE),
Christopher Wileyade4b452015-10-10 11:06:03 -0700792 '"' + fq_name + '"'}}}};
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700793 decls.push_back(std::move(meta_if));
794
Steven Moreland693640b2018-07-19 13:46:27 -0700795 for (const auto& constant : interface.GetConstantDeclarations()) {
796 const AidlConstantValue& value = constant->GetValue();
797 if (value.GetType() != AidlConstantValue::Type::STRING) continue;
798
Steven Moreland4d12f9a2018-10-31 14:30:55 -0700799 std::string cppType = constant->GetType().GetLanguageType<Type>()->CppType();
800
801 unique_ptr<MethodImpl> getter(new MethodImpl("const " + cppType + "&",
802 ClassName(interface, ClassNames::INTERFACE),
803 constant->GetName(), {}));
Steven Moreland860b1942018-08-16 14:59:28 -0700804 getter->GetStatementBlock()->AddLiteral(
Steven Moreland4d12f9a2018-10-31 14:30:55 -0700805 StringPrintf("static const %s value(%s)", cppType.c_str(),
Steven Moreland860b1942018-08-16 14:59:28 -0700806 constant->ValueString(ConstantValueDecorator).c_str()));
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700807 getter->GetStatementBlock()->AddLiteral("return value");
808 decls.push_back(std::move(getter));
809 }
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700810
Jiyong Park75e1a742018-07-04 12:31:23 +0900811 // Implement the default impl class.
812 // onAsBinder returns nullptr as this interface is not associated with a
813 // real binder.
814 const string default_impl(ClassName(interface, ClassNames::DEFAULT_IMPL));
815 decls.emplace_back(
816 new LiteralDecl(StringPrintf("::android::IBinder* %s::onAsBinder() {\n"
817 " return nullptr;\n"
818 "}\n",
819 default_impl.c_str())));
820 // Each interface method by default returns UNKNOWN_TRANSACTION with is
821 // the same status that is returned by transact() when the method is
822 // not implemented in the server side. In other words, these default
823 // methods do nothing; they only exist to aid making a real default
824 // impl class without having to override all methods in an interface.
825 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900826 if (method->IsUserDefined()) {
827 std::ostringstream code;
828 code << "::android::binder::Status " << default_impl << "::" << method->GetName()
829 << BuildArgList(types, *method, true, true).ToString() << " {\n"
830 << " return ::android::binder::Status::fromStatusT(::android::UNKNOWN_TRANSACTION);\n"
831 << "}\n";
832 decls.emplace_back(new LiteralDecl(code.str()));
833 } else {
834 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
835 std::ostringstream code;
836 code << "int32_t " << default_impl << "::" << kGetInterfaceVersion << "() {\n"
837 << " return 0;\n"
838 << "}\n";
839 decls.emplace_back(new LiteralDecl(code.str()));
840 }
841 }
Jiyong Park75e1a742018-07-04 12:31:23 +0900842 }
843
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700844 return unique_ptr<Document>{new CppSource{
845 include_list,
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700846 NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700847}
848
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900849unique_ptr<Document> BuildClientHeader(const TypeNamespace& types, const AidlInterface& interface,
Jiyong Park309668e2018-07-28 16:55:44 +0900850 const Options& options) {
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700851 const string i_name = ClassName(interface, ClassNames::INTERFACE);
852 const string bp_name = ClassName(interface, ClassNames::CLIENT);
Casey Dahlina834dd42015-09-23 11:52:15 -0700853
Jiyong Parkb064cbb2018-11-06 02:47:18 +0900854 vector<string> includes = {kIBinderHeader, kIInterfaceHeader, "utils/Errors.h",
Jiyong Parkce50e262018-10-29 09:54:20 +0900855 HeaderFile(interface, ClassNames::INTERFACE, false)};
856
Christopher Wileyb23149d2015-10-14 13:52:21 -0700857 unique_ptr<ConstructorDecl> constructor{new ConstructorDecl{
858 bp_name,
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800859 ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
860 kImplVarName)},
Christopher Wileyb23149d2015-10-14 13:52:21 -0700861 ConstructorDecl::IS_EXPLICIT
862 }};
863 unique_ptr<ConstructorDecl> destructor{new ConstructorDecl{
864 "~" + bp_name,
865 ArgList{},
866 ConstructorDecl::IS_VIRTUAL | ConstructorDecl::IS_DEFAULT}};
Casey Dahlina834dd42015-09-23 11:52:15 -0700867
Christopher Wileyf944e792015-09-29 10:00:46 -0700868 vector<unique_ptr<Declaration>> publics;
Casey Dahlina834dd42015-09-23 11:52:15 -0700869 publics.push_back(std::move(constructor));
870 publics.push_back(std::move(destructor));
871
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700872 for (const auto& method: interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900873 if (method->IsUserDefined()) {
874 publics.push_back(BuildMethodDecl(*method, types, false));
875 } else {
876 publics.push_back(BuildMetaMethodDecl(*method, types, options, false));
877 }
Casey Dahlina834dd42015-09-23 11:52:15 -0700878 }
879
Jiyong Parkce50e262018-10-29 09:54:20 +0900880 if (options.GenLog()) {
Jiyong Parkb064cbb2018-11-06 02:47:18 +0900881 includes.emplace_back("chrono"); // for std::chrono::steady_clock
882 includes.emplace_back("functional"); // for std::function
883 includes.emplace_back("json/value.h");
Jiyong Parkce50e262018-10-29 09:54:20 +0900884 publics.emplace_back(
885 new LiteralDecl{"static std::function<void(const Json::Value&)> logFunc;\n"});
886 }
887
Jiyong Park309668e2018-07-28 16:55:44 +0900888 vector<unique_ptr<Declaration>> privates;
889
890 if (options.Version() > 0) {
891 privates.emplace_back(new LiteralDecl("int32_t cached_version_ = -1;\n"));
892 }
893
894 unique_ptr<ClassDecl> bp_class{new ClassDecl{
895 bp_name,
896 "::android::BpInterface<" + i_name + ">",
897 std::move(publics),
898 std::move(privates),
899 }};
Casey Dahlina834dd42015-09-23 11:52:15 -0700900
Jiyong Parkce50e262018-10-29 09:54:20 +0900901 return unique_ptr<Document>{
Jiyong Parkb064cbb2018-11-06 02:47:18 +0900902 new CppHeader{BuildHeaderGuard(interface, ClassNames::CLIENT), includes,
Jiyong Parkce50e262018-10-29 09:54:20 +0900903 NestInNamespaces(std::move(bp_class), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700904}
905
Christopher Wileyf59c4992015-10-08 13:12:44 -0700906unique_ptr<Document> BuildServerHeader(const TypeNamespace& /* types */,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900907 const AidlInterface& interface, const Options&) {
Christopher Wileyfd51d602015-10-14 13:04:48 -0700908 const string i_name = ClassName(interface, ClassNames::INTERFACE);
909 const string bn_name = ClassName(interface, ClassNames::SERVER);
Casey Dahlin082f1d12015-09-21 14:06:25 -0700910
Christopher Wileyfd51d602015-10-14 13:04:48 -0700911 unique_ptr<Declaration> on_transact{new MethodDecl{
Christopher Wileyade4b452015-10-10 11:06:03 -0700912 kAndroidStatusLiteral, "onTransact",
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800913 ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
914 StringPrintf("const %s& %s", kAndroidParcelLiteral,
915 kDataVarName),
916 StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
Jiyong Park8533bd02018-10-29 21:31:18 +0900917 StringPrintf("uint32_t %s", kFlagsVarName)}},
Christopher Wileyfd51d602015-10-14 13:04:48 -0700918 MethodDecl::IS_OVERRIDE
919 }};
Casey Dahlin082f1d12015-09-21 14:06:25 -0700920
Christopher Wileyf944e792015-09-29 10:00:46 -0700921 std::vector<unique_ptr<Declaration>> publics;
Casey Dahlinb7d0f7f2015-09-22 17:21:08 -0700922 publics.push_back(std::move(on_transact));
923
Christopher Wileyf944e792015-09-29 10:00:46 -0700924 unique_ptr<ClassDecl> bn_class{
925 new ClassDecl{bn_name,
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800926 "::android::BnInterface<" + i_name + ">",
Christopher Wileyf944e792015-09-29 10:00:46 -0700927 std::move(publics),
928 {}
Casey Dahlinb7d0f7f2015-09-22 17:21:08 -0700929 }};
Casey Dahlin082f1d12015-09-21 14:06:25 -0700930
Christopher Wiley0c732db2015-09-29 14:36:44 -0700931 return unique_ptr<Document>{new CppHeader{
Christopher Wileyfd51d602015-10-14 13:04:48 -0700932 BuildHeaderGuard(interface, ClassNames::SERVER),
Christopher Wiley0c732db2015-09-29 14:36:44 -0700933 {"binder/IInterface.h",
Christopher Wiley054afbd2015-10-16 17:08:43 -0700934 HeaderFile(interface, ClassNames::INTERFACE, false)},
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700935 NestInNamespaces(std::move(bn_class), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700936}
937
Christopher Wileye3550c62015-09-29 13:26:10 -0700938unique_ptr<Document> BuildInterfaceHeader(const TypeNamespace& types,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900939 const AidlInterface& interface, const Options& options) {
Jiyong Park75e1a742018-07-04 12:31:23 +0900940 set<string> includes = {kIBinderHeader, kIInterfaceHeader, kStatusHeader, kStrongPointerHeader};
Casey Dahlince776cf2015-10-15 18:45:54 -0700941
942 for (const auto& method : interface.GetMethods()) {
943 for (const auto& argument : method->GetArguments()) {
Casey Dahlina2f77c42015-12-01 18:26:02 -0800944 const Type* type = argument->GetType().GetLanguageType<Type>();
945 type->GetHeaders(&includes);
Casey Dahlince776cf2015-10-15 18:45:54 -0700946 }
947
Casey Dahlina2f77c42015-12-01 18:26:02 -0800948 const Type* return_type = method->GetType().GetLanguageType<Type>();
Jiyong Parkb034bf02018-07-30 17:44:33 +0900949 if (return_type != nullptr) {
950 return_type->GetHeaders(&includes);
951 }
Casey Dahlince776cf2015-10-15 18:45:54 -0700952 }
953
Jiyong Park75e1a742018-07-04 12:31:23 +0900954 const string i_name = ClassName(interface, ClassNames::INTERFACE);
955 unique_ptr<ClassDecl> if_class{new ClassDecl{i_name, "::android::IInterface"}};
Christopher Wiley11a9d792016-02-24 17:20:33 -0800956 if_class->AddPublic(unique_ptr<Declaration>{new MacroDecl{
Christopher Wileyade4b452015-10-10 11:06:03 -0700957 "DECLARE_META_INTERFACE",
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700958 ArgList{vector<string>{ClassName(interface, ClassNames::BASE)}}}});
Christopher Wiley0c732db2015-09-29 14:36:44 -0700959
Jiyong Park309668e2018-07-28 16:55:44 +0900960 if (options.Version() > 0) {
961 std::ostringstream code;
962 code << "const int32_t VERSION = " << options.Version() << ";\n";
963
964 if_class->AddPublic(unique_ptr<Declaration>(new LiteralDecl(code.str())));
965 }
966
Steven Moreland693640b2018-07-19 13:46:27 -0700967 std::vector<std::unique_ptr<Declaration>> string_constants;
968 unique_ptr<Enum> int_constant_enum{new Enum{"", "int32_t"}};
969 for (const auto& constant : interface.GetConstantDeclarations()) {
970 const AidlConstantValue& value = constant->GetValue();
Casey Dahlind40e2fe2015-11-24 14:06:52 -0800971
Steven Moreland693640b2018-07-19 13:46:27 -0700972 switch (value.GetType()) {
973 case AidlConstantValue::Type::STRING: {
Steven Moreland4d12f9a2018-10-31 14:30:55 -0700974 std::string cppType = constant->GetType().GetLanguageType<Type>()->CppType();
975 unique_ptr<Declaration> getter(new MethodDecl("const " + cppType + "&", constant->GetName(),
976 {}, MethodDecl::IS_STATIC));
Steven Moreland693640b2018-07-19 13:46:27 -0700977 string_constants.push_back(std::move(getter));
978 break;
979 }
Steven Moreland25294322018-08-07 18:13:55 -0700980 case AidlConstantValue::Type::INTEGRAL:
981 case AidlConstantValue::Type::HEXIDECIMAL: {
Steven Moreland860b1942018-08-16 14:59:28 -0700982 int_constant_enum->AddValue(constant->GetName(),
983 constant->ValueString(ConstantValueDecorator));
Steven Moreland693640b2018-07-19 13:46:27 -0700984 break;
985 }
986 default: {
987 LOG(FATAL) << "Unrecognized constant type: " << static_cast<int>(value.GetType());
988 }
989 }
990 }
991 if (int_constant_enum->HasValues()) {
992 if_class->AddPublic(std::move(int_constant_enum));
993 }
994 if (!string_constants.empty()) {
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700995 includes.insert(kString16Header);
Steven Moreland693640b2018-07-19 13:46:27 -0700996
997 for (auto& string_constant : string_constants) {
998 if_class->AddPublic(std::move(string_constant));
999 }
Christopher Wiley69b44cf2016-05-03 13:43:33 -07001000 }
Martijn Coenenf1b50782018-02-21 21:06:23 +01001001
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001002 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +01001003 includes.insert(kTraceHeader);
1004 }
1005
Christopher Wileyd6bdd8d2016-05-03 11:23:13 -07001006 if (!interface.GetMethods().empty()) {
1007 unique_ptr<Enum> call_enum{new Enum{"Call"}};
1008 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +09001009 if (method->IsUserDefined()) {
1010 // Each method gets an enum entry and pure virtual declaration.
1011 if_class->AddPublic(BuildMethodDecl(*method, types, true));
1012 call_enum->AddValue(
1013 UpperCase(method->GetName()),
1014 StringPrintf("::android::IBinder::FIRST_CALL_TRANSACTION + %d", method->GetId()));
1015 } else {
1016 if_class->AddPublic(BuildMetaMethodDecl(*method, types, options, true));
1017 call_enum->AddValue(UpperCase(method->GetName()), std::to_string(method->GetId()));
1018 }
Christopher Wileyd6bdd8d2016-05-03 11:23:13 -07001019 }
1020 if_class->AddPublic(std::move(call_enum));
Christopher Wiley0c732db2015-09-29 14:36:44 -07001021 }
Christopher Wiley0c732db2015-09-29 14:36:44 -07001022
Jiyong Park75e1a742018-07-04 12:31:23 +09001023 vector<unique_ptr<Declaration>> decls;
1024 decls.emplace_back(std::move(if_class));
1025
1026 // Base class for the default implementation.
1027 vector<string> method_decls;
1028 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +09001029 if (method->IsUserDefined()) {
1030 method_decls.emplace_back(BuildMethodDecl(*method, types, false)->ToString());
1031 } else {
1032 method_decls.emplace_back(BuildMetaMethodDecl(*method, types, options, false)->ToString());
1033 }
Jiyong Park75e1a742018-07-04 12:31:23 +09001034 }
Jiyong Park309668e2018-07-28 16:55:44 +09001035
Jiyong Park75e1a742018-07-04 12:31:23 +09001036 decls.emplace_back(new LiteralDecl(
1037 android::base::StringPrintf("class %s : public %s {\n"
1038 "public:\n"
1039 " ::android::IBinder* onAsBinder() override;\n"
1040 " %s\n"
1041 "};\n",
1042 ClassName(interface, ClassNames::DEFAULT_IMPL).c_str(),
1043 i_name.c_str(), Join(method_decls, " ").c_str())));
1044
1045 return unique_ptr<Document>{
1046 new CppHeader{BuildHeaderGuard(interface, ClassNames::INTERFACE),
1047 vector<string>(includes.begin(), includes.end()),
1048 NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001049}
1050
Steven Moreland5557f1c2018-07-02 13:50:23 -07001051std::unique_ptr<Document> BuildParcelHeader(const TypeNamespace& /*types*/,
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001052 const AidlStructuredParcelable& parcel,
1053 const Options&) {
Steven Moreland5557f1c2018-07-02 13:50:23 -07001054 unique_ptr<ClassDecl> parcel_class{new ClassDecl{parcel.GetName(), "::android::Parcelable"}};
1055
1056 set<string> includes = {kStatusHeader, kParcelHeader};
1057 for (const auto& variable : parcel.GetFields()) {
1058 const Type* type = variable->GetType().GetLanguageType<Type>();
1059 type->GetHeaders(&includes);
1060 }
1061
1062 for (const auto& variable : parcel.GetFields()) {
1063 const Type* type = variable->GetType().GetLanguageType<Type>();
1064
Steven Moreland9ea10e32018-07-19 15:26:09 -07001065 std::ostringstream out;
1066 out << type->CppType().c_str() << " " << variable->GetName().c_str();
Steven Moreland25294322018-08-07 18:13:55 -07001067 if (variable->GetDefaultValue()) {
Steven Moreland860b1942018-08-16 14:59:28 -07001068 out << " = " << type->CppType().c_str() << "("
1069 << variable->ValueString(ConstantValueDecorator) << ")";
Steven Moreland9ea10e32018-07-19 15:26:09 -07001070 }
1071 out << ";\n";
1072
1073 parcel_class->AddPublic(std::unique_ptr<LiteralDecl>(new LiteralDecl(out.str())));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001074 }
1075
1076 unique_ptr<MethodDecl> read(new MethodDecl(kAndroidStatusLiteral, "readFromParcel",
Steven Morelandce39c532018-07-11 16:59:50 -07001077 ArgList("const ::android::Parcel* _aidl_parcel"),
Steven Moreland5557f1c2018-07-02 13:50:23 -07001078 MethodDecl::IS_OVERRIDE));
1079 parcel_class->AddPublic(std::move(read));
1080 unique_ptr<MethodDecl> write(new MethodDecl(kAndroidStatusLiteral, "writeToParcel",
Steven Morelandce39c532018-07-11 16:59:50 -07001081 ArgList("::android::Parcel* _aidl_parcel"),
Steven Moreland5557f1c2018-07-02 13:50:23 -07001082 MethodDecl::IS_OVERRIDE | MethodDecl::IS_CONST));
1083 parcel_class->AddPublic(std::move(write));
1084
1085 return unique_ptr<Document>{new CppHeader{
1086 BuildHeaderGuard(parcel, ClassNames::BASE), vector<string>(includes.begin(), includes.end()),
1087 NestInNamespaces(std::move(parcel_class), parcel.GetSplitPackage())}};
1088}
Steven Moreland1c41e972018-07-09 16:07:00 -07001089std::unique_ptr<Document> BuildParcelSource(const TypeNamespace& /*types*/,
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001090 const AidlStructuredParcelable& parcel,
1091 const Options&) {
Steven Moreland5557f1c2018-07-02 13:50:23 -07001092 unique_ptr<MethodImpl> read{new MethodImpl{kAndroidStatusLiteral, parcel.GetName(),
1093 "readFromParcel",
Steven Morelandce39c532018-07-11 16:59:50 -07001094 ArgList("const ::android::Parcel* _aidl_parcel")}};
Steven Moreland5557f1c2018-07-02 13:50:23 -07001095 StatementBlock* read_block = read->GetStatementBlock();
1096 read_block->AddLiteral(
1097 StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName, kAndroidStatusOk));
1098 for (const auto& variable : parcel.GetFields()) {
1099 string method = variable->GetType().GetLanguageType<Type>()->ReadFromParcelMethod();
1100
1101 read_block->AddStatement(new Assignment(
1102 kAndroidStatusVarName, new MethodCall(StringPrintf("_aidl_parcel->%s", method.c_str()),
1103 ArgList("&" + variable->GetName()))));
1104 read_block->AddStatement(ReturnOnStatusNotOk());
1105 }
1106 read_block->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
1107
Steven Morelandce39c532018-07-11 16:59:50 -07001108 unique_ptr<MethodImpl> write{
1109 new MethodImpl{kAndroidStatusLiteral, parcel.GetName(), "writeToParcel",
1110 ArgList("::android::Parcel* _aidl_parcel"), true /*const*/}};
Steven Moreland5557f1c2018-07-02 13:50:23 -07001111 StatementBlock* write_block = write->GetStatementBlock();
1112 write_block->AddLiteral(
1113 StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName, kAndroidStatusOk));
1114 for (const auto& variable : parcel.GetFields()) {
1115 string method = variable->GetType().GetLanguageType<Type>()->WriteToParcelMethod();
1116
1117 write_block->AddStatement(new Assignment(
1118 kAndroidStatusVarName, new MethodCall(StringPrintf("_aidl_parcel->%s", method.c_str()),
1119 ArgList(variable->GetName()))));
1120 write_block->AddStatement(ReturnOnStatusNotOk());
1121 }
1122 write_block->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
1123
1124 vector<unique_ptr<Declaration>> file_decls;
1125 file_decls.push_back(std::move(read));
1126 file_decls.push_back(std::move(write));
1127
1128 set<string> includes = {};
1129 parcel.GetLanguageType<Type>()->GetHeaders(&includes);
1130
1131 return unique_ptr<Document>{
1132 new CppSource{vector<string>(includes.begin(), includes.end()),
1133 NestInNamespaces(std::move(file_decls), parcel.GetSplitPackage())}};
1134}
1135
Jiyong Park74595c12018-07-23 15:22:50 +09001136bool WriteHeader(const Options& options, const TypeNamespace& types, const AidlInterface& interface,
1137 const IoDelegate& io_delegate, ClassNames header_type) {
Christopher Wiley054afbd2015-10-16 17:08:43 -07001138 unique_ptr<Document> header;
1139 switch (header_type) {
1140 case ClassNames::INTERFACE:
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001141 header = BuildInterfaceHeader(types, interface, options);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001142 break;
1143 case ClassNames::CLIENT:
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001144 header = BuildClientHeader(types, interface, options);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001145 break;
1146 case ClassNames::SERVER:
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001147 header = BuildServerHeader(types, interface, options);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001148 break;
1149 default:
1150 LOG(FATAL) << "aidl internal error";
1151 }
1152 if (!header) {
1153 LOG(ERROR) << "aidl internal error: Failed to generate header.";
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001154 return false;
1155 }
Christopher Wiley054afbd2015-10-16 17:08:43 -07001156
Jiyong Park05463732018-08-09 16:03:02 +09001157 const string header_path = options.OutputHeaderDir() + HeaderFile(interface, header_type);
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001158 unique_ptr<CodeWriter> code_writer(io_delegate.GetCodeWriter(header_path));
1159 header->Write(code_writer.get());
Christopher Wiley054afbd2015-10-16 17:08:43 -07001160
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001161 const bool success = code_writer->Close();
1162 if (!success) {
1163 io_delegate.RemovePath(header_path);
1164 }
1165
1166 return success;
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001167}
1168
Casey Dahlina834dd42015-09-23 11:52:15 -07001169} // namespace internals
1170
1171using namespace internals;
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001172
Jiyong Park74595c12018-07-23 15:22:50 +09001173bool GenerateCppInterface(const string& output_file, const Options& options,
1174 const TypeNamespace& types, const AidlInterface& interface,
1175 const IoDelegate& io_delegate) {
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001176 auto interface_src = BuildInterfaceSource(types, interface, options);
1177 auto client_src = BuildClientSource(types, interface, options);
1178 auto server_src = BuildServerSource(types, interface, options);
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001179
Christopher Wiley054afbd2015-10-16 17:08:43 -07001180 if (!interface_src || !client_src || !server_src) {
1181 return false;
1182 }
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001183
Christopher Wiley054afbd2015-10-16 17:08:43 -07001184 if (!WriteHeader(options, types, interface, io_delegate,
1185 ClassNames::INTERFACE) ||
1186 !WriteHeader(options, types, interface, io_delegate,
1187 ClassNames::CLIENT) ||
1188 !WriteHeader(options, types, interface, io_delegate,
1189 ClassNames::SERVER)) {
1190 return false;
1191 }
1192
Jiyong Park74595c12018-07-23 15:22:50 +09001193 unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(output_file);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001194 interface_src->Write(writer.get());
1195 client_src->Write(writer.get());
1196 server_src->Write(writer.get());
1197
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001198 const bool success = writer->Close();
1199 if (!success) {
Steven Morelandc209cab2018-08-27 01:25:21 -07001200 io_delegate.RemovePath(output_file);
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001201 }
1202
1203 return success;
Christopher Wileyeb1acc12015-09-16 11:25:13 -07001204}
1205
Jiyong Park74595c12018-07-23 15:22:50 +09001206bool GenerateCppParcel(const string& output_file, const Options& options,
1207 const cpp::TypeNamespace& types, const AidlStructuredParcelable& parcelable,
1208 const IoDelegate& io_delegate) {
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001209 auto header = BuildParcelHeader(types, parcelable, options);
1210 auto source = BuildParcelSource(types, parcelable, options);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001211
1212 if (!header || !source) {
1213 return false;
1214 }
1215
Jiyong Park05463732018-08-09 16:03:02 +09001216 const string header_path = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::BASE);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001217 unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1218 header->Write(header_writer.get());
1219 CHECK(header_writer->Close());
1220
Steven Moreland81079f92018-07-06 16:15:53 -07001221 // TODO(b/111362593): no unecessary files just to have consistent output with interfaces
Jiyong Park05463732018-08-09 16:03:02 +09001222 const string bp_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::CLIENT);
Steven Moreland81079f92018-07-06 16:15:53 -07001223 unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1224 bp_writer->Write("#error TODO(b/111362593) parcelables do not have bp classes");
1225 CHECK(bp_writer->Close());
Jiyong Park05463732018-08-09 16:03:02 +09001226 const string bn_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::SERVER);
Steven Moreland81079f92018-07-06 16:15:53 -07001227 unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1228 bn_writer->Write("#error TODO(b/111362593) parcelables do not have bn classes");
1229 CHECK(bn_writer->Close());
1230
Jiyong Park74595c12018-07-23 15:22:50 +09001231 unique_ptr<CodeWriter> source_writer = io_delegate.GetCodeWriter(output_file);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001232 source->Write(source_writer.get());
1233 CHECK(source_writer->Close());
1234
1235 return true;
1236}
1237
Jiyong Park74595c12018-07-23 15:22:50 +09001238bool GenerateCpp(const string& output_file, const Options& options, const TypeNamespace& types,
Steven Moreland5557f1c2018-07-02 13:50:23 -07001239 const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
1240 const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
1241 if (parcelable != nullptr) {
Jiyong Park74595c12018-07-23 15:22:50 +09001242 return GenerateCppParcel(output_file, options, types, *parcelable, io_delegate);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001243 }
1244
1245 const AidlInterface* interface = defined_type.AsInterface();
1246 if (interface != nullptr) {
Jiyong Park74595c12018-07-23 15:22:50 +09001247 return GenerateCppInterface(output_file, options, types, *interface, io_delegate);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001248 }
1249
1250 CHECK(false) << "Unrecognized type sent for cpp generation.";
1251 return false;
1252}
1253
Christopher Wileyf944e792015-09-29 10:00:46 -07001254} // namespace cpp
Christopher Wileyeb1acc12015-09-16 11:25:13 -07001255} // namespace aidl
Christopher Wileyf944e792015-09-29 10:00:46 -07001256} // namespace android