blob: 62d9af4e03be64b7bceded9dfdeb0b0dca933f2e [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";
Steven Morelanda57d0a62019-07-30 09:41:14 -070066const char kStabilityHeader[] = "binder/Stability.h";
Christopher Wiley433c8bb2015-11-12 14:20:46 -080067const char kStatusHeader[] = "binder/Status.h";
Christopher Wiley69b44cf2016-05-03 13:43:33 -070068const char kString16Header[] = "utils/String16.h";
Martijn Coenenf1b50782018-02-21 21:06:23 +010069const char kTraceHeader[] = "utils/Trace.h";
Casey Dahlin389781f2015-10-22 13:13:21 -070070const char kStrongPointerHeader[] = "utils/StrongPointer.h";
Jiyong Park75e1a742018-07-04 12:31:23 +090071const char kAndroidBaseMacrosHeader[] = "android-base/macros.h";
Casey Dahlin082f1d12015-09-21 14:06:25 -070072
Christopher Wiley0eb903e2015-10-20 17:07:08 -070073unique_ptr<AstNode> BreakOnStatusNotOk() {
74 IfStatement* ret = new IfStatement(new Comparison(
Casey Dahlinb8d9e882015-11-24 10:57:23 -080075 new LiteralExpression(kAndroidStatusVarName), "!=",
76 new LiteralExpression(kAndroidStatusOk)));
Christopher Wiley0eb903e2015-10-20 17:07:08 -070077 ret->OnTrue()->AddLiteral("break");
78 return unique_ptr<AstNode>(ret);
79}
80
Christopher Wiley433c8bb2015-11-12 14:20:46 -080081unique_ptr<AstNode> GotoErrorOnBadStatus() {
82 IfStatement* ret = new IfStatement(new Comparison(
Casey Dahlinb8d9e882015-11-24 10:57:23 -080083 new LiteralExpression(kAndroidStatusVarName), "!=",
84 new LiteralExpression(kAndroidStatusOk)));
85 ret->OnTrue()->AddLiteral(StringPrintf("goto %s", kErrorLabel));
Christopher Wiley433c8bb2015-11-12 14:20:46 -080086 return unique_ptr<AstNode>(ret);
87}
88
Steven Moreland5557f1c2018-07-02 13:50:23 -070089unique_ptr<AstNode> ReturnOnStatusNotOk() {
90 IfStatement* ret = new IfStatement(new Comparison(new LiteralExpression(kAndroidStatusVarName),
91 "!=", new LiteralExpression(kAndroidStatusOk)));
92 ret->OnTrue()->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
93 return unique_ptr<AstNode>(ret);
94}
95
Jeongik Cha1a7ab642019-07-29 17:31:02 +090096ArgList BuildArgList(const AidlTypenames& typenames, const AidlMethod& method, bool for_declaration,
Jiyong Park75e1a742018-07-04 12:31:23 +090097 bool type_name_only = false) {
Christopher Wileyad339272015-10-05 19:11:58 -070098 // Build up the argument list for the server method call.
99 vector<string> method_arguments;
100 for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
101 string literal;
102 if (for_declaration) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900103 // Method declarations need typenames, pointers to out params, and variable
Christopher Wileyad339272015-10-05 19:11:58 -0700104 // names that match the .aidl specification.
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900105 literal = CppNameOf(a->GetType(), typenames);
Casey Dahlinb0966612015-10-19 16:35:26 -0700106
Christopher Wileyb8e49a42015-10-27 12:55:18 -0700107 if (a->IsOut()) {
108 literal = literal + "*";
109 } else {
110 // We pass in parameters that are not primitives by const reference.
111 // Arrays of primitives are not primitives.
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900112 if (!AidlTypenames::IsPrimitiveTypename(a->GetType().GetName()) || a->GetType().IsArray()) {
Christopher Wileyb8e49a42015-10-27 12:55:18 -0700113 literal = "const " + literal + "&";
114 }
115 }
Jiyong Park75e1a742018-07-04 12:31:23 +0900116 if (!type_name_only) {
117 literal += " " + a->GetName();
118 }
Christopher Wileyad339272015-10-05 19:11:58 -0700119 } else {
120 if (a->IsOut()) { literal = "&"; }
121 literal += BuildVarName(*a);
122 }
123 method_arguments.push_back(literal);
124 }
125
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900126 if (method.GetType().GetName() != "void") {
Christopher Wileyade4b452015-10-10 11:06:03 -0700127 string literal;
Christopher Wileyad339272015-10-05 19:11:58 -0700128 if (for_declaration) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900129 literal = StringPrintf("%s* %s", CppNameOf(method.GetType(), typenames).c_str(),
Jiyong Park75e1a742018-07-04 12:31:23 +0900130 type_name_only ? "" : kReturnVarName);
Christopher Wileyad339272015-10-05 19:11:58 -0700131 } else {
Christopher Wileyade4b452015-10-10 11:06:03 -0700132 literal = string{"&"} + kReturnVarName;
Christopher Wileyad339272015-10-05 19:11:58 -0700133 }
Christopher Wileyade4b452015-10-10 11:06:03 -0700134 method_arguments.push_back(literal);
Christopher Wileyad339272015-10-05 19:11:58 -0700135 }
136
Christopher Wileyade4b452015-10-10 11:06:03 -0700137 return ArgList(method_arguments);
Casey Dahlina834dd42015-09-23 11:52:15 -0700138}
139
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900140unique_ptr<Declaration> BuildMethodDecl(const AidlMethod& method, const AidlTypenames& typenames,
Christopher Wiley0c732db2015-09-29 14:36:44 -0700141 bool for_interface) {
Christopher Wiley0c732db2015-09-29 14:36:44 -0700142 uint32_t modifiers = 0;
143 if (for_interface) {
144 modifiers |= MethodDecl::IS_VIRTUAL;
145 modifiers |= MethodDecl::IS_PURE_VIRTUAL;
146 } else {
147 modifiers |= MethodDecl::IS_OVERRIDE;
148 }
149
150 return unique_ptr<Declaration>{
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900151 new MethodDecl{kBinderStatusLiteral, method.GetName(),
152 BuildArgList(typenames, method, true /* for method decl */), modifiers}};
Christopher Wiley0c732db2015-09-29 14:36:44 -0700153}
154
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900155unique_ptr<Declaration> BuildMetaMethodDecl(const AidlMethod& method, const AidlTypenames&,
Jiyong Park309668e2018-07-28 16:55:44 +0900156 const Options& options, bool for_interface) {
157 CHECK(!method.IsUserDefined());
158 if (method.GetName() == kGetInterfaceVersion && options.Version()) {
159 std::ostringstream code;
160 if (for_interface) {
161 code << "virtual ";
162 }
163 code << "int32_t " << kGetInterfaceVersion << "()";
164 if (for_interface) {
165 code << " = 0;\n";
166 } else {
167 code << " override;\n";
168 }
169 return unique_ptr<Declaration>(new LiteralDecl(code.str()));
170 }
171 return nullptr;
172}
173
Steven Morelandf3da0892018-10-05 14:52:01 -0700174std::vector<unique_ptr<Declaration>> NestInNamespaces(vector<unique_ptr<Declaration>> decls,
175 const vector<string>& package) {
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700176 auto it = package.crbegin(); // Iterate over the namespaces inner to outer
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700177 for (; it != package.crend(); ++it) {
Steven Morelandf3da0892018-10-05 14:52:01 -0700178 vector<unique_ptr<Declaration>> inner;
179 inner.emplace_back(unique_ptr<Declaration>{new CppNamespace{*it, std::move(decls)}});
180
181 decls = std::move(inner);
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700182 }
Steven Morelandf3da0892018-10-05 14:52:01 -0700183 return decls;
Christopher Wiley0c732db2015-09-29 14:36:44 -0700184}
185
Steven Morelandf3da0892018-10-05 14:52:01 -0700186std::vector<unique_ptr<Declaration>> NestInNamespaces(unique_ptr<Declaration> decl,
187 const vector<string>& package) {
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700188 vector<unique_ptr<Declaration>> decls;
189 decls.push_back(std::move(decl));
190 return NestInNamespaces(std::move(decls), package);
Christopher Wiley36570f42015-10-08 17:20:11 -0700191}
192
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900193bool DeclareLocalVariable(const AidlArgument& a, StatementBlock* b,
194 const AidlTypenames& typenamespaces) {
195 string type = CppNameOf(a.GetType(), typenamespaces);
Casey Dahlinb0966612015-10-19 16:35:26 -0700196
197 b->AddLiteral(type + " " + BuildVarName(a));
Christopher Wileyad339272015-10-05 19:11:58 -0700198 return true;
199}
200
Steven Moreland5557f1c2018-07-02 13:50:23 -0700201string BuildHeaderGuard(const AidlDefinedType& defined_type, ClassNames header_type) {
202 string class_name = ClassName(defined_type, header_type);
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700203 for (size_t i = 1; i < class_name.size(); ++i) {
204 if (isupper(class_name[i])) {
205 class_name.insert(i, "_");
206 ++i;
207 }
208 }
Steven Moreland5557f1c2018-07-02 13:50:23 -0700209 string ret = StringPrintf("AIDL_GENERATED_%s_%s_H_", defined_type.GetPackage().c_str(),
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700210 class_name.c_str());
211 for (char& c : ret) {
212 if (c == '.') {
213 c = '_';
214 }
215 c = toupper(c);
216 }
217 return ret;
218}
Christopher Wiley36570f42015-10-08 17:20:11 -0700219
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900220unique_ptr<Declaration> DefineClientTransaction(const AidlTypenames& typenames,
Christopher Wiley36570f42015-10-08 17:20:11 -0700221 const AidlInterface& interface,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900222 const AidlMethod& method, const Options& options) {
Christopher Wiley36570f42015-10-08 17:20:11 -0700223 const string i_name = ClassName(interface, ClassNames::INTERFACE);
224 const string bp_name = ClassName(interface, ClassNames::CLIENT);
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900225 unique_ptr<MethodImpl> ret{
226 new MethodImpl{kBinderStatusLiteral, bp_name, method.GetName(),
227 ArgList{BuildArgList(typenames, method, true /* for method decl */)}}};
Christopher Wiley36570f42015-10-08 17:20:11 -0700228 StatementBlock* b = ret->GetStatementBlock();
229
230 // Declare parcels to hold our query and the response.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800231 b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kDataVarName));
Christopher Wiley1227d612015-10-26 16:59:20 -0700232 // Even if we're oneway, the transact method still takes a parcel.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800233 b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kReplyVarName));
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700234
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800235 // Declare the status_t variable we need for error handling.
Christopher Wiley10957122015-12-04 14:35:38 -0800236 b->AddLiteral(StringPrintf("%s %s = %s", kAndroidStatusLiteral,
237 kAndroidStatusVarName,
238 kAndroidStatusOk));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800239 // We unconditionally return a Status object.
240 b->AddLiteral(StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName));
Christopher Wiley36570f42015-10-08 17:20:11 -0700241
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900242 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100243 b->AddLiteral(
244 StringPrintf("ScopedTrace %s(ATRACE_TAG_AIDL, \"%s::%s::cppClient\")",
245 kTraceVarName, interface.GetName().c_str(), method.GetName().c_str()));
246 }
247
Jiyong Parkce50e262018-10-29 09:54:20 +0900248 if (options.GenLog()) {
Jeongik Cha37e2ad52019-04-18 13:44:26 +0900249 b->AddLiteral(GenLogBeforeExecute(bp_name, method, false /* isServer */, false /* isNdk */),
250 false /* no semicolon */);
Jiyong Parkce50e262018-10-29 09:54:20 +0900251 }
252
Christopher Wiley8993cb52015-10-21 09:53:24 -0700253 // Add the name of the interface we're hoping to call.
254 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800255 kAndroidStatusVarName,
256 new MethodCall(StringPrintf("%s.writeInterfaceToken",
257 kDataVarName),
258 "getInterfaceDescriptor()")));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800259 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley8993cb52015-10-21 09:53:24 -0700260
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700261 for (const auto& a: method.GetArguments()) {
Christopher Wiley36570f42015-10-08 17:20:11 -0700262 string var_name = ((a->IsOut()) ? "*" : "") + a->GetName();
Daniel Norman85aed542019-08-21 12:01:14 -0700263 var_name = ParcelWriteCastOf(a->GetType(), typenames, var_name);
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700264
265 if (a->IsIn()) {
266 // Serialization looks roughly like:
267 // _aidl_ret_status = _aidl_data.WriteInt32(in_param_name);
268 // if (_aidl_ret_status != ::android::OK) { goto error; }
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900269 const string& method = ParcelWriteMethodOf(a->GetType(), typenames);
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700270 b->AddStatement(new Assignment(
271 kAndroidStatusVarName,
Daniel Norman85aed542019-08-21 12:01:14 -0700272 new MethodCall(StringPrintf("%s.%s", kDataVarName, method.c_str()), var_name)));
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700273 b->AddStatement(GotoErrorOnBadStatus());
274 } else if (a->IsOut() && a->GetType().IsArray()) {
275 // Special case, the length of the out array is written into the parcel.
276 // _aidl_ret_status = _aidl_data.writeVectorSize(&out_param_name);
277 // if (_aidl_ret_status != ::android::OK) { goto error; }
278 b->AddStatement(new Assignment(
279 kAndroidStatusVarName,
Daniel Norman85aed542019-08-21 12:01:14 -0700280 new MethodCall(StringPrintf("%s.writeVectorSize", kDataVarName), var_name)));
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700281 b->AddStatement(GotoErrorOnBadStatus());
282 }
Christopher Wiley36570f42015-10-08 17:20:11 -0700283 }
284
285 // Invoke the transaction on the remote binder and confirm status.
Jeongik Chab5d962f2018-11-17 09:12:28 +0900286 string transaction_code = GetTransactionIdFor(method);
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700287
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800288 vector<string> args = {transaction_code, kDataVarName,
289 StringPrintf("&%s", kReplyVarName)};
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700290
Steven Morelandacd53472018-12-14 10:17:26 -0800291 if (method.IsOneway()) {
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800292 args.push_back("::android::IBinder::FLAG_ONEWAY");
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700293 }
294
Christopher Wiley36570f42015-10-08 17:20:11 -0700295 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800296 kAndroidStatusVarName,
Christopher Wiley36570f42015-10-08 17:20:11 -0700297 new MethodCall("remote()->transact",
Casey Dahlin0dd08af2015-10-20 18:45:50 -0700298 ArgList(args))));
Jiyong Park75e1a742018-07-04 12:31:23 +0900299
300 // If the method is not implemented in the remote side, try to call the
301 // default implementation, if provided.
302 vector<string> arg_names;
303 for (const auto& a : method.GetArguments()) {
304 arg_names.emplace_back(a->GetName());
305 }
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900306 if (method.GetType().GetName() != "void") {
Jiyong Park75e1a742018-07-04 12:31:23 +0900307 arg_names.emplace_back(kReturnVarName);
308 }
309 b->AddLiteral(StringPrintf("if (UNLIKELY(_aidl_ret_status == ::android::UNKNOWN_TRANSACTION && "
310 "%s::getDefaultImpl())) {\n"
311 " return %s::getDefaultImpl()->%s(%s);\n"
312 "}\n",
313 i_name.c_str(), i_name.c_str(), method.GetName().c_str(),
314 Join(arg_names, ", ").c_str()),
315 false /* no semicolon */);
316
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800317 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley36570f42015-10-08 17:20:11 -0700318
Steven Morelandacd53472018-12-14 10:17:26 -0800319 if (!method.IsOneway()) {
Christopher Wiley1227d612015-10-26 16:59:20 -0700320 // Strip off the exception header and fail if we see a remote exception.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800321 // _aidl_ret_status = _aidl_status.readFromParcel(_aidl_reply);
322 // if (_aidl_ret_status != ::android::OK) { goto error; }
323 // if (!_aidl_status.isOk()) { return _aidl_ret_status; }
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800324 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800325 kAndroidStatusVarName,
326 StringPrintf("%s.readFromParcel(%s)", kStatusVarName, kReplyVarName)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800327 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley1227d612015-10-26 16:59:20 -0700328 IfStatement* exception_check = new IfStatement(
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800329 new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
Christopher Wiley1227d612015-10-26 16:59:20 -0700330 b->AddStatement(exception_check);
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800331 exception_check->OnTrue()->AddLiteral(
332 StringPrintf("return %s", kStatusVarName));
Christopher Wiley1227d612015-10-26 16:59:20 -0700333 }
334
335 // Type checking should guarantee that nothing below emits code until "return
336 // status" if we are a oneway method, so no more fear of accessing reply.
Christopher Wiley2aaeda82015-10-19 15:16:49 -0700337
Christopher Wiley36570f42015-10-08 17:20:11 -0700338 // If the method is expected to return something, read it first by convention.
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900339 if (method.GetType().GetName() != "void") {
340 const string& method_call = ParcelReadMethodOf(method.GetType(), typenames);
Christopher Wiley36570f42015-10-08 17:20:11 -0700341 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800342 kAndroidStatusVarName,
Daniel Norman85aed542019-08-21 12:01:14 -0700343 new MethodCall(StringPrintf("%s.%s", kReplyVarName, method_call.c_str()),
344 ParcelReadCastOf(method.GetType(), typenames, kReturnVarName))));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800345 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley36570f42015-10-08 17:20:11 -0700346 }
347
348 for (const AidlArgument* a : method.GetOutArguments()) {
349 // Deserialization looks roughly like:
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800350 // _aidl_ret_status = _aidl_reply.ReadInt32(out_param_name);
351 // if (_aidl_status != ::android::OK) { goto _aidl_error; }
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900352 string method = ParcelReadMethodOf(a->GetType(), typenames);
Casey Dahlinb0966612015-10-19 16:35:26 -0700353
Daniel Norman85aed542019-08-21 12:01:14 -0700354 b->AddStatement(
355 new Assignment(kAndroidStatusVarName,
356 new MethodCall(StringPrintf("%s.%s", kReplyVarName, method.c_str()),
357 ParcelReadCastOf(a->GetType(), typenames, a->GetName()))));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800358 b->AddStatement(GotoErrorOnBadStatus());
Christopher Wiley36570f42015-10-08 17:20:11 -0700359 }
360
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800361 // If we've gotten to here, one of two things is true:
362 // 1) We've read some bad status_t
363 // 2) We've only read status_t == OK and there was no exception in the
364 // response.
365 // In both cases, we're free to set Status from the status_t and return.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800366 b->AddLiteral(StringPrintf("%s:\n", kErrorLabel), false /* no semicolon */);
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800367 b->AddLiteral(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800368 StringPrintf("%s.setFromStatusT(%s)", kStatusVarName,
369 kAndroidStatusVarName));
Martijn Coenenf1b50782018-02-21 21:06:23 +0100370
Jiyong Parkce50e262018-10-29 09:54:20 +0900371 if (options.GenLog()) {
Jeongik Cha37e2ad52019-04-18 13:44:26 +0900372 b->AddLiteral(GenLogAfterExecute(bp_name, interface, method, kStatusVarName, kReturnVarName,
373 false /* isServer */, false /* isNdk */),
Jeongik Cha46375122018-12-21 18:41:21 +0900374 false /* no semicolon */);
Jiyong Parkce50e262018-10-29 09:54:20 +0900375 }
376
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800377 b->AddLiteral(StringPrintf("return %s", kStatusVarName));
Christopher Wiley36570f42015-10-08 17:20:11 -0700378
379 return unique_ptr<Declaration>(ret.release());
380}
381
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900382unique_ptr<Declaration> DefineClientMetaTransaction(const AidlTypenames& /* typenames */,
Jiyong Park309668e2018-07-28 16:55:44 +0900383 const AidlInterface& interface,
384 const AidlMethod& method,
385 const Options& options) {
386 CHECK(!method.IsUserDefined());
387 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
388 const string iface = ClassName(interface, ClassNames::INTERFACE);
389 const string proxy = ClassName(interface, ClassNames::CLIENT);
390 // Note: race condition can happen here, but no locking is required
391 // because 1) writing an interger is atomic and 2) this transaction
392 // will always return the same value, i.e., competing threads will
393 // give write the same value to cached_version_.
394 std::ostringstream code;
395 code << "int32_t " << proxy << "::" << kGetInterfaceVersion << "() {\n"
Jiyong Park965c5b92018-11-21 13:37:15 +0900396 << " if (cached_version_ == -1) {\n"
Jiyong Park309668e2018-07-28 16:55:44 +0900397 << " ::android::Parcel data;\n"
398 << " ::android::Parcel reply;\n"
Jiyong Park965c5b92018-11-21 13:37:15 +0900399 << " data.writeInterfaceToken(getInterfaceDescriptor());\n"
Jeongik Chab5d962f2018-11-17 09:12:28 +0900400 << " ::android::status_t err = remote()->transact(" << GetTransactionIdFor(method)
401 << ", data, &reply);\n"
Jiyong Park309668e2018-07-28 16:55:44 +0900402 << " if (err == ::android::OK) {\n"
Jeongik Chaf1470e22019-05-20 18:45:05 +0900403 << " ::android::binder::Status _aidl_status;\n"
404 << " err = _aidl_status.readFromParcel(reply);\n"
405 << " if (err == ::android::OK && _aidl_status.isOk()) {\n"
406 << " cached_version_ = reply.readInt32();\n"
407 << " }\n"
Jiyong Park309668e2018-07-28 16:55:44 +0900408 << " }\n"
409 << " }\n"
410 << " return cached_version_;\n"
411 << "}\n";
412 return unique_ptr<Declaration>(new LiteralDecl(code.str()));
413 }
414 return nullptr;
415}
416
Christopher Wiley36570f42015-10-08 17:20:11 -0700417} // namespace
418
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900419unique_ptr<Document> BuildClientSource(const AidlTypenames& typenames,
420 const AidlInterface& interface, const Options& options) {
Christopher Wiley054afbd2015-10-16 17:08:43 -0700421 vector<string> include_list = {
422 HeaderFile(interface, ClassNames::CLIENT, false),
Jiyong Park75e1a742018-07-04 12:31:23 +0900423 kParcelHeader,
424 kAndroidBaseMacrosHeader
Christopher Wiley054afbd2015-10-16 17:08:43 -0700425 };
Jiyong Parkce50e262018-10-29 09:54:20 +0900426 if (options.GenLog()) {
427 include_list.emplace_back("chrono");
428 include_list.emplace_back("functional");
429 include_list.emplace_back("json/value.h");
Jiyong Parkce50e262018-10-29 09:54:20 +0900430 }
Christopher Wiley36570f42015-10-08 17:20:11 -0700431 vector<unique_ptr<Declaration>> file_decls;
432
433 // The constructor just passes the IBinder instance up to the super
434 // class.
Christopher Wiley1db03482015-10-22 11:42:02 -0700435 const string i_name = ClassName(interface, ClassNames::INTERFACE);
Christopher Wiley36570f42015-10-08 17:20:11 -0700436 file_decls.push_back(unique_ptr<Declaration>{new ConstructorImpl{
Christopher Wiley054afbd2015-10-16 17:08:43 -0700437 ClassName(interface, ClassNames::CLIENT),
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800438 ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
439 kImplVarName)},
440 { "BpInterface<" + i_name + ">(" + kImplVarName + ")" }}});
Christopher Wiley36570f42015-10-08 17:20:11 -0700441
Jiyong Parkce50e262018-10-29 09:54:20 +0900442 if (options.GenLog()) {
443 string code;
444 ClassName(interface, ClassNames::CLIENT);
445 CodeWriterPtr writer = CodeWriter::ForString(&code);
446 (*writer) << "std::function<void(const Json::Value&)> "
447 << ClassName(interface, ClassNames::CLIENT) << "::logFunc;\n";
448 writer->Close();
449 file_decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
450 }
451
Christopher Wiley36570f42015-10-08 17:20:11 -0700452 // Clients define a method per transaction.
453 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900454 unique_ptr<Declaration> m;
455 if (method->IsUserDefined()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900456 m = DefineClientTransaction(typenames, interface, *method, options);
Jiyong Park309668e2018-07-28 16:55:44 +0900457 } else {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900458 m = DefineClientMetaTransaction(typenames, interface, *method, options);
Jiyong Park309668e2018-07-28 16:55:44 +0900459 }
Christopher Wiley36570f42015-10-08 17:20:11 -0700460 if (!m) { return nullptr; }
461 file_decls.push_back(std::move(m));
462 }
463 return unique_ptr<Document>{new CppSource{
464 include_list,
Christopher Wileyb656a3b2015-10-16 11:11:09 -0700465 NestInNamespaces(std::move(file_decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700466}
467
Christopher Wileyad339272015-10-05 19:11:58 -0700468namespace {
469
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900470bool HandleServerTransaction(const AidlTypenames& typenames, const AidlInterface& interface,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900471 const AidlMethod& method, const Options& options, StatementBlock* b) {
Christopher Wileyad339272015-10-05 19:11:58 -0700472 // Declare all the parameters now. In the common case, we expect no errors
473 // in serialization.
474 for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900475 if (!DeclareLocalVariable(*a, b, typenames)) {
Steven Moreland1c41e972018-07-09 16:07:00 -0700476 return false;
477 }
Christopher Wileyad339272015-10-05 19:11:58 -0700478 }
479
480 // Declare a variable to hold the return value.
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900481 if (method.GetType().GetName() != "void") {
482 string type = CppNameOf(method.GetType(), typenames);
483 b->AddLiteral(StringPrintf("%s %s", type.c_str(), kReturnVarName));
Christopher Wileyad339272015-10-05 19:11:58 -0700484 }
485
Christopher Wiley8993cb52015-10-21 09:53:24 -0700486 // Check that the client is calling the correct interface.
487 IfStatement* interface_check = new IfStatement(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800488 new MethodCall(StringPrintf("%s.checkInterface",
489 kDataVarName), "this"),
Christopher Wiley8993cb52015-10-21 09:53:24 -0700490 true /* invert the check */);
491 b->AddStatement(interface_check);
492 interface_check->OnTrue()->AddStatement(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800493 new Assignment(kAndroidStatusVarName, "::android::BAD_TYPE"));
Christopher Wiley8993cb52015-10-21 09:53:24 -0700494 interface_check->OnTrue()->AddLiteral("break");
495
Christopher Wileyad339272015-10-05 19:11:58 -0700496 // Deserialize each "in" parameter to the transaction.
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700497 for (const auto& a: method.GetArguments()) {
Christopher Wileyad339272015-10-05 19:11:58 -0700498 // Deserialization looks roughly like:
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800499 // _aidl_ret_status = _aidl_data.ReadInt32(&in_param_name);
500 // if (_aidl_ret_status != ::android::OK) { break; }
Daniel Norman85aed542019-08-21 12:01:14 -0700501 const string& var_name = ParcelReadCastOf(a->GetType(), typenames, "&" + BuildVarName(*a));
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700502 if (a->IsIn()) {
Daniel Norman85aed542019-08-21 12:01:14 -0700503 const string& readMethod = ParcelReadMethodOf(a->GetType(), typenames);
504 b->AddStatement(
505 new Assignment{kAndroidStatusVarName,
506 new MethodCall{string(kDataVarName) + "." + readMethod, var_name}});
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700507 b->AddStatement(BreakOnStatusNotOk());
508 } else if (a->IsOut() && a->GetType().IsArray()) {
509 // Special case, the length of the out array is written into the parcel.
510 // _aidl_ret_status = _aidl_data.resizeOutVector(&out_param_name);
511 // if (_aidl_ret_status != ::android::OK) { break; }
Daniel Norman85aed542019-08-21 12:01:14 -0700512 b->AddStatement(
513 new Assignment{kAndroidStatusVarName,
514 new MethodCall{string(kDataVarName) + ".resizeOutVector", var_name}});
Christopher Wiley74b7bf12016-08-19 11:06:32 -0700515 b->AddStatement(BreakOnStatusNotOk());
516 }
Christopher Wileyad339272015-10-05 19:11:58 -0700517 }
518
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900519 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100520 b->AddStatement(new Statement(new MethodCall("atrace_begin",
521 ArgList{{"ATRACE_TAG_AIDL",
522 StringPrintf("\"%s::%s::cppServer\"",
523 interface.GetName().c_str(),
524 method.GetName().c_str())}})));
525 }
Jeongik Cha46375122018-12-21 18:41:21 +0900526 const string bn_name = ClassName(interface, ClassNames::SERVER);
527 if (options.GenLog()) {
Jeongik Cha37e2ad52019-04-18 13:44:26 +0900528 b->AddLiteral(GenLogBeforeExecute(bn_name, method, true /* isServer */, false /* isNdk */),
529 false);
Jeongik Cha46375122018-12-21 18:41:21 +0900530 }
Christopher Wileyad339272015-10-05 19:11:58 -0700531 // Call the actual method. This is implemented by the subclass.
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800532 vector<unique_ptr<AstNode>> status_args;
533 status_args.emplace_back(new MethodCall(
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900534 method.GetName(), BuildArgList(typenames, method, false /* not for method decl */)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800535 b->AddStatement(new Statement(new MethodCall(
536 StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName),
537 ArgList(std::move(status_args)))));
Christopher Wileyad339272015-10-05 19:11:58 -0700538
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900539 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100540 b->AddStatement(new Statement(new MethodCall("atrace_end",
541 "ATRACE_TAG_AIDL")));
542 }
543
Jeongik Chab34800b2019-03-08 14:36:58 +0900544 if (options.GenLog()) {
Jeongik Cha37e2ad52019-04-18 13:44:26 +0900545 b->AddLiteral(GenLogAfterExecute(bn_name, interface, method, kStatusVarName, kReturnVarName,
546 true /* isServer */, false /* isNdk */),
547 false);
Jeongik Chab34800b2019-03-08 14:36:58 +0900548 }
549
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800550 // Write exceptions during transaction handling to parcel.
551 if (!method.IsOneway()) {
552 b->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800553 kAndroidStatusVarName,
554 StringPrintf("%s.writeToParcel(%s)", kStatusVarName, kReplyVarName)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800555 b->AddStatement(BreakOnStatusNotOk());
556 IfStatement* exception_check = new IfStatement(
557 new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
558 b->AddStatement(exception_check);
559 exception_check->OnTrue()->AddLiteral("break");
560 }
Casey Dahlinb0966612015-10-19 16:35:26 -0700561
Christopher Wiley36570f42015-10-08 17:20:11 -0700562 // If we have a return value, write it first.
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900563 if (method.GetType().GetName() != "void") {
Christopher Wiley2aaeda82015-10-19 15:16:49 -0700564 string writeMethod =
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900565 string(kReplyVarName) + "->" + ParcelWriteMethodOf(method.GetType(), typenames);
Daniel Norman85aed542019-08-21 12:01:14 -0700566 b->AddStatement(new Assignment(
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900567 kAndroidStatusVarName,
Daniel Norman85aed542019-08-21 12:01:14 -0700568 new MethodCall(writeMethod,
569 ParcelWriteCastOf(method.GetType(), typenames, kReturnVarName))));
Christopher Wiley0eb903e2015-10-20 17:07:08 -0700570 b->AddStatement(BreakOnStatusNotOk());
Christopher Wiley36570f42015-10-08 17:20:11 -0700571 }
Christopher Wileyad339272015-10-05 19:11:58 -0700572 // Write each out parameter to the reply parcel.
573 for (const AidlArgument* a : method.GetOutArguments()) {
574 // Serialization looks roughly like:
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800575 // _aidl_ret_status = data.WriteInt32(out_param_name);
576 // if (_aidl_ret_status != ::android::OK) { break; }
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900577 const string& writeMethod = ParcelWriteMethodOf(a->GetType(), typenames);
Daniel Norman85aed542019-08-21 12:01:14 -0700578 b->AddStatement(new Assignment(
579 kAndroidStatusVarName,
580 new MethodCall(string(kReplyVarName) + "->" + writeMethod,
581 ParcelWriteCastOf(a->GetType(), typenames, BuildVarName(*a)))));
Christopher Wiley0eb903e2015-10-20 17:07:08 -0700582 b->AddStatement(BreakOnStatusNotOk());
Christopher Wileyad339272015-10-05 19:11:58 -0700583 }
584
585 return true;
586}
587
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900588bool HandleServerMetaTransaction(const AidlTypenames&, const AidlInterface& interface,
Jiyong Park309668e2018-07-28 16:55:44 +0900589 const AidlMethod& method, const Options& options,
590 StatementBlock* b) {
591 CHECK(!method.IsUserDefined());
592
593 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
594 std::ostringstream code;
Jiyong Park965c5b92018-11-21 13:37:15 +0900595 code << "_aidl_data.checkInterface(this);\n"
Jeongik Chaf1470e22019-05-20 18:45:05 +0900596 << "_aidl_reply->writeNoException();\n"
Jiyong Park965c5b92018-11-21 13:37:15 +0900597 << "_aidl_reply->writeInt32(" << ClassName(interface, ClassNames::INTERFACE)
Jiyong Park309668e2018-07-28 16:55:44 +0900598 << "::VERSION)";
599 b->AddLiteral(code.str());
600 return true;
601 }
602 return false;
603}
604
Christopher Wileyad339272015-10-05 19:11:58 -0700605} // namespace
606
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900607unique_ptr<Document> BuildServerSource(const AidlTypenames& typenames,
608 const AidlInterface& interface, const Options& options) {
Christopher Wiley054afbd2015-10-16 17:08:43 -0700609 const string bn_name = ClassName(interface, ClassNames::SERVER);
610 vector<string> include_list{
611 HeaderFile(interface, ClassNames::SERVER, false),
Steven Morelanda57d0a62019-07-30 09:41:14 -0700612 kParcelHeader,
613 kStabilityHeader,
Christopher Wiley054afbd2015-10-16 17:08:43 -0700614 };
Jeongik Cha46375122018-12-21 18:41:21 +0900615 if (options.GenLog()) {
616 include_list.emplace_back("chrono");
617 include_list.emplace_back("functional");
618 include_list.emplace_back("json/value.h");
Jeongik Cha46375122018-12-21 18:41:21 +0900619 }
Steven Moreland800508d2019-07-30 10:45:31 -0700620
621 unique_ptr<ConstructorImpl> constructor{
622 new ConstructorImpl{ClassName(interface, ClassNames::SERVER), ArgList{}, {}}};
623
Steven Morelanda57d0a62019-07-30 09:41:14 -0700624 if (interface.IsVintfStability()) {
625 constructor->GetStatementBlock()->AddLiteral("::android::internal::Stability::markVintf(this)");
626 } else {
627 constructor->GetStatementBlock()->AddLiteral(
628 "::android::internal::Stability::markCompilationUnit(this)");
629 }
630
Christopher Wileyad339272015-10-05 19:11:58 -0700631 unique_ptr<MethodImpl> on_transact{new MethodImpl{
632 kAndroidStatusLiteral, bn_name, "onTransact",
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800633 ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
634 StringPrintf("const %s& %s", kAndroidParcelLiteral,
635 kDataVarName),
636 StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
637 StringPrintf("uint32_t %s", kFlagsVarName)}}
Christopher Wiley36570f42015-10-08 17:20:11 -0700638 }};
Christopher Wileyad339272015-10-05 19:11:58 -0700639
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800640 // Declare the status_t variable
Christopher Wiley05f4f892015-10-14 13:30:43 -0700641 on_transact->GetStatementBlock()->AddLiteral(
Christopher Wiley10957122015-12-04 14:35:38 -0800642 StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName,
643 kAndroidStatusOk));
Christopher Wiley05f4f892015-10-14 13:30:43 -0700644
Christopher Wileyad339272015-10-05 19:11:58 -0700645 // Add the all important switch statement, but retain a pointer to it.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800646 SwitchStatement* s = new SwitchStatement{kCodeVarName};
Christopher Wileyf9688b02015-10-08 17:17:50 -0700647 on_transact->GetStatementBlock()->AddStatement(s);
Christopher Wileyad339272015-10-05 19:11:58 -0700648
649 // The switch statement has a case statement for each transaction code.
Christopher Wiley054afbd2015-10-16 17:08:43 -0700650 for (const auto& method : interface.GetMethods()) {
Jeongik Chab5d962f2018-11-17 09:12:28 +0900651 StatementBlock* b = s->AddCase(GetTransactionIdFor(*method));
Christopher Wileyad339272015-10-05 19:11:58 -0700652 if (!b) { return nullptr; }
653
Jiyong Park309668e2018-07-28 16:55:44 +0900654 bool success = false;
655 if (method->IsUserDefined()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900656 success = HandleServerTransaction(typenames, interface, *method, options, b);
Jiyong Park309668e2018-07-28 16:55:44 +0900657 } else {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900658 success = HandleServerMetaTransaction(typenames, interface, *method, options, b);
Jiyong Park309668e2018-07-28 16:55:44 +0900659 }
660 if (!success) {
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900661 return nullptr;
662 }
Christopher Wileyad339272015-10-05 19:11:58 -0700663 }
664
665 // The switch statement has a default case which defers to the super class.
666 // The superclass handles a few pre-defined transactions.
667 StatementBlock* b = s->AddCase("");
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800668 b->AddLiteral(StringPrintf(
669 "%s = ::android::BBinder::onTransact(%s, %s, "
670 "%s, %s)", kAndroidStatusVarName, kCodeVarName,
671 kDataVarName, kReplyVarName, kFlagsVarName));
Christopher Wileyad339272015-10-05 19:11:58 -0700672
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800673 // If we saw a null reference, we can map that to an appropriate exception.
674 IfStatement* null_check = new IfStatement(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800675 new LiteralExpression(string(kAndroidStatusVarName) +
676 " == ::android::UNEXPECTED_NULL"));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800677 on_transact->GetStatementBlock()->AddStatement(null_check);
678 null_check->OnTrue()->AddStatement(new Assignment(
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800679 kAndroidStatusVarName,
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800680 StringPrintf("%s::fromExceptionCode(%s::EX_NULL_POINTER)"
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800681 ".writeToParcel(%s)",
682 kBinderStatusLiteral, kBinderStatusLiteral,
683 kReplyVarName)));
Christopher Wiley433c8bb2015-11-12 14:20:46 -0800684
Christopher Wileyad339272015-10-05 19:11:58 -0700685 // Finally, the server's onTransact method just returns a status code.
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800686 on_transact->GetStatementBlock()->AddLiteral(
687 StringPrintf("return %s", kAndroidStatusVarName));
Jeongik Cha46375122018-12-21 18:41:21 +0900688 vector<unique_ptr<Declaration>> decls;
Steven Moreland800508d2019-07-30 10:45:31 -0700689 decls.push_back(std::move(constructor));
Jeongik Cha46375122018-12-21 18:41:21 +0900690 decls.push_back(std::move(on_transact));
Christopher Wileyad339272015-10-05 19:11:58 -0700691
Jiyong Park22d4cfc2019-04-09 14:23:41 +0900692 if (options.Version() > 0) {
693 std::ostringstream code;
694 code << "int32_t " << bn_name << "::" << kGetInterfaceVersion << "() {\n"
695 << " return " << ClassName(interface, ClassNames::INTERFACE) << "::VERSION;\n"
696 << "}\n";
697 decls.emplace_back(new LiteralDecl(code.str()));
698 }
699
Jeongik Cha46375122018-12-21 18:41:21 +0900700 if (options.GenLog()) {
701 string code;
702 ClassName(interface, ClassNames::SERVER);
703 CodeWriterPtr writer = CodeWriter::ForString(&code);
704 (*writer) << "std::function<void(const Json::Value&)> "
705 << ClassName(interface, ClassNames::SERVER) << "::logFunc;\n";
706 writer->Close();
707 decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
708 }
709 return unique_ptr<Document>{
710 new CppSource{include_list, NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700711}
712
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900713unique_ptr<Document> BuildInterfaceSource(const AidlTypenames& typenames,
Jiyong Park309668e2018-07-28 16:55:44 +0900714 const AidlInterface& interface, const Options& options) {
Christopher Wiley054afbd2015-10-16 17:08:43 -0700715 vector<string> include_list{
Jiyong Park5b7e5322019-04-03 20:05:01 +0900716 HeaderFile(interface, ClassNames::RAW, false),
Christopher Wiley054afbd2015-10-16 17:08:43 -0700717 HeaderFile(interface, ClassNames::CLIENT, false),
718 };
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700719
Christopher Wiley054afbd2015-10-16 17:08:43 -0700720 string fq_name = ClassName(interface, ClassNames::INTERFACE);
721 if (!interface.GetPackage().empty()) {
722 fq_name = interface.GetPackage() + "." + fq_name;
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700723 }
724
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700725 vector<unique_ptr<Declaration>> decls;
726
Christopher Wiley11a9d792016-02-24 17:20:33 -0800727 unique_ptr<MacroDecl> meta_if{new MacroDecl{
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700728 "IMPLEMENT_META_INTERFACE",
Christopher Wiley054afbd2015-10-16 17:08:43 -0700729 ArgList{vector<string>{ClassName(interface, ClassNames::BASE),
Christopher Wileyade4b452015-10-10 11:06:03 -0700730 '"' + fq_name + '"'}}}};
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700731 decls.push_back(std::move(meta_if));
732
Steven Moreland693640b2018-07-19 13:46:27 -0700733 for (const auto& constant : interface.GetConstantDeclarations()) {
734 const AidlConstantValue& value = constant->GetValue();
735 if (value.GetType() != AidlConstantValue::Type::STRING) continue;
736
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900737 std::string cppType = CppNameOf(constant->GetType(), typenames);
Steven Moreland4d12f9a2018-10-31 14:30:55 -0700738 unique_ptr<MethodImpl> getter(new MethodImpl("const " + cppType + "&",
739 ClassName(interface, ClassNames::INTERFACE),
740 constant->GetName(), {}));
Steven Moreland860b1942018-08-16 14:59:28 -0700741 getter->GetStatementBlock()->AddLiteral(
Steven Moreland4d12f9a2018-10-31 14:30:55 -0700742 StringPrintf("static const %s value(%s)", cppType.c_str(),
Steven Moreland860b1942018-08-16 14:59:28 -0700743 constant->ValueString(ConstantValueDecorator).c_str()));
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700744 getter->GetStatementBlock()->AddLiteral("return value");
745 decls.push_back(std::move(getter));
746 }
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700747
Jiyong Park75e1a742018-07-04 12:31:23 +0900748 // Implement the default impl class.
749 // onAsBinder returns nullptr as this interface is not associated with a
750 // real binder.
751 const string default_impl(ClassName(interface, ClassNames::DEFAULT_IMPL));
752 decls.emplace_back(
753 new LiteralDecl(StringPrintf("::android::IBinder* %s::onAsBinder() {\n"
754 " return nullptr;\n"
755 "}\n",
756 default_impl.c_str())));
757 // Each interface method by default returns UNKNOWN_TRANSACTION with is
758 // the same status that is returned by transact() when the method is
759 // not implemented in the server side. In other words, these default
760 // methods do nothing; they only exist to aid making a real default
761 // impl class without having to override all methods in an interface.
762 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900763 if (method->IsUserDefined()) {
764 std::ostringstream code;
765 code << "::android::binder::Status " << default_impl << "::" << method->GetName()
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900766 << BuildArgList(typenames, *method, true, true).ToString() << " {\n"
Jiyong Park309668e2018-07-28 16:55:44 +0900767 << " return ::android::binder::Status::fromStatusT(::android::UNKNOWN_TRANSACTION);\n"
768 << "}\n";
769 decls.emplace_back(new LiteralDecl(code.str()));
770 } else {
771 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
772 std::ostringstream code;
773 code << "int32_t " << default_impl << "::" << kGetInterfaceVersion << "() {\n"
774 << " return 0;\n"
775 << "}\n";
776 decls.emplace_back(new LiteralDecl(code.str()));
777 }
778 }
Jiyong Park75e1a742018-07-04 12:31:23 +0900779 }
780
Christopher Wiley1dd458d2015-09-30 11:05:52 -0700781 return unique_ptr<Document>{new CppSource{
782 include_list,
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700783 NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700784}
785
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900786unique_ptr<Document> BuildClientHeader(const AidlTypenames& typenames,
787 const AidlInterface& interface, const Options& options) {
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700788 const string i_name = ClassName(interface, ClassNames::INTERFACE);
789 const string bp_name = ClassName(interface, ClassNames::CLIENT);
Casey Dahlina834dd42015-09-23 11:52:15 -0700790
Jiyong Parkb064cbb2018-11-06 02:47:18 +0900791 vector<string> includes = {kIBinderHeader, kIInterfaceHeader, "utils/Errors.h",
Jiyong Park5b7e5322019-04-03 20:05:01 +0900792 HeaderFile(interface, ClassNames::RAW, false)};
Jiyong Parkce50e262018-10-29 09:54:20 +0900793
Christopher Wileyb23149d2015-10-14 13:52:21 -0700794 unique_ptr<ConstructorDecl> constructor{new ConstructorDecl{
795 bp_name,
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800796 ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
797 kImplVarName)},
Christopher Wileyb23149d2015-10-14 13:52:21 -0700798 ConstructorDecl::IS_EXPLICIT
799 }};
800 unique_ptr<ConstructorDecl> destructor{new ConstructorDecl{
801 "~" + bp_name,
802 ArgList{},
803 ConstructorDecl::IS_VIRTUAL | ConstructorDecl::IS_DEFAULT}};
Casey Dahlina834dd42015-09-23 11:52:15 -0700804
Christopher Wileyf944e792015-09-29 10:00:46 -0700805 vector<unique_ptr<Declaration>> publics;
Casey Dahlina834dd42015-09-23 11:52:15 -0700806 publics.push_back(std::move(constructor));
807 publics.push_back(std::move(destructor));
808
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700809 for (const auto& method: interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900810 if (method->IsUserDefined()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900811 publics.push_back(BuildMethodDecl(*method, typenames, false));
Jiyong Park309668e2018-07-28 16:55:44 +0900812 } else {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900813 publics.push_back(BuildMetaMethodDecl(*method, typenames, options, false));
Jiyong Park309668e2018-07-28 16:55:44 +0900814 }
Casey Dahlina834dd42015-09-23 11:52:15 -0700815 }
816
Jiyong Parkce50e262018-10-29 09:54:20 +0900817 if (options.GenLog()) {
Jiyong Parkb064cbb2018-11-06 02:47:18 +0900818 includes.emplace_back("chrono"); // for std::chrono::steady_clock
819 includes.emplace_back("functional"); // for std::function
820 includes.emplace_back("json/value.h");
Jiyong Parkce50e262018-10-29 09:54:20 +0900821 publics.emplace_back(
822 new LiteralDecl{"static std::function<void(const Json::Value&)> logFunc;\n"});
823 }
824
Jiyong Park309668e2018-07-28 16:55:44 +0900825 vector<unique_ptr<Declaration>> privates;
826
827 if (options.Version() > 0) {
828 privates.emplace_back(new LiteralDecl("int32_t cached_version_ = -1;\n"));
829 }
830
831 unique_ptr<ClassDecl> bp_class{new ClassDecl{
832 bp_name,
833 "::android::BpInterface<" + i_name + ">",
834 std::move(publics),
835 std::move(privates),
836 }};
Casey Dahlina834dd42015-09-23 11:52:15 -0700837
Jiyong Parkce50e262018-10-29 09:54:20 +0900838 return unique_ptr<Document>{
Jiyong Parkb064cbb2018-11-06 02:47:18 +0900839 new CppHeader{BuildHeaderGuard(interface, ClassNames::CLIENT), includes,
Jiyong Parkce50e262018-10-29 09:54:20 +0900840 NestInNamespaces(std::move(bp_class), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700841}
842
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900843unique_ptr<Document> BuildServerHeader(const AidlTypenames& /* typenames */,
Jeongik Cha46375122018-12-21 18:41:21 +0900844 const AidlInterface& interface, const Options& options) {
Christopher Wileyfd51d602015-10-14 13:04:48 -0700845 const string i_name = ClassName(interface, ClassNames::INTERFACE);
846 const string bn_name = ClassName(interface, ClassNames::SERVER);
Casey Dahlin082f1d12015-09-21 14:06:25 -0700847
Steven Moreland800508d2019-07-30 10:45:31 -0700848 unique_ptr<ConstructorDecl> constructor{
849 new ConstructorDecl{bn_name, ArgList{}, ConstructorDecl::IS_EXPLICIT}};
850
Christopher Wileyfd51d602015-10-14 13:04:48 -0700851 unique_ptr<Declaration> on_transact{new MethodDecl{
Christopher Wileyade4b452015-10-10 11:06:03 -0700852 kAndroidStatusLiteral, "onTransact",
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800853 ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
854 StringPrintf("const %s& %s", kAndroidParcelLiteral,
855 kDataVarName),
856 StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
Jiyong Park8533bd02018-10-29 21:31:18 +0900857 StringPrintf("uint32_t %s", kFlagsVarName)}},
Christopher Wileyfd51d602015-10-14 13:04:48 -0700858 MethodDecl::IS_OVERRIDE
859 }};
Jiyong Park5b7e5322019-04-03 20:05:01 +0900860 vector<string> includes = {"binder/IInterface.h", HeaderFile(interface, ClassNames::RAW, false)};
Casey Dahlin082f1d12015-09-21 14:06:25 -0700861
Jeongik Cha46375122018-12-21 18:41:21 +0900862 vector<unique_ptr<Declaration>> publics;
Steven Moreland800508d2019-07-30 10:45:31 -0700863 publics.push_back(std::move(constructor));
Casey Dahlinb7d0f7f2015-09-22 17:21:08 -0700864 publics.push_back(std::move(on_transact));
865
Jiyong Park22d4cfc2019-04-09 14:23:41 +0900866 if (options.Version() > 0) {
867 std::ostringstream code;
868 code << "int32_t " << kGetInterfaceVersion << "() final override;\n";
869 publics.emplace_back(new LiteralDecl(code.str()));
870 }
871
Jeongik Cha46375122018-12-21 18:41:21 +0900872 if (options.GenLog()) {
873 includes.emplace_back("chrono"); // for std::chrono::steady_clock
874 includes.emplace_back("functional"); // for std::function
875 includes.emplace_back("json/value.h");
876 publics.emplace_back(
877 new LiteralDecl{"static std::function<void(const Json::Value&)> logFunc;\n"});
878 }
Christopher Wileyf944e792015-09-29 10:00:46 -0700879 unique_ptr<ClassDecl> bn_class{
880 new ClassDecl{bn_name,
Casey Dahlinb8d9e882015-11-24 10:57:23 -0800881 "::android::BnInterface<" + i_name + ">",
Christopher Wileyf944e792015-09-29 10:00:46 -0700882 std::move(publics),
883 {}
Casey Dahlinb7d0f7f2015-09-22 17:21:08 -0700884 }};
Casey Dahlin082f1d12015-09-21 14:06:25 -0700885
Jeongik Cha46375122018-12-21 18:41:21 +0900886 return unique_ptr<Document>{
887 new CppHeader{BuildHeaderGuard(interface, ClassNames::SERVER), includes,
888 NestInNamespaces(std::move(bn_class), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700889}
890
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900891unique_ptr<Document> BuildInterfaceHeader(const AidlTypenames& typenames,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900892 const AidlInterface& interface, const Options& options) {
Jiyong Park75e1a742018-07-04 12:31:23 +0900893 set<string> includes = {kIBinderHeader, kIInterfaceHeader, kStatusHeader, kStrongPointerHeader};
Casey Dahlince776cf2015-10-15 18:45:54 -0700894
895 for (const auto& method : interface.GetMethods()) {
896 for (const auto& argument : method->GetArguments()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900897 AddHeaders(argument->GetType(), typenames, includes);
Casey Dahlince776cf2015-10-15 18:45:54 -0700898 }
899
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900900 AddHeaders(method->GetType(), typenames, includes);
Casey Dahlince776cf2015-10-15 18:45:54 -0700901 }
902
Jiyong Park75e1a742018-07-04 12:31:23 +0900903 const string i_name = ClassName(interface, ClassNames::INTERFACE);
904 unique_ptr<ClassDecl> if_class{new ClassDecl{i_name, "::android::IInterface"}};
Christopher Wiley11a9d792016-02-24 17:20:33 -0800905 if_class->AddPublic(unique_ptr<Declaration>{new MacroDecl{
Christopher Wileyade4b452015-10-10 11:06:03 -0700906 "DECLARE_META_INTERFACE",
Christopher Wiley3bb6bc12015-10-14 10:58:27 -0700907 ArgList{vector<string>{ClassName(interface, ClassNames::BASE)}}}});
Christopher Wiley0c732db2015-09-29 14:36:44 -0700908
Jiyong Park309668e2018-07-28 16:55:44 +0900909 if (options.Version() > 0) {
910 std::ostringstream code;
911 code << "const int32_t VERSION = " << options.Version() << ";\n";
912
913 if_class->AddPublic(unique_ptr<Declaration>(new LiteralDecl(code.str())));
914 }
915
Steven Moreland693640b2018-07-19 13:46:27 -0700916 std::vector<std::unique_ptr<Declaration>> string_constants;
Daniel Norman85aed542019-08-21 12:01:14 -0700917 unique_ptr<Enum> int_constant_enum{new Enum{"", "int32_t", false}};
Steven Moreland693640b2018-07-19 13:46:27 -0700918 for (const auto& constant : interface.GetConstantDeclarations()) {
919 const AidlConstantValue& value = constant->GetValue();
Casey Dahlind40e2fe2015-11-24 14:06:52 -0800920
Steven Moreland693640b2018-07-19 13:46:27 -0700921 switch (value.GetType()) {
922 case AidlConstantValue::Type::STRING: {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900923 std::string cppType = CppNameOf(constant->GetType(), typenames);
Steven Moreland4d12f9a2018-10-31 14:30:55 -0700924 unique_ptr<Declaration> getter(new MethodDecl("const " + cppType + "&", constant->GetName(),
925 {}, MethodDecl::IS_STATIC));
Steven Moreland693640b2018-07-19 13:46:27 -0700926 string_constants.push_back(std::move(getter));
927 break;
928 }
Steven Moreland25294322018-08-07 18:13:55 -0700929 case AidlConstantValue::Type::INTEGRAL:
930 case AidlConstantValue::Type::HEXIDECIMAL: {
Steven Moreland860b1942018-08-16 14:59:28 -0700931 int_constant_enum->AddValue(constant->GetName(),
932 constant->ValueString(ConstantValueDecorator));
Steven Moreland693640b2018-07-19 13:46:27 -0700933 break;
934 }
935 default: {
936 LOG(FATAL) << "Unrecognized constant type: " << static_cast<int>(value.GetType());
937 }
938 }
939 }
940 if (int_constant_enum->HasValues()) {
941 if_class->AddPublic(std::move(int_constant_enum));
942 }
943 if (!string_constants.empty()) {
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700944 includes.insert(kString16Header);
Steven Moreland693640b2018-07-19 13:46:27 -0700945
946 for (auto& string_constant : string_constants) {
947 if_class->AddPublic(std::move(string_constant));
948 }
Christopher Wiley69b44cf2016-05-03 13:43:33 -0700949 }
Martijn Coenenf1b50782018-02-21 21:06:23 +0100950
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900951 if (options.GenTraces()) {
Martijn Coenenf1b50782018-02-21 21:06:23 +0100952 includes.insert(kTraceHeader);
953 }
954
Christopher Wileyd6bdd8d2016-05-03 11:23:13 -0700955 if (!interface.GetMethods().empty()) {
Christopher Wileyd6bdd8d2016-05-03 11:23:13 -0700956 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900957 if (method->IsUserDefined()) {
958 // Each method gets an enum entry and pure virtual declaration.
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900959 if_class->AddPublic(BuildMethodDecl(*method, typenames, true));
Jiyong Park309668e2018-07-28 16:55:44 +0900960 } else {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900961 if_class->AddPublic(BuildMetaMethodDecl(*method, typenames, options, true));
Jiyong Park309668e2018-07-28 16:55:44 +0900962 }
Christopher Wileyd6bdd8d2016-05-03 11:23:13 -0700963 }
Christopher Wiley0c732db2015-09-29 14:36:44 -0700964 }
Christopher Wiley0c732db2015-09-29 14:36:44 -0700965
Jiyong Park75e1a742018-07-04 12:31:23 +0900966 vector<unique_ptr<Declaration>> decls;
967 decls.emplace_back(std::move(if_class));
968
969 // Base class for the default implementation.
970 vector<string> method_decls;
971 for (const auto& method : interface.GetMethods()) {
Jiyong Park309668e2018-07-28 16:55:44 +0900972 if (method->IsUserDefined()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900973 method_decls.emplace_back(BuildMethodDecl(*method, typenames, false)->ToString());
Jiyong Park309668e2018-07-28 16:55:44 +0900974 } else {
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900975 method_decls.emplace_back(
976 BuildMetaMethodDecl(*method, typenames, options, false)->ToString());
Jiyong Park309668e2018-07-28 16:55:44 +0900977 }
Jiyong Park75e1a742018-07-04 12:31:23 +0900978 }
Jiyong Park309668e2018-07-28 16:55:44 +0900979
Jiyong Park75e1a742018-07-04 12:31:23 +0900980 decls.emplace_back(new LiteralDecl(
981 android::base::StringPrintf("class %s : public %s {\n"
982 "public:\n"
983 " ::android::IBinder* onAsBinder() override;\n"
984 " %s\n"
985 "};\n",
986 ClassName(interface, ClassNames::DEFAULT_IMPL).c_str(),
987 i_name.c_str(), Join(method_decls, " ").c_str())));
988
989 return unique_ptr<Document>{
990 new CppHeader{BuildHeaderGuard(interface, ClassNames::INTERFACE),
991 vector<string>(includes.begin(), includes.end()),
992 NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
Christopher Wiley9a8e1d92015-09-19 10:34:33 -0700993}
994
Jeongik Cha1a7ab642019-07-29 17:31:02 +0900995std::unique_ptr<Document> BuildParcelHeader(const AidlTypenames& typenames,
Jiyong Parkfbbfa932018-07-30 21:44:10 +0900996 const AidlStructuredParcelable& parcel,
997 const Options&) {
Steven Moreland5557f1c2018-07-02 13:50:23 -0700998 unique_ptr<ClassDecl> parcel_class{new ClassDecl{parcel.GetName(), "::android::Parcelable"}};
999
1000 set<string> includes = {kStatusHeader, kParcelHeader};
1001 for (const auto& variable : parcel.GetFields()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001002 AddHeaders(variable->GetType(), typenames, includes);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001003 }
1004
1005 for (const auto& variable : parcel.GetFields()) {
Steven Moreland5557f1c2018-07-02 13:50:23 -07001006
Steven Moreland9ea10e32018-07-19 15:26:09 -07001007 std::ostringstream out;
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001008 std::string cppType = CppNameOf(variable->GetType(), typenames);
1009 out << cppType.c_str() << " " << variable->GetName().c_str();
Steven Moreland25294322018-08-07 18:13:55 -07001010 if (variable->GetDefaultValue()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001011 out << " = " << cppType.c_str() << "(" << variable->ValueString(ConstantValueDecorator)
1012 << ")";
Steven Moreland9ea10e32018-07-19 15:26:09 -07001013 }
1014 out << ";\n";
1015
1016 parcel_class->AddPublic(std::unique_ptr<LiteralDecl>(new LiteralDecl(out.str())));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001017 }
1018
1019 unique_ptr<MethodDecl> read(new MethodDecl(kAndroidStatusLiteral, "readFromParcel",
Steven Morelandce39c532018-07-11 16:59:50 -07001020 ArgList("const ::android::Parcel* _aidl_parcel"),
Jeongik Chaa2ada0c2018-11-17 15:11:45 +09001021 MethodDecl::IS_OVERRIDE | MethodDecl::IS_FINAL));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001022 parcel_class->AddPublic(std::move(read));
Jeongik Chaa2ada0c2018-11-17 15:11:45 +09001023 unique_ptr<MethodDecl> write(new MethodDecl(
1024 kAndroidStatusLiteral, "writeToParcel", ArgList("::android::Parcel* _aidl_parcel"),
1025 MethodDecl::IS_OVERRIDE | MethodDecl::IS_CONST | MethodDecl::IS_FINAL));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001026 parcel_class->AddPublic(std::move(write));
1027
1028 return unique_ptr<Document>{new CppHeader{
1029 BuildHeaderGuard(parcel, ClassNames::BASE), vector<string>(includes.begin(), includes.end()),
1030 NestInNamespaces(std::move(parcel_class), parcel.GetSplitPackage())}};
1031}
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001032std::unique_ptr<Document> BuildParcelSource(const AidlTypenames& typenames,
Jiyong Parkfbbfa932018-07-30 21:44:10 +09001033 const AidlStructuredParcelable& parcel,
1034 const Options&) {
Steven Moreland5557f1c2018-07-02 13:50:23 -07001035 unique_ptr<MethodImpl> read{new MethodImpl{kAndroidStatusLiteral, parcel.GetName(),
1036 "readFromParcel",
Steven Morelandce39c532018-07-11 16:59:50 -07001037 ArgList("const ::android::Parcel* _aidl_parcel")}};
Steven Moreland5557f1c2018-07-02 13:50:23 -07001038 StatementBlock* read_block = read->GetStatementBlock();
1039 read_block->AddLiteral(
1040 StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName, kAndroidStatusOk));
Jeongik Cha95eba572018-11-22 09:14:52 +09001041
1042 read_block->AddLiteral(
1043 "size_t _aidl_start_pos = _aidl_parcel->dataPosition();\n"
1044 "int32_t _aidl_parcelable_raw_size = _aidl_parcel->readInt32();\n"
1045 "if (_aidl_parcelable_raw_size < 0) return ::android::BAD_VALUE;\n"
1046 "size_t _aidl_parcelable_size = static_cast<size_t>(_aidl_parcelable_raw_size);\n");
1047
Steven Moreland5557f1c2018-07-02 13:50:23 -07001048 for (const auto& variable : parcel.GetFields()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001049 string method = ParcelReadMethodOf(variable->GetType(), typenames);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001050
1051 read_block->AddStatement(new Assignment(
1052 kAndroidStatusVarName, new MethodCall(StringPrintf("_aidl_parcel->%s", method.c_str()),
Daniel Norman85aed542019-08-21 12:01:14 -07001053 ParcelReadCastOf(variable->GetType(), typenames,
1054 "&" + variable->GetName()))));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001055 read_block->AddStatement(ReturnOnStatusNotOk());
Jeongik Cha95eba572018-11-22 09:14:52 +09001056 read_block->AddLiteral(StringPrintf(
1057 "if (_aidl_parcel->dataPosition() - _aidl_start_pos >= _aidl_parcelable_size) {\n"
1058 " _aidl_parcel->setDataPosition(_aidl_start_pos + _aidl_parcelable_size);\n"
1059 " return %s;\n"
1060 "}",
1061 kAndroidStatusVarName));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001062 }
1063 read_block->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
1064
Steven Morelandce39c532018-07-11 16:59:50 -07001065 unique_ptr<MethodImpl> write{
1066 new MethodImpl{kAndroidStatusLiteral, parcel.GetName(), "writeToParcel",
1067 ArgList("::android::Parcel* _aidl_parcel"), true /*const*/}};
Steven Moreland5557f1c2018-07-02 13:50:23 -07001068 StatementBlock* write_block = write->GetStatementBlock();
1069 write_block->AddLiteral(
1070 StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName, kAndroidStatusOk));
Jeongik Cha95eba572018-11-22 09:14:52 +09001071
1072 write_block->AddLiteral(
1073 "auto _aidl_start_pos = _aidl_parcel->dataPosition();\n"
1074 "_aidl_parcel->writeInt32(0);");
1075
Steven Moreland5557f1c2018-07-02 13:50:23 -07001076 for (const auto& variable : parcel.GetFields()) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001077 string method = ParcelWriteMethodOf(variable->GetType(), typenames);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001078 write_block->AddStatement(new Assignment(
Daniel Norman85aed542019-08-21 12:01:14 -07001079 kAndroidStatusVarName,
1080 new MethodCall(StringPrintf("_aidl_parcel->%s", method.c_str()),
1081 ParcelWriteCastOf(variable->GetType(), typenames, variable->GetName()))));
Steven Moreland5557f1c2018-07-02 13:50:23 -07001082 write_block->AddStatement(ReturnOnStatusNotOk());
1083 }
Jeongik Cha95eba572018-11-22 09:14:52 +09001084
1085 write_block->AddLiteral(
1086 "auto _aidl_end_pos = _aidl_parcel->dataPosition();\n"
1087 "_aidl_parcel->setDataPosition(_aidl_start_pos);\n"
1088 "_aidl_parcel->writeInt32(_aidl_end_pos - _aidl_start_pos);\n"
1089 "_aidl_parcel->setDataPosition(_aidl_end_pos);");
Steven Moreland5557f1c2018-07-02 13:50:23 -07001090 write_block->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
1091
1092 vector<unique_ptr<Declaration>> file_decls;
1093 file_decls.push_back(std::move(read));
1094 file_decls.push_back(std::move(write));
1095
1096 set<string> includes = {};
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001097 AddHeaders(parcel, includes);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001098
1099 return unique_ptr<Document>{
1100 new CppSource{vector<string>(includes.begin(), includes.end()),
1101 NestInNamespaces(std::move(file_decls), parcel.GetSplitPackage())}};
1102}
1103
Daniel Norman85aed542019-08-21 12:01:14 -07001104std::unique_ptr<Document> BuildEnumHeader(const AidlTypenames& typenames,
1105 const AidlEnumDeclaration& enum_decl) {
1106 unique_ptr<Enum> generated_enum{
1107 new Enum{enum_decl.GetName(), CppNameOf(enum_decl.GetBackingType(), typenames), true}};
1108 for (const auto& enumerator : enum_decl.GetEnumerators()) {
1109 generated_enum->AddValue(
1110 enumerator->GetName(),
1111 enumerator->ValueString(enum_decl.GetBackingType(), ConstantValueDecorator));
1112 }
1113
1114 set<string> includes = {};
1115 AddHeaders(enum_decl.GetBackingType(), typenames, includes);
1116
1117 return unique_ptr<Document>{
1118 new CppHeader{BuildHeaderGuard(enum_decl, ClassNames::BASE),
1119 vector<string>(includes.begin(), includes.end()),
1120 NestInNamespaces(std::move(generated_enum), enum_decl.GetSplitPackage())}};
1121}
1122
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001123bool WriteHeader(const Options& options, const AidlTypenames& typenames,
1124 const AidlInterface& interface, const IoDelegate& io_delegate,
1125 ClassNames header_type) {
Christopher Wiley054afbd2015-10-16 17:08:43 -07001126 unique_ptr<Document> header;
1127 switch (header_type) {
1128 case ClassNames::INTERFACE:
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001129 header = BuildInterfaceHeader(typenames, interface, options);
Jiyong Park5b7e5322019-04-03 20:05:01 +09001130 header_type = ClassNames::RAW;
Christopher Wiley054afbd2015-10-16 17:08:43 -07001131 break;
1132 case ClassNames::CLIENT:
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001133 header = BuildClientHeader(typenames, interface, options);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001134 break;
1135 case ClassNames::SERVER:
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001136 header = BuildServerHeader(typenames, interface, options);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001137 break;
1138 default:
1139 LOG(FATAL) << "aidl internal error";
1140 }
1141 if (!header) {
1142 LOG(ERROR) << "aidl internal error: Failed to generate header.";
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001143 return false;
1144 }
Christopher Wiley054afbd2015-10-16 17:08:43 -07001145
Jiyong Park05463732018-08-09 16:03:02 +09001146 const string header_path = options.OutputHeaderDir() + HeaderFile(interface, header_type);
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001147 unique_ptr<CodeWriter> code_writer(io_delegate.GetCodeWriter(header_path));
1148 header->Write(code_writer.get());
Christopher Wiley054afbd2015-10-16 17:08:43 -07001149
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001150 const bool success = code_writer->Close();
1151 if (!success) {
1152 io_delegate.RemovePath(header_path);
1153 }
1154
1155 return success;
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001156}
1157
Casey Dahlina834dd42015-09-23 11:52:15 -07001158} // namespace internals
1159
1160using namespace internals;
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001161
Jiyong Park74595c12018-07-23 15:22:50 +09001162bool GenerateCppInterface(const string& output_file, const Options& options,
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001163 const AidlTypenames& typenames, const AidlInterface& interface,
Jiyong Park74595c12018-07-23 15:22:50 +09001164 const IoDelegate& io_delegate) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001165 auto interface_src = BuildInterfaceSource(typenames, interface, options);
1166 auto client_src = BuildClientSource(typenames, interface, options);
1167 auto server_src = BuildServerSource(typenames, interface, options);
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001168
Christopher Wiley054afbd2015-10-16 17:08:43 -07001169 if (!interface_src || !client_src || !server_src) {
1170 return false;
1171 }
Christopher Wiley9a8e1d92015-09-19 10:34:33 -07001172
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001173 if (!WriteHeader(options, typenames, interface, io_delegate, ClassNames::INTERFACE) ||
1174 !WriteHeader(options, typenames, interface, io_delegate, ClassNames::CLIENT) ||
1175 !WriteHeader(options, typenames, interface, io_delegate, ClassNames::SERVER)) {
Christopher Wiley054afbd2015-10-16 17:08:43 -07001176 return false;
1177 }
1178
Jiyong Park74595c12018-07-23 15:22:50 +09001179 unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(output_file);
Christopher Wiley054afbd2015-10-16 17:08:43 -07001180 interface_src->Write(writer.get());
1181 client_src->Write(writer.get());
1182 server_src->Write(writer.get());
1183
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001184 const bool success = writer->Close();
1185 if (!success) {
Steven Morelandc209cab2018-08-27 01:25:21 -07001186 io_delegate.RemovePath(output_file);
Christopher Wiley9d6e0b22015-11-13 12:18:16 -08001187 }
1188
1189 return success;
Christopher Wileyeb1acc12015-09-16 11:25:13 -07001190}
1191
Jiyong Park74595c12018-07-23 15:22:50 +09001192bool GenerateCppParcel(const string& output_file, const Options& options,
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001193 const AidlTypenames& typenames, const AidlStructuredParcelable& parcelable,
Jiyong Park74595c12018-07-23 15:22:50 +09001194 const IoDelegate& io_delegate) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001195 auto header = BuildParcelHeader(typenames, parcelable, options);
1196 auto source = BuildParcelSource(typenames, parcelable, options);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001197
1198 if (!header || !source) {
1199 return false;
1200 }
1201
Jiyong Park5b7e5322019-04-03 20:05:01 +09001202 const string header_path = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::RAW);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001203 unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1204 header->Write(header_writer.get());
1205 CHECK(header_writer->Close());
1206
Steven Moreland81079f92018-07-06 16:15:53 -07001207 // TODO(b/111362593): no unecessary files just to have consistent output with interfaces
Jiyong Park05463732018-08-09 16:03:02 +09001208 const string bp_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::CLIENT);
Steven Moreland81079f92018-07-06 16:15:53 -07001209 unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1210 bp_writer->Write("#error TODO(b/111362593) parcelables do not have bp classes");
1211 CHECK(bp_writer->Close());
Jiyong Park05463732018-08-09 16:03:02 +09001212 const string bn_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::SERVER);
Steven Moreland81079f92018-07-06 16:15:53 -07001213 unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1214 bn_writer->Write("#error TODO(b/111362593) parcelables do not have bn classes");
1215 CHECK(bn_writer->Close());
1216
Jiyong Park74595c12018-07-23 15:22:50 +09001217 unique_ptr<CodeWriter> source_writer = io_delegate.GetCodeWriter(output_file);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001218 source->Write(source_writer.get());
1219 CHECK(source_writer->Close());
1220
1221 return true;
1222}
1223
Dan Willemsenc46b65e2019-06-06 10:55:58 -07001224bool GenerateCppParcelDeclaration(const std::string& filename, const Options& options,
1225 const AidlParcelable& parcelable, const IoDelegate& io_delegate) {
1226 CodeWriterPtr source_writer = io_delegate.GetCodeWriter(filename);
1227 *source_writer
Steven Moreland2a9a7d62019-02-05 16:11:54 -08001228 << "// This file is intentionally left blank as placeholder for parcel declaration.\n";
Dan Willemsenc46b65e2019-06-06 10:55:58 -07001229 CHECK(source_writer->Close());
1230
1231 // TODO(b/111362593): no unecessary files just to have consistent output with interfaces
1232 const string header_path = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::RAW);
1233 unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1234 header_writer->Write("#error TODO(b/111362593) parcelables do not have headers");
1235 CHECK(header_writer->Close());
1236 const string bp_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::CLIENT);
1237 unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1238 bp_writer->Write("#error TODO(b/111362593) parcelables do not have bp classes");
1239 CHECK(bp_writer->Close());
1240 const string bn_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::SERVER);
1241 unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1242 bn_writer->Write("#error TODO(b/111362593) parcelables do not have bn classes");
1243 CHECK(bn_writer->Close());
Steven Moreland2a9a7d62019-02-05 16:11:54 -08001244
1245 return true;
1246}
1247
Daniel Norman85aed542019-08-21 12:01:14 -07001248bool GenerateCppEnumDeclaration(const std::string& filename, const Options& options,
1249 const AidlTypenames& typenames,
1250 const AidlEnumDeclaration& enum_decl,
1251 const IoDelegate& io_delegate) {
1252 auto header = BuildEnumHeader(typenames, enum_decl);
1253 if (!header) return false;
1254
1255 const string header_path = options.OutputHeaderDir() + HeaderFile(enum_decl, ClassNames::RAW);
1256 unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1257 header->Write(header_writer.get());
1258 CHECK(header_writer->Close());
1259
1260 // TODO(b/111362593): no unnecessary files just to have consistent output with interfaces
1261 CodeWriterPtr source_writer = io_delegate.GetCodeWriter(filename);
1262 *source_writer
1263 << "// This file is intentionally left blank as placeholder for enum declaration.\n";
1264 CHECK(source_writer->Close());
1265 const string bp_header = options.OutputHeaderDir() + HeaderFile(enum_decl, ClassNames::CLIENT);
1266 unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1267 bp_writer->Write("#error TODO(b/111362593) enums do not have bp classes");
1268 CHECK(bp_writer->Close());
1269 const string bn_header = options.OutputHeaderDir() + HeaderFile(enum_decl, ClassNames::SERVER);
1270 unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1271 bn_writer->Write("#error TODO(b/111362593) enums do not have bn classes");
1272 CHECK(bn_writer->Close());
1273
1274 return true;
1275}
1276
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001277bool GenerateCpp(const string& output_file, const Options& options, const AidlTypenames& typenames,
Steven Moreland5557f1c2018-07-02 13:50:23 -07001278 const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
1279 const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
1280 if (parcelable != nullptr) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001281 return GenerateCppParcel(output_file, options, typenames, *parcelable, io_delegate);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001282 }
1283
Steven Moreland2a9a7d62019-02-05 16:11:54 -08001284 const AidlParcelable* parcelable_decl = defined_type.AsParcelable();
1285 if (parcelable_decl != nullptr) {
Dan Willemsenc46b65e2019-06-06 10:55:58 -07001286 return GenerateCppParcelDeclaration(output_file, options, *parcelable_decl, io_delegate);
Steven Moreland2a9a7d62019-02-05 16:11:54 -08001287 }
1288
Daniel Norman85aed542019-08-21 12:01:14 -07001289 const AidlEnumDeclaration* enum_decl = defined_type.AsEnumDeclaration();
1290 if (enum_decl != nullptr) {
1291 return GenerateCppEnumDeclaration(output_file, options, typenames, *enum_decl, io_delegate);
1292 }
1293
Steven Moreland5557f1c2018-07-02 13:50:23 -07001294 const AidlInterface* interface = defined_type.AsInterface();
1295 if (interface != nullptr) {
Jeongik Cha1a7ab642019-07-29 17:31:02 +09001296 return GenerateCppInterface(output_file, options, typenames, *interface, io_delegate);
Steven Moreland5557f1c2018-07-02 13:50:23 -07001297 }
1298
1299 CHECK(false) << "Unrecognized type sent for cpp generation.";
1300 return false;
1301}
1302
Christopher Wileyf944e792015-09-29 10:00:46 -07001303} // namespace cpp
Christopher Wileyeb1acc12015-09-16 11:25:13 -07001304} // namespace aidl
Christopher Wileyf944e792015-09-29 10:00:46 -07001305} // namespace android