• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018, 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_ndk.h"
18 
19 #include "aidl.h"
20 #include "aidl_language.h"
21 #include "aidl_to_cpp_common.h"
22 #include "aidl_to_ndk.h"
23 
24 #include <android-base/logging.h>
25 
26 namespace android {
27 namespace aidl {
28 namespace ndk {
29 
30 static constexpr const char* kClazz = "_g_aidl_clazz";
31 static constexpr const char* kDescriptor = "descriptor";
32 static constexpr const char* kVersion = "version";
33 static constexpr const char* kCacheVariable = "_aidl_cached_value";
34 
35 using namespace internals;
36 using cpp::ClassNames;
37 
GenerateNdkInterface(const string & output_file,const Options & options,const AidlTypenames & types,const AidlInterface & defined_type,const IoDelegate & io_delegate)38 void GenerateNdkInterface(const string& output_file, const Options& options,
39                           const AidlTypenames& types, const AidlInterface& defined_type,
40                           const IoDelegate& io_delegate) {
41   const string i_header = options.OutputHeaderDir() + NdkHeaderFile(defined_type, ClassNames::RAW);
42   unique_ptr<CodeWriter> i_writer(io_delegate.GetCodeWriter(i_header));
43   GenerateInterfaceHeader(*i_writer, types, defined_type, options);
44   CHECK(i_writer->Close());
45 
46   const string bp_header =
47       options.OutputHeaderDir() + NdkHeaderFile(defined_type, ClassNames::CLIENT);
48   unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
49   GenerateClientHeader(*bp_writer, types, defined_type, options);
50   CHECK(bp_writer->Close());
51 
52   const string bn_header =
53       options.OutputHeaderDir() + NdkHeaderFile(defined_type, ClassNames::SERVER);
54   unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
55   GenerateServerHeader(*bn_writer, types, defined_type, options);
56   CHECK(bn_writer->Close());
57 
58   unique_ptr<CodeWriter> source_writer = io_delegate.GetCodeWriter(output_file);
59   GenerateSource(*source_writer, types, defined_type, options);
60   CHECK(source_writer->Close());
61 }
62 
GenerateNdkParcel(const string & output_file,const Options & options,const AidlTypenames & types,const AidlStructuredParcelable & defined_type,const IoDelegate & io_delegate)63 void GenerateNdkParcel(const string& output_file, const Options& options,
64                        const AidlTypenames& types, const AidlStructuredParcelable& defined_type,
65                        const IoDelegate& io_delegate) {
66   const string header_path =
67       options.OutputHeaderDir() + NdkHeaderFile(defined_type, ClassNames::RAW);
68   unique_ptr<CodeWriter> header_writer(io_delegate.GetCodeWriter(header_path));
69   GenerateParcelHeader(*header_writer, types, defined_type, options);
70   CHECK(header_writer->Close());
71 
72   const string bp_header =
73       options.OutputHeaderDir() + NdkHeaderFile(defined_type, ClassNames::CLIENT);
74   unique_ptr<CodeWriter> bp_writer(io_delegate.GetCodeWriter(bp_header));
75   *bp_writer << "#error TODO(b/111362593) defined_types do not have bp classes\n";
76   CHECK(bp_writer->Close());
77 
78   const string bn_header =
79       options.OutputHeaderDir() + NdkHeaderFile(defined_type, ClassNames::SERVER);
80   unique_ptr<CodeWriter> bn_writer(io_delegate.GetCodeWriter(bn_header));
81   *bn_writer << "#error TODO(b/111362593) defined_types do not have bn classes\n";
82   CHECK(bn_writer->Close());
83 
84   unique_ptr<CodeWriter> source_writer = io_delegate.GetCodeWriter(output_file);
85   GenerateParcelSource(*source_writer, types, defined_type, options);
86   CHECK(source_writer->Close());
87 }
88 
GenerateNdkParcelDeclaration(const std::string & filename,const IoDelegate & io_delegate)89 void GenerateNdkParcelDeclaration(const std::string& filename, const IoDelegate& io_delegate) {
90   CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
91   *code_writer
92       << "// This file is intentionally left blank as placeholder for parcel declaration.\n";
93   CHECK(code_writer->Close());
94 }
95 
GenerateNdk(const string & output_file,const Options & options,const AidlTypenames & types,const AidlDefinedType & defined_type,const IoDelegate & io_delegate)96 void GenerateNdk(const string& output_file, const Options& options, const AidlTypenames& types,
97                  const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
98   const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
99   if (parcelable != nullptr) {
100     GenerateNdkParcel(output_file, options, types, *parcelable, io_delegate);
101     return;
102   }
103 
104   const AidlParcelable* parcelable_decl = defined_type.AsParcelable();
105   if (parcelable_decl != nullptr) {
106     GenerateNdkParcelDeclaration(output_file, io_delegate);
107     return;
108   }
109 
110   const AidlInterface* interface = defined_type.AsInterface();
111   if (interface != nullptr) {
112     GenerateNdkInterface(output_file, options, types, *interface, io_delegate);
113     return;
114   }
115 
116   CHECK(false) << "Unrecognized type sent for cpp generation.";
117 }
118 namespace internals {
119 
EnterNdkNamespace(CodeWriter & out,const AidlDefinedType & defined_type)120 void EnterNdkNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
121   out << "namespace aidl {\n";
122   cpp::EnterNamespace(out, defined_type);
123 }
LeaveNdkNamespace(CodeWriter & out,const AidlDefinedType & defined_type)124 void LeaveNdkNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
125   cpp::LeaveNamespace(out, defined_type);
126   out << "}  // namespace aidl\n";
127 }
128 
StatusCheckGoto(CodeWriter & out)129 static void StatusCheckGoto(CodeWriter& out) {
130   out << "if (_aidl_ret_status != STATUS_OK) goto _aidl_error;\n\n";
131 }
StatusCheckBreak(CodeWriter & out)132 static void StatusCheckBreak(CodeWriter& out) {
133   out << "if (_aidl_ret_status != STATUS_OK) break;\n\n";
134 }
StatusCheckReturn(CodeWriter & out)135 static void StatusCheckReturn(CodeWriter& out) {
136   out << "if (_aidl_ret_status != STATUS_OK) return _aidl_ret_status;\n\n";
137 }
138 
GenerateHeaderIncludes(CodeWriter & out,const AidlTypenames & types,const AidlDefinedType & defined_type)139 static void GenerateHeaderIncludes(CodeWriter& out, const AidlTypenames& types,
140                                    const AidlDefinedType& defined_type) {
141   out << "#include <android/binder_parcel_utils.h>\n";
142 
143   types.IterateTypes([&](const AidlDefinedType& other_defined_type) {
144     if (&other_defined_type == &defined_type) return;
145 
146     if (other_defined_type.AsInterface() != nullptr) {
147       out << "#include <"
148           << NdkHeaderFile(other_defined_type, ClassNames::RAW, false /*use_os_sep*/) << ">\n";
149     } else if (other_defined_type.AsStructuredParcelable() != nullptr) {
150       out << "#include <"
151           << NdkHeaderFile(other_defined_type, ClassNames::BASE, false /*use_os_sep*/) << ">\n";
152     } else if (other_defined_type.AsParcelable() != nullptr) {
153       out << "#include \"" << other_defined_type.AsParcelable()->GetCppHeader() << "\"\n";
154     } else {
155       AIDL_FATAL(defined_type) << "Unrecognized type.";
156     }
157   });
158 }
GenerateSourceIncludes(CodeWriter & out,const AidlTypenames & types,const AidlDefinedType &)159 static void GenerateSourceIncludes(CodeWriter& out, const AidlTypenames& types,
160                                    const AidlDefinedType& /*defined_type*/) {
161   types.IterateTypes([&](const AidlDefinedType& a_defined_type) {
162     if (a_defined_type.AsInterface() != nullptr) {
163       out << "#include <" << NdkHeaderFile(a_defined_type, ClassNames::CLIENT, false /*use_os_sep*/)
164           << ">\n";
165       out << "#include <" << NdkHeaderFile(a_defined_type, ClassNames::SERVER, false /*use_os_sep*/)
166           << ">\n";
167       out << "#include <" << NdkHeaderFile(a_defined_type, ClassNames::RAW, false /*use_os_sep*/)
168           << ">\n";
169     }
170   });
171 }
172 
GenerateConstantDeclarations(CodeWriter & out,const AidlInterface & interface)173 static void GenerateConstantDeclarations(CodeWriter& out, const AidlInterface& interface) {
174   for (const auto& constant : interface.GetConstantDeclarations()) {
175     const AidlConstantValue& value = constant->GetValue();
176     if (value.GetType() == AidlConstantValue::Type::STRING) {
177       out << "static const char* " << constant->GetName() << ";\n";
178     }
179   }
180   out << "\n";
181 
182   bool hasIntegralConstant = false;
183   for (const auto& constant : interface.GetConstantDeclarations()) {
184     const AidlConstantValue& value = constant->GetValue();
185     if (value.GetType() == AidlConstantValue::Type::HEXIDECIMAL ||
186         value.GetType() == AidlConstantValue::Type::INTEGRAL) {
187       hasIntegralConstant = true;
188       break;
189     }
190   }
191 
192   if (hasIntegralConstant) {
193     out << "enum : int32_t {\n";
194     out.Indent();
195     for (const auto& constant : interface.GetConstantDeclarations()) {
196       const AidlConstantValue& value = constant->GetValue();
197       if (value.GetType() == AidlConstantValue::Type::HEXIDECIMAL ||
198           value.GetType() == AidlConstantValue::Type::INTEGRAL) {
199         out << constant->GetName() << " = " << constant->ValueString(AidlConstantValueDecorator)
200             << ",\n";
201       }
202     }
203     out.Dedent();
204     out << "};\n";
205   }
206 }
GenerateConstantDefinitions(CodeWriter & out,const AidlInterface & interface)207 static void GenerateConstantDefinitions(CodeWriter& out, const AidlInterface& interface) {
208   const std::string clazz = ClassName(interface, ClassNames::INTERFACE);
209 
210   for (const auto& constant : interface.GetConstantDeclarations()) {
211     const AidlConstantValue& value = constant->GetValue();
212     if (value.GetType() == AidlConstantValue::Type::STRING) {
213       out << "const char* " << clazz << "::" << constant->GetName() << " = "
214           << constant->ValueString(AidlConstantValueDecorator) << ";\n";
215     }
216   }
217 }
218 
GenerateSource(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)219 void GenerateSource(CodeWriter& out, const AidlTypenames& types, const AidlInterface& defined_type,
220                     const Options& options) {
221   GenerateSourceIncludes(out, types, defined_type);
222   out << "\n";
223 
224   EnterNdkNamespace(out, defined_type);
225   GenerateClassSource(out, types, defined_type, options);
226   GenerateClientSource(out, types, defined_type, options);
227   GenerateServerSource(out, types, defined_type, options);
228   GenerateInterfaceSource(out, types, defined_type, options);
229   LeaveNdkNamespace(out, defined_type);
230 }
231 
MethodId(const AidlMethod & m)232 static std::string MethodId(const AidlMethod& m) {
233   return "(FIRST_CALL_TRANSACTION + " + std::to_string(m.GetId()) + " /*" + m.GetName() + "*/)";
234 }
235 
GenerateClientMethodDefinition(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const AidlMethod & method,const std::optional<std::string> return_value_cached_to,const Options & options)236 static void GenerateClientMethodDefinition(CodeWriter& out, const AidlTypenames& types,
237                                            const AidlInterface& defined_type,
238                                            const AidlMethod& method,
239                                            const std::optional<std::string> return_value_cached_to,
240                                            const Options& options) {
241   const std::string clazz = ClassName(defined_type, ClassNames::CLIENT);
242 
243   out << NdkMethodDecl(types, method, clazz) << " {\n";
244   out.Indent();
245   out << "binder_status_t _aidl_ret_status = STATUS_OK;\n";
246   out << "::ndk::ScopedAStatus _aidl_status;\n";
247 
248   if (return_value_cached_to) {
249     out << "if (" << *return_value_cached_to << " != -1) {\n";
250     out.Indent();
251     out << "*_aidl_return = " << *return_value_cached_to << ";\n"
252         << "_aidl_status.set(AStatus_fromStatus(_aidl_ret_status));\n"
253         << "return _aidl_status;\n";
254     out.Dedent();
255     out << "}\n";
256   }
257   out << "::ndk::ScopedAParcel _aidl_in;\n";
258   out << "::ndk::ScopedAParcel _aidl_out;\n";
259   out << "\n";
260 
261   if (options.GenLog()) {
262     out << cpp::GenLogBeforeExecute(ClassName(defined_type, ClassNames::CLIENT), method,
263                                     false /* isServer */, true /* isNdk */);
264   }
265 
266   out << "_aidl_ret_status = AIBinder_prepareTransaction(asBinder().get(), _aidl_in.getR());\n";
267   StatusCheckGoto(out);
268 
269   for (const auto& arg : method.GetArguments()) {
270     const std::string var_name = cpp::BuildVarName(*arg);
271 
272     if (arg->IsIn()) {
273       out << "_aidl_ret_status = ";
274       const std::string prefix = (arg->IsOut() ? "*" : "");
275       WriteToParcelFor({out, types, arg->GetType(), "_aidl_in.get()", prefix + var_name});
276       out << ";\n";
277       StatusCheckGoto(out);
278     } else if (arg->IsOut() && arg->GetType().IsArray()) {
279       out << "_aidl_ret_status = ::ndk::AParcel_writeVectorSize(_aidl_in.get(), *" << var_name
280           << ");\n";
281     }
282   }
283   out << "_aidl_ret_status = AIBinder_transact(\n";
284   out.Indent();
285   out << "asBinder().get(),\n";
286   out << MethodId(method) << ",\n";
287   out << "_aidl_in.getR(),\n";
288   out << "_aidl_out.getR(),\n";
289   out << (method.IsOneway() ? "FLAG_ONEWAY" : "0") << ");\n";
290   out.Dedent();
291 
292   // If the method is not implmented in the server side but the client has
293   // provided the default implementation, call it instead of failing hard.
294   const std::string iface = ClassName(defined_type, ClassNames::INTERFACE);
295   out << "if (_aidl_ret_status == STATUS_UNKNOWN_TRANSACTION && ";
296   out << iface << "::getDefaultImpl()) {\n";
297   out.Indent();
298   out << "return " << iface << "::getDefaultImpl()->" << method.GetName() << "(";
299   out << NdkArgList(types, method, FormatArgNameOnly) << ");\n";
300   out.Dedent();
301   out << "}\n";
302 
303   StatusCheckGoto(out);
304 
305   if (!method.IsOneway()) {
306     out << "_aidl_ret_status = AParcel_readStatusHeader(_aidl_out.get(), _aidl_status.getR());\n";
307     StatusCheckGoto(out);
308 
309     out << "if (!AStatus_isOk(_aidl_status.get())) return _aidl_status;\n\n";
310   }
311 
312   if (method.GetType().GetName() != "void") {
313     out << "_aidl_ret_status = ";
314     ReadFromParcelFor({out, types, method.GetType(), "_aidl_out.get()", "_aidl_return"});
315     out << ";\n";
316     StatusCheckGoto(out);
317     if (return_value_cached_to) {
318       out << *return_value_cached_to << " = *_aidl_return;\n";
319     }
320   }
321   for (const AidlArgument* arg : method.GetOutArguments()) {
322     out << "_aidl_ret_status = ";
323     ReadFromParcelFor({out, types, arg->GetType(), "_aidl_out.get()", cpp::BuildVarName(*arg)});
324     out << ";\n";
325     StatusCheckGoto(out);
326   }
327 
328   out << "_aidl_error:\n";
329   out << "_aidl_status.set(AStatus_fromStatus(_aidl_ret_status));\n";
330   if (options.GenLog()) {
331     out << cpp::GenLogAfterExecute(ClassName(defined_type, ClassNames::CLIENT), defined_type,
332                                    method, "_aidl_status", "_aidl_return", false /* isServer */,
333                                    true /* isNdk */);
334   }
335   out << "return _aidl_status;\n";
336   out.Dedent();
337   out << "}\n";
338 }
339 
GenerateServerCaseDefinition(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const AidlMethod & method,const Options & options)340 static void GenerateServerCaseDefinition(CodeWriter& out, const AidlTypenames& types,
341                                          const AidlInterface& defined_type,
342                                          const AidlMethod& method, const Options& options) {
343   out << "case " << MethodId(method) << ": {\n";
344   out.Indent();
345   for (const auto& arg : method.GetArguments()) {
346     out << NdkNameOf(types, arg->GetType(), StorageMode::STACK) << " " << cpp::BuildVarName(*arg)
347         << ";\n";
348   }
349   if (method.GetType().GetName() != "void") {
350     out << NdkNameOf(types, method.GetType(), StorageMode::STACK) << " _aidl_return;\n";
351   }
352   out << "\n";
353 
354   for (const auto& arg : method.GetArguments()) {
355     const std::string var_name = cpp::BuildVarName(*arg);
356 
357     if (arg->IsIn()) {
358       out << "_aidl_ret_status = ";
359       ReadFromParcelFor({out, types, arg->GetType(), "_aidl_in", "&" + var_name});
360       out << ";\n";
361       StatusCheckBreak(out);
362     } else if (arg->IsOut() && arg->GetType().IsArray()) {
363       out << "_aidl_ret_status = ::ndk::AParcel_resizeVector(_aidl_in, &" << var_name << ");\n";
364     }
365   }
366   if (options.GenLog()) {
367     out << cpp::GenLogBeforeExecute(ClassName(defined_type, ClassNames::SERVER), method,
368                                     true /* isServer */, true /* isNdk */);
369   }
370   out << "::ndk::ScopedAStatus _aidl_status = _aidl_impl->" << method.GetName() << "("
371       << NdkArgList(types, method, FormatArgForCall) << ");\n";
372 
373   if (options.GenLog()) {
374     out << cpp::GenLogAfterExecute(ClassName(defined_type, ClassNames::SERVER), defined_type,
375                                    method, "_aidl_status", "_aidl_return", true /* isServer */,
376                                    true /* isNdk */);
377   }
378   if (method.IsOneway()) {
379     // For a oneway transaction, the kernel will have already returned a result. This is for the
380     // in-process case when a oneway transaction is parceled/unparceled in the same process.
381     out << "_aidl_ret_status = STATUS_OK;\n";
382   } else {
383     out << "_aidl_ret_status = AParcel_writeStatusHeader(_aidl_out, _aidl_status.get());\n";
384     StatusCheckBreak(out);
385 
386     out << "if (!AStatus_isOk(_aidl_status.get())) break;\n\n";
387 
388     if (method.GetType().GetName() != "void") {
389       out << "_aidl_ret_status = ";
390       WriteToParcelFor({out, types, method.GetType(), "_aidl_out", "_aidl_return"});
391       out << ";\n";
392       StatusCheckBreak(out);
393     }
394     for (const AidlArgument* arg : method.GetOutArguments()) {
395       out << "_aidl_ret_status = ";
396       WriteToParcelFor({out, types, arg->GetType(), "_aidl_out", cpp::BuildVarName(*arg)});
397       out << ";\n";
398       StatusCheckBreak(out);
399     }
400   }
401   out << "break;\n";
402   out.Dedent();
403   out << "}\n";
404 }
405 
GenerateClassSource(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)406 void GenerateClassSource(CodeWriter& out, const AidlTypenames& types,
407                          const AidlInterface& defined_type, const Options& options) {
408   const std::string clazz = ClassName(defined_type, ClassNames::INTERFACE);
409   const std::string bn_clazz = ClassName(defined_type, ClassNames::SERVER);
410 
411   out << "static binder_status_t "
412       << "_aidl_onTransact"
413       << "(AIBinder* _aidl_binder, transaction_code_t _aidl_code, const AParcel* _aidl_in, "
414          "AParcel* _aidl_out) {\n";
415   out.Indent();
416   out << "(void)_aidl_in;\n";
417   out << "(void)_aidl_out;\n";
418   out << "binder_status_t _aidl_ret_status = STATUS_UNKNOWN_TRANSACTION;\n";
419   if (!defined_type.GetMethods().empty()) {
420     // we know this cast is valid because this method is only called by the ICInterface
421     // AIBinder_Class object which is associated with this class.
422     out << "std::shared_ptr<" << bn_clazz << "> _aidl_impl = std::static_pointer_cast<" << bn_clazz
423         << ">(::ndk::ICInterface::asInterface(_aidl_binder));\n";
424     out << "switch (_aidl_code) {\n";
425     out.Indent();
426     for (const auto& method : defined_type.GetMethods()) {
427       GenerateServerCaseDefinition(out, types, defined_type, *method, options);
428     }
429     out.Dedent();
430     out << "}\n";
431   } else {
432     out << "(void)_aidl_binder;\n";
433     out << "(void)_aidl_code;\n";
434   }
435   out << "return _aidl_ret_status;\n";
436   out.Dedent();
437   out << "};\n\n";
438 
439   out << "static AIBinder_Class* " << kClazz << " = ::ndk::ICInterface::defineClass(" << clazz
440       << "::" << kDescriptor << ", _aidl_onTransact);\n\n";
441 }
GenerateClientSource(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)442 void GenerateClientSource(CodeWriter& out, const AidlTypenames& types,
443                           const AidlInterface& defined_type, const Options& options) {
444   const std::string clazz = ClassName(defined_type, ClassNames::CLIENT);
445 
446   out << clazz << "::" << clazz << "(const ::ndk::SpAIBinder& binder) : BpCInterface(binder) {}\n";
447   out << clazz << "::~" << clazz << "() {}\n";
448   if (options.GenLog()) {
449     out << "std::function<void(const Json::Value&)> " << clazz << "::logFunc;\n";
450   }
451   out << "\n";
452   for (const auto& method : defined_type.GetMethods()) {
453     // Only getInterfaceVersion can use cache.
454     const bool cacheable = !method->IsUserDefined() && method->GetName() == kGetInterfaceVersion &&
455                            options.Version() > 0;
456     const auto return_value_cached_to =
457         cacheable ? std::make_optional<std::string>(kCacheVariable) : std::nullopt;
458     GenerateClientMethodDefinition(out, types, defined_type, *method, return_value_cached_to,
459                                    options);
460   }
461 }
GenerateServerSource(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)462 void GenerateServerSource(CodeWriter& out, const AidlTypenames& types,
463                           const AidlInterface& defined_type, const Options& options) {
464   const std::string clazz = ClassName(defined_type, ClassNames::SERVER);
465   const std::string iface = ClassName(defined_type, ClassNames::INTERFACE);
466 
467   out << "// Source for " << clazz << "\n";
468   out << clazz << "::" << clazz << "() {}\n";
469   out << clazz << "::~" << clazz << "() {}\n";
470   if (options.GenLog()) {
471     out << "std::function<void(const Json::Value&)> " << clazz << "::logFunc;\n";
472   }
473   out << "::ndk::SpAIBinder " << clazz << "::createBinder() {\n";
474   out.Indent();
475   out << "AIBinder* binder = AIBinder_new(" << kClazz << ", static_cast<void*>(this));\n";
476   out << "return ::ndk::SpAIBinder(binder);\n";
477   out.Dedent();
478   out << "}\n";
479 
480   // Implement the meta methods
481   for (const auto& method : defined_type.GetMethods()) {
482     if (method->IsUserDefined()) {
483       continue;
484     }
485     if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
486       out << NdkMethodDecl(types, *method, clazz) << " {\n";
487       out.Indent();
488       out << "*_aidl_return = " << iface << "::" << kVersion << ";\n";
489       out << "return ::ndk::ScopedAStatus(AStatus_newOk());\n";
490       out.Dedent();
491       out << "}\n";
492     }
493   }
494 }
GenerateInterfaceSource(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)495 void GenerateInterfaceSource(CodeWriter& out, const AidlTypenames& types,
496                              const AidlInterface& defined_type, const Options& options) {
497   const std::string clazz = ClassName(defined_type, ClassNames::INTERFACE);
498   const std::string bp_clazz = ClassName(defined_type, ClassNames::CLIENT);
499 
500   out << "// Source for " << clazz << "\n";
501   out << "const char* " << clazz << "::" << kDescriptor << " = \""
502       << defined_type.GetCanonicalName() << "\";\n";
503   out << clazz << "::" << clazz << "() {}\n";
504   out << clazz << "::~" << clazz << "() {}\n";
505   out << "\n";
506   GenerateConstantDefinitions(out, defined_type);
507   out << "\n";
508 
509   out << "std::shared_ptr<" << clazz << "> " << clazz
510       << "::fromBinder(const ::ndk::SpAIBinder& binder) {\n";
511   out.Indent();
512   out << "if (!AIBinder_associateClass(binder.get(), " << kClazz << ")) { return nullptr; }\n";
513   out << "std::shared_ptr<::ndk::ICInterface> interface = "
514          "::ndk::ICInterface::asInterface(binder.get());\n";
515   out << "if (interface) {\n";
516   out.Indent();
517   out << "return std::static_pointer_cast<" << clazz << ">(interface);\n";
518   out.Dedent();
519   out << "}\n";
520   out << "return (new " << bp_clazz << "(binder))->ref<" << clazz << ">();\n";
521   out.Dedent();
522   out << "}\n\n";
523 
524   out << "binder_status_t " << clazz << "::writeToParcel(AParcel* parcel, const std::shared_ptr<"
525       << clazz << ">& instance) {\n";
526   out.Indent();
527   out << "return AParcel_writeStrongBinder(parcel, instance ? instance->asBinder().get() : "
528          "nullptr);\n";
529   out.Dedent();
530   out << "}\n";
531 
532   out << "binder_status_t " << clazz << "::readFromParcel(const AParcel* parcel, std::shared_ptr<"
533       << clazz << ">* instance) {\n";
534   out.Indent();
535   out << "::ndk::SpAIBinder binder;\n";
536   out << "binder_status_t status = AParcel_readStrongBinder(parcel, binder.getR());\n";
537   out << "if (status != STATUS_OK) return status;\n";
538   out << "*instance = " << clazz << "::fromBinder(binder);\n";
539   out << "return STATUS_OK;\n";
540   out.Dedent();
541   out << "}\n";
542 
543   // defintion for static member setDefaultImpl
544   out << "bool " << clazz << "::setDefaultImpl(std::shared_ptr<" << clazz << "> impl) {\n";
545   out.Indent();
546   out << "if (!" << clazz << "::default_impl && impl) {\n";
547   out.Indent();
548   out << clazz << "::default_impl = impl;\n";
549   out << "return true;\n";
550   out.Dedent();
551   out << "}\n";
552   out << "return false;\n";
553   out.Dedent();
554   out << "}\n";
555 
556   // definition for static member getDefaultImpl
557   out << "const std::shared_ptr<" << clazz << ">& " << clazz << "::getDefaultImpl() {\n";
558   out.Indent();
559   out << "return " << clazz << "::default_impl;\n";
560   out.Dedent();
561   out << "}\n";
562 
563   // definition for the static field default_impl
564   out << "std::shared_ptr<" << clazz << "> " << clazz << "::default_impl = nullptr;\n";
565 
566   // default implementation for the <Name>Default class members
567   const std::string defaultClazz = clazz + "Default";
568   for (const auto& method : defined_type.GetMethods()) {
569     if (method->IsUserDefined()) {
570       out << "::ndk::ScopedAStatus " << defaultClazz << "::" << method->GetName() << "("
571           << NdkArgList(types, *method, FormatArgNameUnused) << ") {\n";
572       out.Indent();
573       out << "::ndk::ScopedAStatus _aidl_status;\n";
574       out << "_aidl_status.set(AStatus_fromStatus(STATUS_UNKNOWN_TRANSACTION));\n";
575       out << "return _aidl_status;\n";
576       out.Dedent();
577       out << "}\n";
578     } else {
579       if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
580         out << "::ndk::ScopedAStatus " << defaultClazz << "::" << method->GetName() << "("
581             << "int32_t* _aidl_return) {\n";
582         out.Indent();
583         out << "*_aidl_return = 0;\n";
584         out << "return ::ndk::ScopedAStatus(AStatus_newOk());\n";
585         out.Dedent();
586         out << "}\n";
587       }
588     }
589   }
590 
591   out << "::ndk::SpAIBinder " << defaultClazz << "::asBinder() {\n";
592   out.Indent();
593   out << "return ::ndk::SpAIBinder();\n";
594   out.Dedent();
595   out << "}\n";
596 
597   out << "bool " << defaultClazz << "::isRemote() {\n";
598   out.Indent();
599   out << "return false;\n";
600   out.Dedent();
601   out << "}\n";
602 }
603 
GenerateClientHeader(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)604 void GenerateClientHeader(CodeWriter& out, const AidlTypenames& types,
605                           const AidlInterface& defined_type, const Options& options) {
606   const std::string clazz = ClassName(defined_type, ClassNames::CLIENT);
607 
608   out << "#pragma once\n\n";
609   out << "#include \"" << NdkHeaderFile(defined_type, ClassNames::RAW, false /*use_os_sep*/)
610       << "\"\n";
611   out << "\n";
612   out << "#include <android/binder_ibinder.h>\n";
613   if (options.GenLog()) {
614     out << "#include <json/value.h>\n";
615     out << "#include <functional>\n";
616     out << "#include <chrono>\n";
617     out << "#include <sstream>\n";
618   }
619   out << "\n";
620   EnterNdkNamespace(out, defined_type);
621   out << "class " << clazz << " : public ::ndk::BpCInterface<"
622       << ClassName(defined_type, ClassNames::INTERFACE) << "> {\n";
623   out << "public:\n";
624   out.Indent();
625   out << clazz << "(const ::ndk::SpAIBinder& binder);\n";
626   out << "virtual ~" << clazz << "();\n";
627   out << "\n";
628   for (const auto& method : defined_type.GetMethods()) {
629     out << NdkMethodDecl(types, *method) << " override;\n";
630   }
631 
632   if (options.Version() > 0) {
633     out << "int32_t " << kCacheVariable << " = -1;\n";
634   }
635   if (options.GenLog()) {
636     out << "static std::function<void(const Json::Value&)> logFunc;\n";
637   }
638   out.Dedent();
639   out << "};\n";
640   LeaveNdkNamespace(out, defined_type);
641 }
GenerateServerHeader(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)642 void GenerateServerHeader(CodeWriter& out, const AidlTypenames& types,
643                           const AidlInterface& defined_type, const Options& options) {
644   const std::string clazz = ClassName(defined_type, ClassNames::SERVER);
645   const std::string iface = ClassName(defined_type, ClassNames::INTERFACE);
646 
647   out << "#pragma once\n\n";
648   out << "#include \"" << NdkHeaderFile(defined_type, ClassNames::RAW, false /*use_os_sep*/)
649       << "\"\n";
650   out << "\n";
651   out << "#include <android/binder_ibinder.h>\n";
652   out << "\n";
653   EnterNdkNamespace(out, defined_type);
654   out << "class " << clazz << " : public ::ndk::BnCInterface<" << iface << "> {\n";
655   out << "public:\n";
656   out.Indent();
657   out << clazz << "();\n";
658   out << "virtual ~" << clazz << "();\n";
659 
660   // Declare the meta methods
661   for (const auto& method : defined_type.GetMethods()) {
662     if (method->IsUserDefined()) {
663       continue;
664     }
665     if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
666       out << NdkMethodDecl(types, *method) << " final override;\n";
667     } else {
668       AIDL_FATAL(defined_type) << "Meta method '" << method->GetName() << "' is unimplemented.";
669     }
670   }
671   if (options.GenLog()) {
672     out << "static std::function<void(const Json::Value&)> logFunc;\n";
673   }
674   out.Dedent();
675   out << "protected:\n";
676   out.Indent();
677   out << "::ndk::SpAIBinder createBinder() override;\n";
678   out.Dedent();
679   out << "private:\n";
680   out.Indent();
681   out.Dedent();
682   out << "};\n";
683   LeaveNdkNamespace(out, defined_type);
684 }
GenerateInterfaceHeader(CodeWriter & out,const AidlTypenames & types,const AidlInterface & defined_type,const Options & options)685 void GenerateInterfaceHeader(CodeWriter& out, const AidlTypenames& types,
686                              const AidlInterface& defined_type, const Options& options) {
687   const std::string clazz = ClassName(defined_type, ClassNames::INTERFACE);
688 
689   out << "#pragma once\n\n";
690   out << "#include <android/binder_interface_utils.h>\n";
691   if (options.GenLog()) {
692     out << "#include <json/value.h>\n";
693     out << "#include <functional>\n";
694     out << "#include <chrono>\n";
695     out << "#include <sstream>\n";
696   }
697   out << "\n";
698 
699   GenerateHeaderIncludes(out, types, defined_type);
700   out << "\n";
701 
702   EnterNdkNamespace(out, defined_type);
703   out << "class " << clazz << " : public ::ndk::ICInterface {\n";
704   out << "public:\n";
705   out.Indent();
706   out << "static const char* " << kDescriptor << ";\n";
707   out << clazz << "();\n";
708   out << "virtual ~" << clazz << "();\n";
709   out << "\n";
710   GenerateConstantDeclarations(out, defined_type);
711   if (options.Version() > 0) {
712     out << "static const int32_t " << kVersion << " = " << std::to_string(options.Version())
713         << ";\n";
714   }
715   out << "\n";
716   out << "static std::shared_ptr<" << clazz << "> fromBinder(const ::ndk::SpAIBinder& binder);\n";
717   out << "static binder_status_t writeToParcel(AParcel* parcel, const std::shared_ptr<" << clazz
718       << ">& instance);";
719   out << "\n";
720   out << "static binder_status_t readFromParcel(const AParcel* parcel, std::shared_ptr<" << clazz
721       << ">* instance);";
722   out << "\n";
723   out << "static bool setDefaultImpl(std::shared_ptr<" << clazz << "> impl);";
724   out << "\n";
725   out << "static const std::shared_ptr<" << clazz << ">& getDefaultImpl();";
726   out << "\n";
727   for (const auto& method : defined_type.GetMethods()) {
728     out << "virtual " << NdkMethodDecl(types, *method) << " = 0;\n";
729   }
730   out.Dedent();
731   out << "private:\n";
732   out.Indent();
733   out << "static std::shared_ptr<" << clazz << "> default_impl;\n";
734   out.Dedent();
735   out << "};\n";
736 
737   const std::string defaultClazz = clazz + "Default";
738 
739   out << "class " << defaultClazz << " : public " << clazz << " {\n";
740   out << "public:\n";
741   out.Indent();
742   for (const auto& method : defined_type.GetMethods()) {
743     if (method->IsUserDefined()) {
744       out << NdkMethodDecl(types, *method) << " override;\n";
745     } else if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
746       out << NdkMethodDecl(types, *method) << " override;\n";
747     }
748   }
749   out << "::ndk::SpAIBinder asBinder() override;\n";
750   out << "bool isRemote() override;\n";
751   out.Dedent();
752   out << "};\n";
753 
754   LeaveNdkNamespace(out, defined_type);
755 }
GenerateParcelHeader(CodeWriter & out,const AidlTypenames & types,const AidlStructuredParcelable & defined_type,const Options &)756 void GenerateParcelHeader(CodeWriter& out, const AidlTypenames& types,
757                           const AidlStructuredParcelable& defined_type,
758                           const Options& /*options*/) {
759   const std::string clazz = ClassName(defined_type, ClassNames::BASE);
760 
761   out << "#pragma once\n";
762   out << "#include <android/binder_interface_utils.h>\n";
763   out << "\n";
764 
765   GenerateHeaderIncludes(out, types, defined_type);
766 
767   EnterNdkNamespace(out, defined_type);
768   out << "class " << clazz << " {\n";
769   out << "public:\n";
770   out.Indent();
771   out << "static const char* descriptor;\n";
772   out << "\n";
773   for (const auto& variable : defined_type.GetFields()) {
774     out << NdkNameOf(types, variable->GetType(), StorageMode::STACK) << " " << variable->GetName();
775     if (variable->GetDefaultValue()) {
776       out << " = " << variable->ValueString(AidlConstantValueDecorator);
777     }
778     out << ";\n";
779   }
780   out << "\n";
781   out << "binder_status_t readFromParcel(const AParcel* parcel);\n";
782   out << "binder_status_t writeToParcel(AParcel* parcel) const;\n";
783   out.Dedent();
784   out << "};\n";
785   LeaveNdkNamespace(out, defined_type);
786 }
GenerateParcelSource(CodeWriter & out,const AidlTypenames & types,const AidlStructuredParcelable & defined_type,const Options &)787 void GenerateParcelSource(CodeWriter& out, const AidlTypenames& types,
788                           const AidlStructuredParcelable& defined_type,
789                           const Options& /*options*/) {
790   const std::string clazz = ClassName(defined_type, ClassNames::BASE);
791 
792   out << "#include \"" << NdkHeaderFile(defined_type, ClassNames::RAW, false /*use_os_sep*/)
793       << "\"\n";
794   out << "\n";
795   GenerateSourceIncludes(out, types, defined_type);
796   out << "\n";
797   EnterNdkNamespace(out, defined_type);
798   out << "const char* " << clazz << "::" << kDescriptor << " = \""
799       << defined_type.GetCanonicalName() << "\";\n";
800   out << "\n";
801 
802   out << "binder_status_t " << clazz << "::readFromParcel(const AParcel* parcel) {\n";
803   out.Indent();
804   out << "std::string _aidl_descriptor;\n";
805   out << "binder_status_t _aidl_ret_status;\n";
806 
807   out << "int32_t _aidl_null;\n";
808   out << "int32_t _aidl_parcelable_size;\n";
809   out << "int32_t _aidl_start_pos;\n";
810   out << "_aidl_ret_status = AParcel_readInt32(parcel, &_aidl_null);\n";
811   StatusCheckReturn(out);
812   out << "_aidl_start_pos = AParcel_getDataPosition(parcel);\n";
813   out << "_aidl_ret_status = AParcel_readInt32(parcel, &_aidl_parcelable_size);\n";
814   out << "if (_aidl_parcelable_size < 0) return STATUS_BAD_VALUE;\n";
815   StatusCheckReturn(out);
816 
817   // TODO(b/117281836)
818   out << "if (_aidl_null == 0) return STATUS_UNEXPECTED_NULL;\n\n";
819 
820   for (const auto& variable : defined_type.GetFields()) {
821     out << "_aidl_ret_status = ";
822     ReadFromParcelFor({out, types, variable->GetType(), "parcel", "&" + variable->GetName()});
823     out << ";\n";
824     StatusCheckReturn(out);
825     out << "if (AParcel_getDataPosition(parcel) - _aidl_start_pos >= _aidl_parcelable_size) {\n"
826         << "  AParcel_setDataPosition(parcel, _aidl_start_pos + _aidl_parcelable_size);\n"
827         << "  return _aidl_ret_status;\n"
828         << "}\n";
829   }
830   out << "AParcel_setDataPosition(parcel, _aidl_start_pos + _aidl_parcelable_size);\n"
831       << "return _aidl_ret_status;\n";
832   out.Dedent();
833   out << "}\n";
834 
835   out << "binder_status_t " << clazz << "::writeToParcel(AParcel* parcel) const {\n";
836   out.Indent();
837   out << "binder_status_t _aidl_ret_status;\n";
838 
839   // non-null
840   out << "_aidl_ret_status = AParcel_writeInt32(parcel, 1);\n";
841   StatusCheckReturn(out);
842   out << "size_t _aidl_start_pos = AParcel_getDataPosition(parcel);\n";
843   out << "_aidl_ret_status = AParcel_writeInt32(parcel, 0);\n";
844   StatusCheckReturn(out);
845 
846   for (const auto& variable : defined_type.GetFields()) {
847     out << "_aidl_ret_status = ";
848     WriteToParcelFor({out, types, variable->GetType(), "parcel", variable->GetName()});
849     out << ";\n";
850     StatusCheckReturn(out);
851   }
852   out << "size_t _aidl_end_pos = AParcel_getDataPosition(parcel);\n";
853   out << "AParcel_setDataPosition(parcel, _aidl_start_pos);\n";
854   out << "AParcel_writeInt32(parcel, _aidl_end_pos - _aidl_start_pos);\n";
855   out << "AParcel_setDataPosition(parcel, _aidl_end_pos);\n";
856 
857   out << "return _aidl_ret_status;\n";
858   out.Dedent();
859   out << "}\n";
860   out << "\n";
861   LeaveNdkNamespace(out, defined_type);
862 }
863 }  // namespace internals
864 }  // namespace ndk
865 }  // namespace aidl
866 }  // namespace android
867