1 /*
2  * Copyright (C) 2015, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "generate_cpp.h"
18 #include "aidl.h"
19 
20 #include <cctype>
21 #include <cstring>
22 #include <memory>
23 #include <random>
24 #include <set>
25 #include <string>
26 
27 #include <android-base/stringprintf.h>
28 
29 #include "aidl_language.h"
30 #include "aidl_to_cpp.h"
31 #include "ast_cpp.h"
32 #include "code_writer.h"
33 #include "logging.h"
34 #include "os.h"
35 
36 using android::base::Join;
37 using android::base::StringPrintf;
38 using std::set;
39 using std::string;
40 using std::unique_ptr;
41 using std::vector;
42 
43 namespace android {
44 namespace aidl {
45 namespace cpp {
46 namespace internals {
47 namespace {
48 
49 const char kAndroidStatusVarName[] = "_aidl_ret_status";
50 const char kCodeVarName[] = "_aidl_code";
51 const char kFlagsVarName[] = "_aidl_flags";
52 const char kDataVarName[] = "_aidl_data";
53 const char kErrorLabel[] = "_aidl_error";
54 const char kImplVarName[] = "_aidl_impl";
55 const char kReplyVarName[] = "_aidl_reply";
56 const char kReturnVarName[] = "_aidl_return";
57 const char kStatusVarName[] = "_aidl_status";
58 const char kTraceVarName[] = "_aidl_trace";
59 const char kAndroidParcelLiteral[] = "::android::Parcel";
60 const char kAndroidStatusLiteral[] = "::android::status_t";
61 const char kAndroidStatusOk[] = "::android::OK";
62 const char kBinderStatusLiteral[] = "::android::binder::Status";
63 const char kIBinderHeader[] = "binder/IBinder.h";
64 const char kIInterfaceHeader[] = "binder/IInterface.h";
65 const char kParcelHeader[] = "binder/Parcel.h";
66 const char kStabilityHeader[] = "binder/Stability.h";
67 const char kStatusHeader[] = "binder/Status.h";
68 const char kString16Header[] = "utils/String16.h";
69 const char kTraceHeader[] = "utils/Trace.h";
70 const char kStrongPointerHeader[] = "utils/StrongPointer.h";
71 const char kAndroidBaseMacrosHeader[] = "android-base/macros.h";
72 
BreakOnStatusNotOk()73 unique_ptr<AstNode> BreakOnStatusNotOk() {
74   IfStatement* ret = new IfStatement(new Comparison(
75       new LiteralExpression(kAndroidStatusVarName), "!=",
76       new LiteralExpression(kAndroidStatusOk)));
77   ret->OnTrue()->AddLiteral("break");
78   return unique_ptr<AstNode>(ret);
79 }
80 
GotoErrorOnBadStatus()81 unique_ptr<AstNode> GotoErrorOnBadStatus() {
82   IfStatement* ret = new IfStatement(new Comparison(
83       new LiteralExpression(kAndroidStatusVarName), "!=",
84       new LiteralExpression(kAndroidStatusOk)));
85   ret->OnTrue()->AddLiteral(StringPrintf("goto %s", kErrorLabel));
86   return unique_ptr<AstNode>(ret);
87 }
88 
ReturnOnStatusNotOk()89 unique_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 
BuildArgList(const AidlTypenames & typenames,const AidlMethod & method,bool for_declaration,bool type_name_only=false)96 ArgList BuildArgList(const AidlTypenames& typenames, const AidlMethod& method, bool for_declaration,
97                      bool type_name_only = false) {
98   // 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     // b/144943748: CppNameOf FileDescriptor is unique_fd. Don't pass it by
103     // const reference but by value to make it easier for the user to keep
104     // it beyond the scope of the call. unique_fd is a thin wrapper for an
105     // int (fd) so passing by value is not expensive.
106     const bool nonCopyable = IsNonCopyableType(a->GetType(), typenames);
107     if (for_declaration) {
108       // Method declarations need typenames, pointers to out params, and variable
109       // names that match the .aidl specification.
110       literal = CppNameOf(a->GetType(), typenames);
111 
112       if (a->IsOut()) {
113         literal = literal + "*";
114       } else {
115         const auto definedType = typenames.TryGetDefinedType(a->GetType().GetName());
116 
117         const bool isEnum = definedType && definedType->AsEnumDeclaration() != nullptr;
118         const bool isPrimitive = AidlTypenames::IsPrimitiveTypename(a->GetType().GetName());
119 
120         // We pass in parameters that are not primitives by const reference.
121         // Arrays of primitives are not primitives.
122         if (!(isPrimitive || isEnum || nonCopyable) || a->GetType().IsArray()) {
123           literal = "const " + literal + "&";
124         }
125       }
126       if (!type_name_only) {
127         literal += " " + a->GetName();
128       }
129     } else {
130       std::string varName = BuildVarName(*a);
131       if (a->IsOut()) {
132         literal = "&" + varName;
133       } else if (nonCopyable) {
134         literal = "std::move(" + varName + ")";
135       } else {
136         literal = varName;
137       }
138     }
139     method_arguments.push_back(literal);
140   }
141 
142   if (method.GetType().GetName() != "void") {
143     string literal;
144     if (for_declaration) {
145       literal = CppNameOf(method.GetType(), typenames) + "*";
146       if (!type_name_only) {
147         literal += " " + string(kReturnVarName);
148       }
149     } else {
150       literal = string{"&"} + kReturnVarName;
151     }
152     method_arguments.push_back(literal);
153   }
154 
155   return ArgList(method_arguments);
156 }
157 
BuildMethodDecl(const AidlMethod & method,const AidlTypenames & typenames,bool for_interface)158 unique_ptr<Declaration> BuildMethodDecl(const AidlMethod& method, const AidlTypenames& typenames,
159                                         bool for_interface) {
160   uint32_t modifiers = 0;
161   if (for_interface) {
162     modifiers |= MethodDecl::IS_VIRTUAL;
163     modifiers |= MethodDecl::IS_PURE_VIRTUAL;
164   } else {
165     modifiers |= MethodDecl::IS_OVERRIDE;
166   }
167 
168   return unique_ptr<Declaration>{
169       new MethodDecl{kBinderStatusLiteral, method.GetName(),
170                      BuildArgList(typenames, method, true /* for method decl */), modifiers}};
171 }
172 
BuildMetaMethodDecl(const AidlMethod & method,const AidlTypenames &,const Options & options,bool for_interface)173 unique_ptr<Declaration> BuildMetaMethodDecl(const AidlMethod& method, const AidlTypenames&,
174                                             const Options& options, bool for_interface) {
175   CHECK(!method.IsUserDefined());
176   if (method.GetName() == kGetInterfaceVersion && options.Version()) {
177     std::ostringstream code;
178     if (for_interface) {
179       code << "virtual ";
180     }
181     code << "int32_t " << kGetInterfaceVersion << "()";
182     if (for_interface) {
183       code << " = 0;\n";
184     } else {
185       code << " override;\n";
186     }
187     return unique_ptr<Declaration>(new LiteralDecl(code.str()));
188   }
189   if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
190     std::ostringstream code;
191     if (for_interface) {
192       code << "virtual ";
193     }
194     code << "std::string " << kGetInterfaceHash << "()";
195     if (for_interface) {
196       code << " = 0;\n";
197     } else {
198       code << " override;\n";
199     }
200     return unique_ptr<Declaration>(new LiteralDecl(code.str()));
201   }
202   return nullptr;
203 }
204 
NestInNamespaces(vector<unique_ptr<Declaration>> decls,const vector<string> & package)205 std::vector<unique_ptr<Declaration>> NestInNamespaces(vector<unique_ptr<Declaration>> decls,
206                                                       const vector<string>& package) {
207   auto it = package.crbegin();  // Iterate over the namespaces inner to outer
208   for (; it != package.crend(); ++it) {
209     vector<unique_ptr<Declaration>> inner;
210     inner.emplace_back(unique_ptr<Declaration>{new CppNamespace{*it, std::move(decls)}});
211 
212     decls = std::move(inner);
213   }
214   return decls;
215 }
216 
NestInNamespaces(unique_ptr<Declaration> decl,const vector<string> & package)217 std::vector<unique_ptr<Declaration>> NestInNamespaces(unique_ptr<Declaration> decl,
218                                                       const vector<string>& package) {
219   vector<unique_ptr<Declaration>> decls;
220   decls.push_back(std::move(decl));
221   return NestInNamespaces(std::move(decls), package);
222 }
223 
DeclareLocalVariable(const AidlArgument & a,StatementBlock * b,const AidlTypenames & typenamespaces)224 bool DeclareLocalVariable(const AidlArgument& a, StatementBlock* b,
225                           const AidlTypenames& typenamespaces) {
226   string type = CppNameOf(a.GetType(), typenamespaces);
227 
228   b->AddLiteral(type + " " + BuildVarName(a));
229   return true;
230 }
231 
BuildHeaderGuard(const AidlDefinedType & defined_type,ClassNames header_type)232 string BuildHeaderGuard(const AidlDefinedType& defined_type, ClassNames header_type) {
233   string class_name = ClassName(defined_type, header_type);
234   for (size_t i = 1; i < class_name.size(); ++i) {
235     if (isupper(class_name[i])) {
236       class_name.insert(i, "_");
237       ++i;
238     }
239   }
240   string ret = StringPrintf("AIDL_GENERATED_%s_%s_H_", defined_type.GetPackage().c_str(),
241                             class_name.c_str());
242   for (char& c : ret) {
243     if (c == '.') {
244       c = '_';
245     }
246     c = toupper(c);
247   }
248   return ret;
249 }
250 
DefineClientTransaction(const AidlTypenames & typenames,const AidlInterface & interface,const AidlMethod & method,const Options & options)251 unique_ptr<Declaration> DefineClientTransaction(const AidlTypenames& typenames,
252                                                 const AidlInterface& interface,
253                                                 const AidlMethod& method, const Options& options) {
254   const string i_name = ClassName(interface, ClassNames::INTERFACE);
255   const string bp_name = ClassName(interface, ClassNames::CLIENT);
256   unique_ptr<MethodImpl> ret{
257       new MethodImpl{kBinderStatusLiteral, bp_name, method.GetName(),
258                      ArgList{BuildArgList(typenames, method, true /* for method decl */)}}};
259   StatementBlock* b = ret->GetStatementBlock();
260 
261   // Declare parcels to hold our query and the response.
262   b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kDataVarName));
263   // Even if we're oneway, the transact method still takes a parcel.
264   b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kReplyVarName));
265 
266   // Declare the status_t variable we need for error handling.
267   b->AddLiteral(StringPrintf("%s %s = %s", kAndroidStatusLiteral,
268                              kAndroidStatusVarName,
269                              kAndroidStatusOk));
270   // We unconditionally return a Status object.
271   b->AddLiteral(StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName));
272 
273   if (options.GenTraces()) {
274     b->AddLiteral(
275         StringPrintf("::android::ScopedTrace %s(ATRACE_TAG_AIDL, \"AIDL::cpp::%s::%s::cppClient\")",
276                      kTraceVarName, interface.GetName().c_str(), method.GetName().c_str()));
277   }
278 
279   if (options.GenLog()) {
280     b->AddLiteral(GenLogBeforeExecute(bp_name, method, false /* isServer */, false /* isNdk */),
281                   false /* no semicolon */);
282   }
283 
284   // Add the name of the interface we're hoping to call.
285   b->AddStatement(new Assignment(
286       kAndroidStatusVarName,
287       new MethodCall(StringPrintf("%s.writeInterfaceToken",
288                                   kDataVarName),
289                      "getInterfaceDescriptor()")));
290   b->AddStatement(GotoErrorOnBadStatus());
291 
292   for (const auto& a: method.GetArguments()) {
293     const string var_name = ((a->IsOut()) ? "*" : "") + a->GetName();
294 
295     if (a->IsIn()) {
296       // Serialization looks roughly like:
297       //     _aidl_ret_status = _aidl_data.WriteInt32(in_param_name);
298       //     if (_aidl_ret_status != ::android::OK) { goto error; }
299       const string& method = ParcelWriteMethodOf(a->GetType(), typenames);
300       b->AddStatement(
301           new Assignment(kAndroidStatusVarName,
302                          new MethodCall(StringPrintf("%s.%s", kDataVarName, method.c_str()),
303                                         ParcelWriteCastOf(a->GetType(), typenames, var_name))));
304       b->AddStatement(GotoErrorOnBadStatus());
305     } else if (a->IsOut() && a->GetType().IsArray()) {
306       // Special case, the length of the out array is written into the parcel.
307       //     _aidl_ret_status = _aidl_data.writeVectorSize(&out_param_name);
308       //     if (_aidl_ret_status != ::android::OK) { goto error; }
309       b->AddStatement(new Assignment(
310           kAndroidStatusVarName,
311           new MethodCall(StringPrintf("%s.writeVectorSize", kDataVarName), var_name)));
312       b->AddStatement(GotoErrorOnBadStatus());
313     }
314   }
315 
316   // Invoke the transaction on the remote binder and confirm status.
317   string transaction_code = GetTransactionIdFor(method);
318 
319   vector<string> args = {transaction_code, kDataVarName,
320                          StringPrintf("&%s", kReplyVarName)};
321 
322   if (method.IsOneway()) {
323     args.push_back("::android::IBinder::FLAG_ONEWAY");
324   }
325 
326   b->AddStatement(new Assignment(
327       kAndroidStatusVarName,
328       new MethodCall("remote()->transact",
329                      ArgList(args))));
330 
331   // If the method is not implemented in the remote side, try to call the
332   // default implementation, if provided.
333   vector<string> arg_names;
334   for (const auto& a : method.GetArguments()) {
335     if (IsNonCopyableType(a->GetType(), typenames)) {
336       arg_names.emplace_back(StringPrintf("std::move(%s)", a->GetName().c_str()));
337     } else {
338       arg_names.emplace_back(a->GetName());
339     }
340   }
341   if (method.GetType().GetName() != "void") {
342     arg_names.emplace_back(kReturnVarName);
343   }
344   b->AddLiteral(StringPrintf("if (UNLIKELY(_aidl_ret_status == ::android::UNKNOWN_TRANSACTION && "
345                              "%s::getDefaultImpl())) {\n"
346                              "   return %s::getDefaultImpl()->%s(%s);\n"
347                              "}\n",
348                              i_name.c_str(), i_name.c_str(), method.GetName().c_str(),
349                              Join(arg_names, ", ").c_str()),
350                 false /* no semicolon */);
351 
352   b->AddStatement(GotoErrorOnBadStatus());
353 
354   if (!method.IsOneway()) {
355     // Strip off the exception header and fail if we see a remote exception.
356     // _aidl_ret_status = _aidl_status.readFromParcel(_aidl_reply);
357     // if (_aidl_ret_status != ::android::OK) { goto error; }
358     // if (!_aidl_status.isOk()) { return _aidl_ret_status; }
359     b->AddStatement(new Assignment(
360         kAndroidStatusVarName,
361         StringPrintf("%s.readFromParcel(%s)", kStatusVarName, kReplyVarName)));
362     b->AddStatement(GotoErrorOnBadStatus());
363     IfStatement* exception_check = new IfStatement(
364         new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
365     b->AddStatement(exception_check);
366     exception_check->OnTrue()->AddLiteral(
367         StringPrintf("return %s", kStatusVarName));
368   }
369 
370   // Type checking should guarantee that nothing below emits code until "return
371   // status" if we are a oneway method, so no more fear of accessing reply.
372 
373   // If the method is expected to return something, read it first by convention.
374   if (method.GetType().GetName() != "void") {
375     const string& method_call = ParcelReadMethodOf(method.GetType(), typenames);
376     b->AddStatement(new Assignment(
377         kAndroidStatusVarName,
378         new MethodCall(StringPrintf("%s.%s", kReplyVarName, method_call.c_str()),
379                        ParcelReadCastOf(method.GetType(), typenames, kReturnVarName))));
380     b->AddStatement(GotoErrorOnBadStatus());
381   }
382 
383   for (const AidlArgument* a : method.GetOutArguments()) {
384     // Deserialization looks roughly like:
385     //     _aidl_ret_status = _aidl_reply.ReadInt32(out_param_name);
386     //     if (_aidl_status != ::android::OK) { goto _aidl_error; }
387     string method = ParcelReadMethodOf(a->GetType(), typenames);
388 
389     b->AddStatement(
390         new Assignment(kAndroidStatusVarName,
391                        new MethodCall(StringPrintf("%s.%s", kReplyVarName, method.c_str()),
392                                       ParcelReadCastOf(a->GetType(), typenames, a->GetName()))));
393     b->AddStatement(GotoErrorOnBadStatus());
394   }
395 
396   // If we've gotten to here, one of two things is true:
397   //   1) We've read some bad status_t
398   //   2) We've only read status_t == OK and there was no exception in the
399   //      response.
400   // In both cases, we're free to set Status from the status_t and return.
401   b->AddLiteral(StringPrintf("%s:\n", kErrorLabel), false /* no semicolon */);
402   b->AddLiteral(
403       StringPrintf("%s.setFromStatusT(%s)", kStatusVarName,
404                    kAndroidStatusVarName));
405 
406   if (options.GenLog()) {
407     b->AddLiteral(GenLogAfterExecute(bp_name, interface, method, kStatusVarName, kReturnVarName,
408                                      false /* isServer */, false /* isNdk */),
409                   false /* no semicolon */);
410   }
411 
412   b->AddLiteral(StringPrintf("return %s", kStatusVarName));
413 
414   return unique_ptr<Declaration>(ret.release());
415 }
416 
DefineClientMetaTransaction(const AidlTypenames &,const AidlInterface & interface,const AidlMethod & method,const Options & options)417 unique_ptr<Declaration> DefineClientMetaTransaction(const AidlTypenames& /* typenames */,
418                                                     const AidlInterface& interface,
419                                                     const AidlMethod& method,
420                                                     const Options& options) {
421   CHECK(!method.IsUserDefined());
422   if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
423     const string iface = ClassName(interface, ClassNames::INTERFACE);
424     const string proxy = ClassName(interface, ClassNames::CLIENT);
425     // Note: race condition can happen here, but no locking is required
426     // because 1) writing an interger is atomic and 2) this transaction
427     // will always return the same value, i.e., competing threads will
428     // give write the same value to cached_version_.
429     std::ostringstream code;
430     code << "int32_t " << proxy << "::" << kGetInterfaceVersion << "() {\n"
431          << "  if (cached_version_ == -1) {\n"
432          << "    ::android::Parcel data;\n"
433          << "    ::android::Parcel reply;\n"
434          << "    data.writeInterfaceToken(getInterfaceDescriptor());\n"
435          << "    ::android::status_t err = remote()->transact(" << GetTransactionIdFor(method)
436          << ", data, &reply);\n"
437          << "    if (err == ::android::OK) {\n"
438          << "      ::android::binder::Status _aidl_status;\n"
439          << "      err = _aidl_status.readFromParcel(reply);\n"
440          << "      if (err == ::android::OK && _aidl_status.isOk()) {\n"
441          << "        cached_version_ = reply.readInt32();\n"
442          << "      }\n"
443          << "    }\n"
444          << "  }\n"
445          << "  return cached_version_;\n"
446          << "}\n";
447     return unique_ptr<Declaration>(new LiteralDecl(code.str()));
448   }
449   if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
450     const string iface = ClassName(interface, ClassNames::INTERFACE);
451     const string proxy = ClassName(interface, ClassNames::CLIENT);
452     std::ostringstream code;
453     code << "std::string " << proxy << "::" << kGetInterfaceHash << "() {\n"
454          << "  std::lock_guard<std::mutex> lockGuard(cached_hash_mutex_);\n"
455          << "  if (cached_hash_ == \"-1\") {\n"
456          << "    ::android::Parcel data;\n"
457          << "    ::android::Parcel reply;\n"
458          << "    data.writeInterfaceToken(getInterfaceDescriptor());\n"
459          << "    ::android::status_t err = remote()->transact(" << GetTransactionIdFor(method)
460          << ", data, &reply);\n"
461          << "    if (err == ::android::OK) {\n"
462          << "      ::android::binder::Status _aidl_status;\n"
463          << "      err = _aidl_status.readFromParcel(reply);\n"
464          << "      if (err == ::android::OK && _aidl_status.isOk()) {\n"
465          << "        reply.readUtf8FromUtf16(&cached_hash_);\n"
466          << "      }\n"
467          << "    }\n"
468          << "  }\n"
469          << "  return cached_hash_;\n"
470          << "}\n";
471     return unique_ptr<Declaration>(new LiteralDecl(code.str()));
472   }
473   return nullptr;
474 }
475 
476 }  // namespace
477 
BuildClientSource(const AidlTypenames & typenames,const AidlInterface & interface,const Options & options)478 unique_ptr<Document> BuildClientSource(const AidlTypenames& typenames,
479                                        const AidlInterface& interface, const Options& options) {
480   vector<string> include_list = {
481       HeaderFile(interface, ClassNames::CLIENT, false),
482       kParcelHeader,
483       kAndroidBaseMacrosHeader
484   };
485   if (options.GenLog()) {
486     include_list.emplace_back("chrono");
487     include_list.emplace_back("functional");
488     include_list.emplace_back("json/value.h");
489   }
490   vector<unique_ptr<Declaration>> file_decls;
491 
492   // The constructor just passes the IBinder instance up to the super
493   // class.
494   const string i_name = ClassName(interface, ClassNames::INTERFACE);
495   file_decls.push_back(unique_ptr<Declaration>{new ConstructorImpl{
496       ClassName(interface, ClassNames::CLIENT),
497       ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
498                            kImplVarName)},
499       { "BpInterface<" + i_name + ">(" + kImplVarName + ")" }}});
500 
501   if (options.GenLog()) {
502     string code;
503     ClassName(interface, ClassNames::CLIENT);
504     CodeWriterPtr writer = CodeWriter::ForString(&code);
505     (*writer) << "std::function<void(const Json::Value&)> "
506               << ClassName(interface, ClassNames::CLIENT) << "::logFunc;\n";
507     writer->Close();
508     file_decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
509   }
510 
511   // Clients define a method per transaction.
512   for (const auto& method : interface.GetMethods()) {
513     unique_ptr<Declaration> m;
514     if (method->IsUserDefined()) {
515       m = DefineClientTransaction(typenames, interface, *method, options);
516     } else {
517       m = DefineClientMetaTransaction(typenames, interface, *method, options);
518     }
519     if (!m) { return nullptr; }
520     file_decls.push_back(std::move(m));
521   }
522   return unique_ptr<Document>{new CppSource{
523       include_list,
524       NestInNamespaces(std::move(file_decls), interface.GetSplitPackage())}};
525 }
526 
527 namespace {
528 
HandleServerTransaction(const AidlTypenames & typenames,const AidlInterface & interface,const AidlMethod & method,const Options & options,StatementBlock * b)529 bool HandleServerTransaction(const AidlTypenames& typenames, const AidlInterface& interface,
530                              const AidlMethod& method, const Options& options, StatementBlock* b) {
531   // Declare all the parameters now.  In the common case, we expect no errors
532   // in serialization.
533   for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
534     if (!DeclareLocalVariable(*a, b, typenames)) {
535       return false;
536     }
537   }
538 
539   // Declare a variable to hold the return value.
540   if (method.GetType().GetName() != "void") {
541     string type = CppNameOf(method.GetType(), typenames);
542     b->AddLiteral(StringPrintf("%s %s", type.c_str(), kReturnVarName));
543   }
544 
545   // Check that the client is calling the correct interface.
546   IfStatement* interface_check = new IfStatement(
547       new MethodCall(StringPrintf("%s.checkInterface",
548                                   kDataVarName), "this"),
549       true /* invert the check */);
550   b->AddStatement(interface_check);
551   interface_check->OnTrue()->AddStatement(
552       new Assignment(kAndroidStatusVarName, "::android::BAD_TYPE"));
553   interface_check->OnTrue()->AddLiteral("break");
554 
555   if (options.GenTraces()) {
556     b->AddLiteral(
557         StringPrintf("::android::ScopedTrace %s(ATRACE_TAG_AIDL, \"AIDL::cpp::%s::%s::cppServer\")",
558                      kTraceVarName, interface.GetName().c_str(), method.GetName().c_str()));
559   }
560 
561   // Deserialize each "in" parameter to the transaction.
562   for (const auto& a: method.GetArguments()) {
563     // Deserialization looks roughly like:
564     //     _aidl_ret_status = _aidl_data.ReadInt32(&in_param_name);
565     //     if (_aidl_ret_status != ::android::OK) { break; }
566     const string& var_name = "&" + BuildVarName(*a);
567     if (a->IsIn()) {
568       const string& readMethod = ParcelReadMethodOf(a->GetType(), typenames);
569       b->AddStatement(
570           new Assignment{kAndroidStatusVarName,
571                          new MethodCall{string(kDataVarName) + "." + readMethod,
572                                         ParcelReadCastOf(a->GetType(), typenames, var_name)}});
573       b->AddStatement(BreakOnStatusNotOk());
574     } else if (a->IsOut() && a->GetType().IsArray()) {
575       // Special case, the length of the out array is written into the parcel.
576       //     _aidl_ret_status = _aidl_data.resizeOutVector(&out_param_name);
577       //     if (_aidl_ret_status != ::android::OK) { break; }
578       b->AddStatement(
579           new Assignment{kAndroidStatusVarName,
580                          new MethodCall{string(kDataVarName) + ".resizeOutVector", var_name}});
581       b->AddStatement(BreakOnStatusNotOk());
582     }
583   }
584 
585   const string bn_name = ClassName(interface, ClassNames::SERVER);
586   if (options.GenLog()) {
587     b->AddLiteral(GenLogBeforeExecute(bn_name, method, true /* isServer */, false /* isNdk */),
588                   false);
589   }
590   // Call the actual method.  This is implemented by the subclass.
591   vector<unique_ptr<AstNode>> status_args;
592   status_args.emplace_back(new MethodCall(
593       method.GetName(), BuildArgList(typenames, method, false /* not for method decl */)));
594   b->AddStatement(new Statement(new MethodCall(
595       StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName),
596       ArgList(std::move(status_args)))));
597 
598   if (options.GenLog()) {
599     b->AddLiteral(GenLogAfterExecute(bn_name, interface, method, kStatusVarName, kReturnVarName,
600                                      true /* isServer */, false /* isNdk */),
601                   false);
602   }
603 
604   // Write exceptions during transaction handling to parcel.
605   if (!method.IsOneway()) {
606     b->AddStatement(new Assignment(
607         kAndroidStatusVarName,
608         StringPrintf("%s.writeToParcel(%s)", kStatusVarName, kReplyVarName)));
609     b->AddStatement(BreakOnStatusNotOk());
610     IfStatement* exception_check = new IfStatement(
611         new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
612     b->AddStatement(exception_check);
613     exception_check->OnTrue()->AddLiteral("break");
614   }
615 
616   // If we have a return value, write it first.
617   if (method.GetType().GetName() != "void") {
618     string writeMethod =
619         string(kReplyVarName) + "->" + ParcelWriteMethodOf(method.GetType(), typenames);
620     b->AddStatement(new Assignment(
621         kAndroidStatusVarName,
622         new MethodCall(writeMethod,
623                        ParcelWriteCastOf(method.GetType(), typenames, kReturnVarName))));
624     b->AddStatement(BreakOnStatusNotOk());
625   }
626   // Write each out parameter to the reply parcel.
627   for (const AidlArgument* a : method.GetOutArguments()) {
628     // Serialization looks roughly like:
629     //     _aidl_ret_status = data.WriteInt32(out_param_name);
630     //     if (_aidl_ret_status != ::android::OK) { break; }
631     const string& writeMethod = ParcelWriteMethodOf(a->GetType(), typenames);
632     b->AddStatement(new Assignment(
633         kAndroidStatusVarName,
634         new MethodCall(string(kReplyVarName) + "->" + writeMethod,
635                        ParcelWriteCastOf(a->GetType(), typenames, BuildVarName(*a)))));
636     b->AddStatement(BreakOnStatusNotOk());
637   }
638 
639   return true;
640 }
641 
HandleServerMetaTransaction(const AidlTypenames &,const AidlInterface & interface,const AidlMethod & method,const Options & options,StatementBlock * b)642 bool HandleServerMetaTransaction(const AidlTypenames&, const AidlInterface& interface,
643                                  const AidlMethod& method, const Options& options,
644                                  StatementBlock* b) {
645   CHECK(!method.IsUserDefined());
646 
647   if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
648     std::ostringstream code;
649     code << "_aidl_data.checkInterface(this);\n"
650          << "_aidl_reply->writeNoException();\n"
651          << "_aidl_reply->writeInt32(" << ClassName(interface, ClassNames::INTERFACE)
652          << "::VERSION)";
653     b->AddLiteral(code.str());
654     return true;
655   }
656   if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
657     std::ostringstream code;
658     code << "_aidl_data.checkInterface(this);\n"
659          << "_aidl_reply->writeNoException();\n"
660          << "_aidl_reply->writeUtf8AsUtf16(" << ClassName(interface, ClassNames::INTERFACE)
661          << "::HASH)";
662     b->AddLiteral(code.str());
663     return true;
664   }
665   return false;
666 }
667 
668 }  // namespace
669 
BuildServerSource(const AidlTypenames & typenames,const AidlInterface & interface,const Options & options)670 unique_ptr<Document> BuildServerSource(const AidlTypenames& typenames,
671                                        const AidlInterface& interface, const Options& options) {
672   const string bn_name = ClassName(interface, ClassNames::SERVER);
673   vector<string> include_list{
674       HeaderFile(interface, ClassNames::SERVER, false),
675       kParcelHeader,
676       kStabilityHeader,
677   };
678   if (options.GenLog()) {
679     include_list.emplace_back("chrono");
680     include_list.emplace_back("functional");
681     include_list.emplace_back("json/value.h");
682   }
683 
684   unique_ptr<ConstructorImpl> constructor{
685       new ConstructorImpl{ClassName(interface, ClassNames::SERVER), ArgList{}, {}}};
686 
687   if (interface.IsVintfStability()) {
688     constructor->GetStatementBlock()->AddLiteral("::android::internal::Stability::markVintf(this)");
689   } else {
690     constructor->GetStatementBlock()->AddLiteral(
691         "::android::internal::Stability::markCompilationUnit(this)");
692   }
693 
694   unique_ptr<MethodImpl> on_transact{new MethodImpl{
695       kAndroidStatusLiteral, bn_name, "onTransact",
696       ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
697                StringPrintf("const %s& %s", kAndroidParcelLiteral,
698                             kDataVarName),
699                StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
700                StringPrintf("uint32_t %s", kFlagsVarName)}}
701       }};
702 
703   // Declare the status_t variable
704   on_transact->GetStatementBlock()->AddLiteral(
705       StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName,
706                    kAndroidStatusOk));
707 
708   // Add the all important switch statement, but retain a pointer to it.
709   SwitchStatement* s = new SwitchStatement{kCodeVarName};
710   on_transact->GetStatementBlock()->AddStatement(s);
711 
712   // The switch statement has a case statement for each transaction code.
713   for (const auto& method : interface.GetMethods()) {
714     StatementBlock* b = s->AddCase(GetTransactionIdFor(*method));
715     if (!b) { return nullptr; }
716 
717     bool success = false;
718     if (method->IsUserDefined()) {
719       success = HandleServerTransaction(typenames, interface, *method, options, b);
720     } else {
721       success = HandleServerMetaTransaction(typenames, interface, *method, options, b);
722     }
723     if (!success) {
724       return nullptr;
725     }
726   }
727 
728   // The switch statement has a default case which defers to the super class.
729   // The superclass handles a few pre-defined transactions.
730   StatementBlock* b = s->AddCase("");
731   b->AddLiteral(StringPrintf(
732                 "%s = ::android::BBinder::onTransact(%s, %s, "
733                 "%s, %s)", kAndroidStatusVarName, kCodeVarName,
734                 kDataVarName, kReplyVarName, kFlagsVarName));
735 
736   // If we saw a null reference, we can map that to an appropriate exception.
737   IfStatement* null_check = new IfStatement(
738       new LiteralExpression(string(kAndroidStatusVarName) +
739                             " == ::android::UNEXPECTED_NULL"));
740   on_transact->GetStatementBlock()->AddStatement(null_check);
741   null_check->OnTrue()->AddStatement(new Assignment(
742       kAndroidStatusVarName,
743       StringPrintf("%s::fromExceptionCode(%s::EX_NULL_POINTER)"
744                    ".writeToParcel(%s)",
745                    kBinderStatusLiteral, kBinderStatusLiteral,
746                    kReplyVarName)));
747 
748   // Finally, the server's onTransact method just returns a status code.
749   on_transact->GetStatementBlock()->AddLiteral(
750       StringPrintf("return %s", kAndroidStatusVarName));
751   vector<unique_ptr<Declaration>> decls;
752   decls.push_back(std::move(constructor));
753   decls.push_back(std::move(on_transact));
754 
755   if (options.Version() > 0) {
756     std::ostringstream code;
757     code << "int32_t " << bn_name << "::" << kGetInterfaceVersion << "() {\n"
758          << "  return " << ClassName(interface, ClassNames::INTERFACE) << "::VERSION;\n"
759          << "}\n";
760     decls.emplace_back(new LiteralDecl(code.str()));
761   }
762   if (!options.Hash().empty()) {
763     std::ostringstream code;
764     code << "std::string " << bn_name << "::" << kGetInterfaceHash << "() {\n"
765          << "  return " << ClassName(interface, ClassNames::INTERFACE) << "::HASH;\n"
766          << "}\n";
767     decls.emplace_back(new LiteralDecl(code.str()));
768   }
769 
770   if (options.GenLog()) {
771     string code;
772     ClassName(interface, ClassNames::SERVER);
773     CodeWriterPtr writer = CodeWriter::ForString(&code);
774     (*writer) << "std::function<void(const Json::Value&)> "
775               << ClassName(interface, ClassNames::SERVER) << "::logFunc;\n";
776     writer->Close();
777     decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
778   }
779   return unique_ptr<Document>{
780       new CppSource{include_list, NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
781 }
782 
BuildInterfaceSource(const AidlTypenames & typenames,const AidlInterface & interface,const Options & options)783 unique_ptr<Document> BuildInterfaceSource(const AidlTypenames& typenames,
784                                           const AidlInterface& interface,
785                                           [[maybe_unused]] const Options& options) {
786   vector<string> include_list{
787       HeaderFile(interface, ClassNames::RAW, false),
788       HeaderFile(interface, ClassNames::CLIENT, false),
789   };
790 
791   string fq_name = ClassName(interface, ClassNames::INTERFACE);
792   if (!interface.GetPackage().empty()) {
793     fq_name = interface.GetPackage() + "." + fq_name;
794   }
795 
796   vector<unique_ptr<Declaration>> decls;
797 
798   unique_ptr<MacroDecl> meta_if{new MacroDecl{
799       "DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE",
800       ArgList{vector<string>{ClassName(interface, ClassNames::BASE), '"' + fq_name + '"'}}}};
801   decls.push_back(std::move(meta_if));
802 
803   for (const auto& constant : interface.GetConstantDeclarations()) {
804     const AidlConstantValue& value = constant->GetValue();
805     if (value.GetType() != AidlConstantValue::Type::STRING) continue;
806 
807     std::string cppType = CppNameOf(constant->GetType(), typenames);
808     unique_ptr<MethodImpl> getter(new MethodImpl("const " + cppType + "&",
809                                                  ClassName(interface, ClassNames::INTERFACE),
810                                                  constant->GetName(), {}));
811     getter->GetStatementBlock()->AddLiteral(
812         StringPrintf("static const %s value(%s)", cppType.c_str(),
813                      constant->ValueString(ConstantValueDecorator).c_str()));
814     getter->GetStatementBlock()->AddLiteral("return value");
815     decls.push_back(std::move(getter));
816   }
817 
818   return unique_ptr<Document>{new CppSource{
819       include_list,
820       NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
821 }
822 
BuildClientHeader(const AidlTypenames & typenames,const AidlInterface & interface,const Options & options)823 unique_ptr<Document> BuildClientHeader(const AidlTypenames& typenames,
824                                        const AidlInterface& interface, const Options& options) {
825   const string i_name = ClassName(interface, ClassNames::INTERFACE);
826   const string bp_name = ClassName(interface, ClassNames::CLIENT);
827 
828   vector<string> includes = {kIBinderHeader, kIInterfaceHeader, "utils/Errors.h",
829                              HeaderFile(interface, ClassNames::RAW, false)};
830 
831   unique_ptr<ConstructorDecl> constructor{new ConstructorDecl{
832       bp_name,
833       ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
834                            kImplVarName)},
835       ConstructorDecl::IS_EXPLICIT
836   }};
837   unique_ptr<ConstructorDecl> destructor{new ConstructorDecl{
838       "~" + bp_name,
839       ArgList{},
840       ConstructorDecl::IS_VIRTUAL | ConstructorDecl::IS_DEFAULT}};
841 
842   vector<unique_ptr<Declaration>> publics;
843   publics.push_back(std::move(constructor));
844   publics.push_back(std::move(destructor));
845 
846   for (const auto& method: interface.GetMethods()) {
847     if (method->IsUserDefined()) {
848       publics.push_back(BuildMethodDecl(*method, typenames, false));
849     } else {
850       publics.push_back(BuildMetaMethodDecl(*method, typenames, options, false));
851     }
852   }
853 
854   if (options.GenLog()) {
855     includes.emplace_back("chrono");      // for std::chrono::steady_clock
856     includes.emplace_back("functional");  // for std::function
857     includes.emplace_back("json/value.h");
858     publics.emplace_back(
859         new LiteralDecl{"static std::function<void(const Json::Value&)> logFunc;\n"});
860   }
861 
862   vector<unique_ptr<Declaration>> privates;
863 
864   if (options.Version() > 0) {
865     privates.emplace_back(new LiteralDecl("int32_t cached_version_ = -1;\n"));
866   }
867   if (!options.Hash().empty()) {
868     privates.emplace_back(new LiteralDecl("std::string cached_hash_ = \"-1\";\n"));
869     privates.emplace_back(new LiteralDecl("std::mutex cached_hash_mutex_;\n"));
870   }
871 
872   unique_ptr<ClassDecl> bp_class{new ClassDecl{
873       bp_name,
874       "::android::BpInterface<" + i_name + ">",
875       std::move(publics),
876       std::move(privates),
877   }};
878 
879   return unique_ptr<Document>{
880       new CppHeader{BuildHeaderGuard(interface, ClassNames::CLIENT), includes,
881                     NestInNamespaces(std::move(bp_class), interface.GetSplitPackage())}};
882 }
883 
BuildServerHeader(const AidlTypenames &,const AidlInterface & interface,const Options & options)884 unique_ptr<Document> BuildServerHeader(const AidlTypenames& /* typenames */,
885                                        const AidlInterface& interface, const Options& options) {
886   const string i_name = ClassName(interface, ClassNames::INTERFACE);
887   const string bn_name = ClassName(interface, ClassNames::SERVER);
888 
889   unique_ptr<ConstructorDecl> constructor{
890       new ConstructorDecl{bn_name, ArgList{}, ConstructorDecl::IS_EXPLICIT}};
891 
892   unique_ptr<Declaration> on_transact{new MethodDecl{
893       kAndroidStatusLiteral, "onTransact",
894       ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
895                StringPrintf("const %s& %s", kAndroidParcelLiteral,
896                             kDataVarName),
897                StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
898                StringPrintf("uint32_t %s", kFlagsVarName)}},
899       MethodDecl::IS_OVERRIDE
900   }};
901   vector<string> includes = {"binder/IInterface.h", HeaderFile(interface, ClassNames::RAW, false)};
902 
903   vector<unique_ptr<Declaration>> publics;
904   publics.push_back(std::move(constructor));
905   publics.push_back(std::move(on_transact));
906 
907   if (options.Version() > 0) {
908     std::ostringstream code;
909     code << "int32_t " << kGetInterfaceVersion << "() final override;\n";
910     publics.emplace_back(new LiteralDecl(code.str()));
911   }
912   if (!options.Hash().empty()) {
913     std::ostringstream code;
914     code << "std::string " << kGetInterfaceHash << "();\n";
915     publics.emplace_back(new LiteralDecl(code.str()));
916   }
917 
918   if (options.GenLog()) {
919     includes.emplace_back("chrono");      // for std::chrono::steady_clock
920     includes.emplace_back("functional");  // for std::function
921     includes.emplace_back("json/value.h");
922     publics.emplace_back(
923         new LiteralDecl{"static std::function<void(const Json::Value&)> logFunc;\n"});
924   }
925   unique_ptr<ClassDecl> bn_class{
926       new ClassDecl{bn_name,
927                     "::android::BnInterface<" + i_name + ">",
928                     std::move(publics),
929                     {}
930       }};
931 
932   return unique_ptr<Document>{
933       new CppHeader{BuildHeaderGuard(interface, ClassNames::SERVER), includes,
934                     NestInNamespaces(std::move(bn_class), interface.GetSplitPackage())}};
935 }
936 
BuildInterfaceHeader(const AidlTypenames & typenames,const AidlInterface & interface,const Options & options)937 unique_ptr<Document> BuildInterfaceHeader(const AidlTypenames& typenames,
938                                           const AidlInterface& interface, const Options& options) {
939   set<string> includes = {kIBinderHeader, kIInterfaceHeader, kStatusHeader, kStrongPointerHeader};
940 
941   for (const auto& method : interface.GetMethods()) {
942     for (const auto& argument : method->GetArguments()) {
943       AddHeaders(argument->GetType(), typenames, includes);
944     }
945 
946     AddHeaders(method->GetType(), typenames, includes);
947   }
948 
949   const string i_name = ClassName(interface, ClassNames::INTERFACE);
950   unique_ptr<ClassDecl> if_class{new ClassDecl{i_name, "::android::IInterface"}};
951   if_class->AddPublic(unique_ptr<Declaration>{new MacroDecl{
952       "DECLARE_META_INTERFACE",
953       ArgList{vector<string>{ClassName(interface, ClassNames::BASE)}}}});
954 
955   if (options.Version() > 0) {
956     std::ostringstream code;
957     code << "const int32_t VERSION = " << options.Version() << ";\n";
958 
959     if_class->AddPublic(unique_ptr<Declaration>(new LiteralDecl(code.str())));
960   }
961   if (!options.Hash().empty()) {
962     std::ostringstream code;
963     code << "const std::string HASH = \"" << options.Hash() << "\";\n";
964 
965     if_class->AddPublic(unique_ptr<Declaration>(new LiteralDecl(code.str())));
966   }
967 
968   std::vector<std::unique_ptr<Declaration>> string_constants;
969   unique_ptr<Enum> int_constant_enum{new Enum{"", "int32_t", false}};
970   for (const auto& constant : interface.GetConstantDeclarations()) {
971     const AidlConstantValue& value = constant->GetValue();
972 
973     switch (value.GetType()) {
974       case AidlConstantValue::Type::STRING: {
975         std::string cppType = CppNameOf(constant->GetType(), typenames);
976         unique_ptr<Declaration> getter(new MethodDecl("const " + cppType + "&", constant->GetName(),
977                                                       {}, MethodDecl::IS_STATIC));
978         string_constants.push_back(std::move(getter));
979         break;
980       }
981       case AidlConstantValue::Type::BOOLEAN:  // fall-through
982       case AidlConstantValue::Type::INT8:     // fall-through
983       case AidlConstantValue::Type::INT32: {
984         int_constant_enum->AddValue(constant->GetName(),
985                                     constant->ValueString(ConstantValueDecorator));
986         break;
987       }
988       default: {
989         LOG(FATAL) << "Unrecognized constant type: " << static_cast<int>(value.GetType());
990       }
991     }
992   }
993   if (int_constant_enum->HasValues()) {
994     if_class->AddPublic(std::move(int_constant_enum));
995   }
996   if (!string_constants.empty()) {
997     includes.insert(kString16Header);
998 
999     for (auto& string_constant : string_constants) {
1000       if_class->AddPublic(std::move(string_constant));
1001     }
1002   }
1003 
1004   if (options.GenTraces()) {
1005     includes.insert(kTraceHeader);
1006   }
1007 
1008   if (!interface.GetMethods().empty()) {
1009     for (const auto& method : interface.GetMethods()) {
1010       if (method->IsUserDefined()) {
1011         // Each method gets an enum entry and pure virtual declaration.
1012         if_class->AddPublic(BuildMethodDecl(*method, typenames, true));
1013       } else {
1014         if_class->AddPublic(BuildMetaMethodDecl(*method, typenames, options, true));
1015       }
1016     }
1017   }
1018 
1019   // Implement the default impl class.
1020   vector<unique_ptr<Declaration>> method_decls;
1021   // onAsBinder returns nullptr as this interface is not associated with a
1022   // real binder.
1023   method_decls.emplace_back(
1024       new LiteralDecl("::android::IBinder* onAsBinder() override {\n"
1025                       "  return nullptr;\n"
1026                       "}\n"));
1027   // Each interface method by default returns UNKNOWN_TRANSACTION with is
1028   // the same status that is returned by transact() when the method is
1029   // not implemented in the server side. In other words, these default
1030   // methods do nothing; they only exist to aid making a real default
1031   // impl class without having to override all methods in an interface.
1032   for (const auto& method : interface.GetMethods()) {
1033     if (method->IsUserDefined()) {
1034       std::ostringstream code;
1035       code << "::android::binder::Status " << method->GetName()
1036            << BuildArgList(typenames, *method, true, true).ToString() << " override {\n"
1037            << "  return ::android::binder::Status::fromStatusT(::android::UNKNOWN_TRANSACTION);\n"
1038            << "}\n";
1039       method_decls.emplace_back(new LiteralDecl(code.str()));
1040     } else {
1041       if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
1042         std::ostringstream code;
1043         code << "int32_t " << kGetInterfaceVersion << "() override {\n"
1044              << "  return 0;\n"
1045              << "}\n";
1046         method_decls.emplace_back(new LiteralDecl(code.str()));
1047       }
1048       if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
1049         std::ostringstream code;
1050         code << "std::string " << kGetInterfaceHash << "() override {\n"
1051              << "  return \"\";\n"
1052              << "}\n";
1053         method_decls.emplace_back(new LiteralDecl(code.str()));
1054       }
1055     }
1056   }
1057 
1058   vector<unique_ptr<Declaration>> decls;
1059   decls.emplace_back(std::move(if_class));
1060   decls.emplace_back(new ClassDecl{
1061       ClassName(interface, ClassNames::DEFAULT_IMPL), i_name, std::move(method_decls), {}});
1062 
1063   return unique_ptr<Document>{
1064       new CppHeader{BuildHeaderGuard(interface, ClassNames::INTERFACE),
1065                     vector<string>(includes.begin(), includes.end()),
1066                     NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
1067 }
1068 
BuildParcelHeader(const AidlTypenames & typenames,const AidlStructuredParcelable & parcel,const Options &)1069 std::unique_ptr<Document> BuildParcelHeader(const AidlTypenames& typenames,
1070                                             const AidlStructuredParcelable& parcel,
1071                                             const Options&) {
1072   unique_ptr<ClassDecl> parcel_class{new ClassDecl{parcel.GetName(), "::android::Parcelable"}};
1073 
1074   set<string> includes = {kStatusHeader, kParcelHeader};
1075   includes.insert("tuple");
1076   for (const auto& variable : parcel.GetFields()) {
1077     AddHeaders(variable->GetType(), typenames, includes);
1078   }
1079 
1080   set<string> operators = {"<", ">", "==", ">=", "<=", "!="};
1081   for (const auto& op : operators) {
1082     std::ostringstream operator_code;
1083     std::vector<std::string> variable_name;
1084     std::vector<std::string> rhs_variable_name;
1085     for (const auto& variable : parcel.GetFields()) {
1086       variable_name.push_back(variable->GetName());
1087       rhs_variable_name.push_back("rhs." + variable->GetName());
1088     }
1089 
1090     operator_code << "inline bool operator" << op << "(const " << parcel.GetName()
1091                   << "& rhs) const {\n"
1092                   << "  return "
1093                   << "std::tie(" << Join(variable_name, ", ") << ")" << op << "std::tie("
1094                   << Join(rhs_variable_name, ", ") << ")"
1095                   << ";\n"
1096                   << "}\n";
1097 
1098     parcel_class->AddPublic(std::unique_ptr<LiteralDecl>(new LiteralDecl(operator_code.str())));
1099   }
1100   for (const auto& variable : parcel.GetFields()) {
1101 
1102     std::ostringstream out;
1103     std::string cppType = CppNameOf(variable->GetType(), typenames);
1104     out << cppType.c_str() << " " << variable->GetName().c_str();
1105     if (variable->GetDefaultValue()) {
1106       out << " = " << cppType.c_str() << "(" << variable->ValueString(ConstantValueDecorator)
1107           << ")";
1108     }
1109     out << ";\n";
1110 
1111     parcel_class->AddPublic(std::unique_ptr<LiteralDecl>(new LiteralDecl(out.str())));
1112   }
1113 
1114   if (parcel.IsVintfStability()) {
1115     parcel_class->AddPublic(std::unique_ptr<LiteralDecl>(
1116         new LiteralDecl("::android::Parcelable::Stability getStability() const override { return "
1117                         "::android::Parcelable::Stability::STABILITY_VINTF; }\n")));
1118   }
1119 
1120   unique_ptr<MethodDecl> read(new MethodDecl(kAndroidStatusLiteral, "readFromParcel",
1121                                              ArgList("const ::android::Parcel* _aidl_parcel"),
1122                                              MethodDecl::IS_OVERRIDE | MethodDecl::IS_FINAL));
1123   parcel_class->AddPublic(std::move(read));
1124   unique_ptr<MethodDecl> write(new MethodDecl(
1125       kAndroidStatusLiteral, "writeToParcel", ArgList("::android::Parcel* _aidl_parcel"),
1126       MethodDecl::IS_OVERRIDE | MethodDecl::IS_CONST | MethodDecl::IS_FINAL));
1127   parcel_class->AddPublic(std::move(write));
1128 
1129   return unique_ptr<Document>{new CppHeader{
1130       BuildHeaderGuard(parcel, ClassNames::RAW), vector<string>(includes.begin(), includes.end()),
1131       NestInNamespaces(std::move(parcel_class), parcel.GetSplitPackage())}};
1132 }
BuildParcelSource(const AidlTypenames & typenames,const AidlStructuredParcelable & parcel,const Options &)1133 std::unique_ptr<Document> BuildParcelSource(const AidlTypenames& typenames,
1134                                             const AidlStructuredParcelable& parcel,
1135                                             const Options&) {
1136   unique_ptr<MethodImpl> read{new MethodImpl{kAndroidStatusLiteral, parcel.GetName(),
1137                                              "readFromParcel",
1138                                              ArgList("const ::android::Parcel* _aidl_parcel")}};
1139   StatementBlock* read_block = read->GetStatementBlock();
1140   read_block->AddLiteral(
1141       StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName, kAndroidStatusOk));
1142 
1143   read_block->AddLiteral(
1144       "size_t _aidl_start_pos = _aidl_parcel->dataPosition();\n"
1145       "int32_t _aidl_parcelable_raw_size = _aidl_parcel->readInt32();\n"
1146       "if (_aidl_parcelable_raw_size < 0) return ::android::BAD_VALUE;\n"
1147       "size_t _aidl_parcelable_size = static_cast<size_t>(_aidl_parcelable_raw_size);\n");
1148 
1149   for (const auto& variable : parcel.GetFields()) {
1150     string method = ParcelReadMethodOf(variable->GetType(), typenames);
1151 
1152     read_block->AddStatement(new Assignment(
1153         kAndroidStatusVarName, new MethodCall(StringPrintf("_aidl_parcel->%s", method.c_str()),
1154                                               ParcelReadCastOf(variable->GetType(), typenames,
1155                                                                "&" + variable->GetName()))));
1156     read_block->AddStatement(ReturnOnStatusNotOk());
1157     read_block->AddLiteral(StringPrintf(
1158         "if (_aidl_parcel->dataPosition() - _aidl_start_pos >= _aidl_parcelable_size) {\n"
1159         "  _aidl_parcel->setDataPosition(_aidl_start_pos + _aidl_parcelable_size);\n"
1160         "  return %s;\n"
1161         "}",
1162         kAndroidStatusVarName));
1163   }
1164   read_block->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
1165 
1166   unique_ptr<MethodImpl> write{
1167       new MethodImpl{kAndroidStatusLiteral, parcel.GetName(), "writeToParcel",
1168                      ArgList("::android::Parcel* _aidl_parcel"), true /*const*/}};
1169   StatementBlock* write_block = write->GetStatementBlock();
1170   write_block->AddLiteral(
1171       StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName, kAndroidStatusOk));
1172 
1173   write_block->AddLiteral(
1174       "auto _aidl_start_pos = _aidl_parcel->dataPosition();\n"
1175       "_aidl_parcel->writeInt32(0);");
1176 
1177   for (const auto& variable : parcel.GetFields()) {
1178     string method = ParcelWriteMethodOf(variable->GetType(), typenames);
1179     write_block->AddStatement(new Assignment(
1180         kAndroidStatusVarName,
1181         new MethodCall(StringPrintf("_aidl_parcel->%s", method.c_str()),
1182                        ParcelWriteCastOf(variable->GetType(), typenames, variable->GetName()))));
1183     write_block->AddStatement(ReturnOnStatusNotOk());
1184   }
1185 
1186   write_block->AddLiteral(
1187       "auto _aidl_end_pos = _aidl_parcel->dataPosition();\n"
1188       "_aidl_parcel->setDataPosition(_aidl_start_pos);\n"
1189       "_aidl_parcel->writeInt32(_aidl_end_pos - _aidl_start_pos);\n"
1190       "_aidl_parcel->setDataPosition(_aidl_end_pos);");
1191   write_block->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
1192 
1193   vector<unique_ptr<Declaration>> file_decls;
1194   file_decls.push_back(std::move(read));
1195   file_decls.push_back(std::move(write));
1196 
1197   set<string> includes = {};
1198   AddHeaders(parcel, includes);
1199 
1200   return unique_ptr<Document>{
1201       new CppSource{vector<string>(includes.begin(), includes.end()),
1202                     NestInNamespaces(std::move(file_decls), parcel.GetSplitPackage())}};
1203 }
1204 
GenerateEnumToString(const AidlTypenames & typenames,const AidlEnumDeclaration & enum_decl)1205 std::string GenerateEnumToString(const AidlTypenames& typenames,
1206                                  const AidlEnumDeclaration& enum_decl) {
1207   std::ostringstream code;
1208   code << "static inline std::string toString(" << enum_decl.GetName() << " val) {\n";
1209   code << "  switch(val) {\n";
1210   std::set<std::string> unique_cases;
1211   for (const auto& enumerator : enum_decl.GetEnumerators()) {
1212     std::string c = enumerator->ValueString(enum_decl.GetBackingType(), ConstantValueDecorator);
1213     // Only add a case if its value has not yet been used in the switch
1214     // statement. C++ does not allow multiple cases with the same value, but
1215     // enums does allow this. In this scenario, the first declared
1216     // enumerator with the given value is printed.
1217     if (unique_cases.count(c) == 0) {
1218       unique_cases.insert(c);
1219       code << "  case " << enum_decl.GetName() << "::" << enumerator->GetName() << ":\n";
1220       code << "    return \"" << enumerator->GetName() << "\";\n";
1221     }
1222   }
1223   code << "  default:\n";
1224   code << "    return std::to_string(static_cast<"
1225        << CppNameOf(enum_decl.GetBackingType(), typenames) << ">(val));\n";
1226   code << "  }\n";
1227   code << "}\n";
1228   return code.str();
1229 }
1230 
BuildEnumHeader(const AidlTypenames & typenames,const AidlEnumDeclaration & enum_decl)1231 std::unique_ptr<Document> BuildEnumHeader(const AidlTypenames& typenames,
1232                                           const AidlEnumDeclaration& enum_decl) {
1233   std::unique_ptr<Enum> generated_enum{
1234       new Enum{enum_decl.GetName(), CppNameOf(enum_decl.GetBackingType(), typenames), true}};
1235   for (const auto& enumerator : enum_decl.GetEnumerators()) {
1236     generated_enum->AddValue(
1237         enumerator->GetName(),
1238         enumerator->ValueString(enum_decl.GetBackingType(), ConstantValueDecorator));
1239   }
1240 
1241   std::set<std::string> includes = {
1242       "array",
1243       "binder/Enums.h",
1244       "string",
1245   };
1246   AddHeaders(enum_decl.GetBackingType(), typenames, includes);
1247 
1248   std::vector<std::unique_ptr<Declaration>> decls1;
1249   decls1.push_back(std::move(generated_enum));
1250   decls1.push_back(std::make_unique<LiteralDecl>(GenerateEnumToString(typenames, enum_decl)));
1251 
1252   std::vector<std::unique_ptr<Declaration>> decls2;
1253   decls2.push_back(std::make_unique<LiteralDecl>(GenerateEnumValues(enum_decl, {""})));
1254 
1255   return unique_ptr<Document>{
1256       new CppHeader{BuildHeaderGuard(enum_decl, ClassNames::RAW),
1257                     vector<string>(includes.begin(), includes.end()),
1258                     Append(NestInNamespaces(std::move(decls1), enum_decl.GetSplitPackage()),
1259                            NestInNamespaces(std::move(decls2), {"android", "internal"}))}};
1260 }
1261 
WriteHeader(const Options & options,const AidlTypenames & typenames,const AidlInterface & interface,const IoDelegate & io_delegate,ClassNames header_type)1262 bool WriteHeader(const Options& options, const AidlTypenames& typenames,
1263                  const AidlInterface& interface, const IoDelegate& io_delegate,
1264                  ClassNames header_type) {
1265   unique_ptr<Document> header;
1266   switch (header_type) {
1267     case ClassNames::INTERFACE:
1268       header = BuildInterfaceHeader(typenames, interface, options);
1269       header_type = ClassNames::RAW;
1270       break;
1271     case ClassNames::CLIENT:
1272       header = BuildClientHeader(typenames, interface, options);
1273       break;
1274     case ClassNames::SERVER:
1275       header = BuildServerHeader(typenames, interface, options);
1276       break;
1277     default:
1278       LOG(FATAL) << "aidl internal error";
1279   }
1280   if (!header) {
1281     LOG(ERROR) << "aidl internal error: Failed to generate header.";
1282     return false;
1283   }
1284 
1285   const string header_path = options.OutputHeaderDir() + HeaderFile(interface, header_type);
1286   unique_ptr<CodeWriter> code_writer(io_delegate.GetCodeWriter(header_path));
1287   header->Write(code_writer.get());
1288 
1289   const bool success = code_writer->Close();
1290   if (!success) {
1291     io_delegate.RemovePath(header_path);
1292   }
1293 
1294   return success;
1295 }
1296 
1297 }  // namespace internals
1298 
1299 using namespace internals;
1300 
GenerateCppInterface(const string & output_file,const Options & options,const AidlTypenames & typenames,const AidlInterface & interface,const IoDelegate & io_delegate)1301 bool GenerateCppInterface(const string& output_file, const Options& options,
1302                           const AidlTypenames& typenames, const AidlInterface& interface,
1303                           const IoDelegate& io_delegate) {
1304   auto interface_src = BuildInterfaceSource(typenames, interface, options);
1305   auto client_src = BuildClientSource(typenames, interface, options);
1306   auto server_src = BuildServerSource(typenames, interface, options);
1307 
1308   if (!interface_src || !client_src || !server_src) {
1309     return false;
1310   }
1311 
1312   if (!WriteHeader(options, typenames, interface, io_delegate, ClassNames::INTERFACE) ||
1313       !WriteHeader(options, typenames, interface, io_delegate, ClassNames::CLIENT) ||
1314       !WriteHeader(options, typenames, interface, io_delegate, ClassNames::SERVER)) {
1315     return false;
1316   }
1317 
1318   unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(output_file);
1319   interface_src->Write(writer.get());
1320   client_src->Write(writer.get());
1321   server_src->Write(writer.get());
1322 
1323   const bool success = writer->Close();
1324   if (!success) {
1325     io_delegate.RemovePath(output_file);
1326   }
1327 
1328   return success;
1329 }
1330 
GenerateCppParcel(const string & output_file,const Options & options,const AidlTypenames & typenames,const AidlStructuredParcelable & parcelable,const IoDelegate & io_delegate)1331 bool GenerateCppParcel(const string& output_file, const Options& options,
1332                        const AidlTypenames& typenames, const AidlStructuredParcelable& parcelable,
1333                        const IoDelegate& io_delegate) {
1334   auto header = BuildParcelHeader(typenames, parcelable, options);
1335   auto source = BuildParcelSource(typenames, parcelable, options);
1336 
1337   if (!header || !source) {
1338     return false;
1339   }
1340 
1341   const string header_path = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::RAW);
1342   unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1343   header->Write(header_writer.get());
1344   CHECK(header_writer->Close());
1345 
1346   // TODO(b/111362593): no unecessary files just to have consistent output with interfaces
1347   const string bp_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::CLIENT);
1348   unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1349   bp_writer->Write("#error TODO(b/111362593) parcelables do not have bp classes");
1350   CHECK(bp_writer->Close());
1351   const string bn_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::SERVER);
1352   unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1353   bn_writer->Write("#error TODO(b/111362593) parcelables do not have bn classes");
1354   CHECK(bn_writer->Close());
1355 
1356   unique_ptr<CodeWriter> source_writer = io_delegate.GetCodeWriter(output_file);
1357   source->Write(source_writer.get());
1358   CHECK(source_writer->Close());
1359 
1360   return true;
1361 }
1362 
GenerateCppParcelDeclaration(const std::string & filename,const Options & options,const AidlParcelable & parcelable,const IoDelegate & io_delegate)1363 bool GenerateCppParcelDeclaration(const std::string& filename, const Options& options,
1364                                   const AidlParcelable& parcelable, const IoDelegate& io_delegate) {
1365   CodeWriterPtr source_writer = io_delegate.GetCodeWriter(filename);
1366   *source_writer
1367       << "// This file is intentionally left blank as placeholder for parcel declaration.\n";
1368   CHECK(source_writer->Close());
1369 
1370   // TODO(b/111362593): no unecessary files just to have consistent output with interfaces
1371   const string header_path = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::RAW);
1372   unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1373   header_writer->Write("#error TODO(b/111362593) parcelables do not have headers");
1374   CHECK(header_writer->Close());
1375   const string bp_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::CLIENT);
1376   unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1377   bp_writer->Write("#error TODO(b/111362593) parcelables do not have bp classes");
1378   CHECK(bp_writer->Close());
1379   const string bn_header = options.OutputHeaderDir() + HeaderFile(parcelable, ClassNames::SERVER);
1380   unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1381   bn_writer->Write("#error TODO(b/111362593) parcelables do not have bn classes");
1382   CHECK(bn_writer->Close());
1383 
1384   return true;
1385 }
1386 
GenerateCppEnumDeclaration(const std::string & filename,const Options & options,const AidlTypenames & typenames,const AidlEnumDeclaration & enum_decl,const IoDelegate & io_delegate)1387 bool GenerateCppEnumDeclaration(const std::string& filename, const Options& options,
1388                                 const AidlTypenames& typenames,
1389                                 const AidlEnumDeclaration& enum_decl,
1390                                 const IoDelegate& io_delegate) {
1391   auto header = BuildEnumHeader(typenames, enum_decl);
1392   if (!header) return false;
1393 
1394   const string header_path = options.OutputHeaderDir() + HeaderFile(enum_decl, ClassNames::RAW);
1395   unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
1396   header->Write(header_writer.get());
1397   CHECK(header_writer->Close());
1398 
1399   // TODO(b/111362593): no unnecessary files just to have consistent output with interfaces
1400   CodeWriterPtr source_writer = io_delegate.GetCodeWriter(filename);
1401   *source_writer
1402       << "// This file is intentionally left blank as placeholder for enum declaration.\n";
1403   CHECK(source_writer->Close());
1404   const string bp_header = options.OutputHeaderDir() + HeaderFile(enum_decl, ClassNames::CLIENT);
1405   unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
1406   bp_writer->Write("#error TODO(b/111362593) enums do not have bp classes");
1407   CHECK(bp_writer->Close());
1408   const string bn_header = options.OutputHeaderDir() + HeaderFile(enum_decl, ClassNames::SERVER);
1409   unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
1410   bn_writer->Write("#error TODO(b/111362593) enums do not have bn classes");
1411   CHECK(bn_writer->Close());
1412 
1413   return true;
1414 }
1415 
GenerateCpp(const string & output_file,const Options & options,const AidlTypenames & typenames,const AidlDefinedType & defined_type,const IoDelegate & io_delegate)1416 bool GenerateCpp(const string& output_file, const Options& options, const AidlTypenames& typenames,
1417                  const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
1418   const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
1419   if (parcelable != nullptr) {
1420     return GenerateCppParcel(output_file, options, typenames, *parcelable, io_delegate);
1421   }
1422 
1423   const AidlParcelable* parcelable_decl = defined_type.AsParcelable();
1424   if (parcelable_decl != nullptr) {
1425     return GenerateCppParcelDeclaration(output_file, options, *parcelable_decl, io_delegate);
1426   }
1427 
1428   const AidlEnumDeclaration* enum_decl = defined_type.AsEnumDeclaration();
1429   if (enum_decl != nullptr) {
1430     return GenerateCppEnumDeclaration(output_file, options, typenames, *enum_decl, io_delegate);
1431   }
1432 
1433   const AidlInterface* interface = defined_type.AsInterface();
1434   if (interface != nullptr) {
1435     return GenerateCppInterface(output_file, options, typenames, *interface, io_delegate);
1436   }
1437 
1438   CHECK(false) << "Unrecognized type sent for cpp generation.";
1439   return false;
1440 }
1441 
1442 }  // namespace cpp
1443 }  // namespace aidl
1444 }  // namespace android
1445