• 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 #include "aidl_to_cpp_common.h"
17 
18 #include <android-base/format.h>
19 #include <android-base/stringprintf.h>
20 #include <android-base/strings.h>
21 
22 #include <limits>
23 #include <set>
24 #include <unordered_map>
25 
26 #include "comments.h"
27 #include "logging.h"
28 #include "os.h"
29 
30 using ::android::base::Join;
31 using ::android::base::Split;
32 
33 namespace android {
34 namespace aidl {
35 namespace cpp {
36 
37 char kTransactionLogStruct[] = R"(struct TransactionLog {
38   double duration_ms;
39   std::string interface_name;
40   std::string method_name;
41   const void* proxy_address;
42   const void* stub_address;
43   std::vector<std::pair<std::string, std::string>> input_args;
44   std::vector<std::pair<std::string, std::string>> output_args;
45   std::string result;
46   std::string exception_message;
47   int32_t exception_code;
48   int32_t transaction_error;
49   int32_t service_specific_error_code;
50 };
51 )";
52 
HasDeprecatedField(const AidlParcelable & parcelable)53 bool HasDeprecatedField(const AidlParcelable& parcelable) {
54   return std::any_of(parcelable.GetFields().begin(), parcelable.GetFields().end(),
55                      [](const auto& field) { return field->IsDeprecated(); });
56 }
57 
ClassName(const AidlDefinedType & defined_type,ClassNames type)58 string ClassName(const AidlDefinedType& defined_type, ClassNames type) {
59   if (type == ClassNames::MAYBE_INTERFACE && defined_type.AsInterface()) {
60     type = ClassNames::INTERFACE;
61   }
62   string base_name = defined_type.GetName();
63   if (base_name.length() >= 2 && base_name[0] == 'I' && isupper(base_name[1])) {
64     base_name = base_name.substr(1);
65   }
66 
67   switch (type) {
68     case ClassNames::CLIENT:
69       return "Bp" + base_name;
70     case ClassNames::SERVER:
71       return "Bn" + base_name;
72     case ClassNames::INTERFACE:
73       return "I" + base_name;
74     case ClassNames::DEFAULT_IMPL:
75       return "I" + base_name + "Default";
76     case ClassNames::BASE:
77       return base_name;
78     case ClassNames::DELEGATOR_IMPL:
79       return "I" + base_name + "Delegator";
80     case ClassNames::RAW:
81       [[fallthrough]];
82     default:
83       return defined_type.GetName();
84   }
85 }
86 
HeaderFile(const AidlDefinedType & defined_type,ClassNames class_type,bool use_os_sep)87 std::string HeaderFile(const AidlDefinedType& defined_type, ClassNames class_type,
88                        bool use_os_sep) {
89   // For a nested type, we need to include its top-most parent type's header.
90   const AidlDefinedType* toplevel = &defined_type;
91   for (auto parent = toplevel->GetParentType(); parent;) {
92     // When including the parent's header, it should be always RAW
93     class_type = ClassNames::RAW;
94     toplevel = parent;
95     parent = toplevel->GetParentType();
96   }
97   AIDL_FATAL_IF(toplevel->GetParentType() != nullptr, defined_type)
98       << "Can't find a top-level decl";
99 
100   char separator = (use_os_sep) ? OS_PATH_SEPARATOR : '/';
101   vector<string> paths = toplevel->GetSplitPackage();
102   paths.push_back(ClassName(*toplevel, class_type));
103   return Join(paths, separator) + ".h";
104 }
105 
106 // Ensures that output_file is  <out_dir>/<packagename>/<typename>.cpp
ValidateOutputFilePath(const string & output_file,const Options & options,const AidlDefinedType & defined_type)107 bool ValidateOutputFilePath(const string& output_file, const Options& options,
108                             const AidlDefinedType& defined_type) {
109   const auto& out_dir =
110       !options.OutputDir().empty() ? options.OutputDir() : options.OutputHeaderDir();
111   if (output_file.empty() || !android::base::StartsWith(output_file, out_dir)) {
112     // If output_file is not set (which happens in the unit tests) or is outside of out_dir, we can
113     // help but accepting it, because the path is what the user has requested.
114     return true;
115   }
116 
117   string canonical_name = defined_type.GetCanonicalName();
118   std::replace(canonical_name.begin(), canonical_name.end(), '.', OS_PATH_SEPARATOR);
119   const string expected = out_dir + canonical_name + ".cpp";
120   if (expected != output_file) {
121     AIDL_ERROR(defined_type) << "Output file is expected to be at " << expected << ", but is "
122                              << output_file << ".\n If this is an Android platform "
123                              << "build, consider providing the input AIDL files using a filegroup "
124                              << "with `path:\"<base>\"` so that the AIDL files are located at "
125                              << "<base>/<packagename>/<typename>.aidl.";
126     return false;
127   }
128   return true;
129 }
130 
EnterNamespace(CodeWriter & out,const AidlDefinedType & defined_type)131 void EnterNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
132   const std::vector<std::string> packages = defined_type.GetSplitPackage();
133   for (const std::string& package : packages) {
134     out << "namespace " << package << " {\n";
135   }
136 }
LeaveNamespace(CodeWriter & out,const AidlDefinedType & defined_type)137 void LeaveNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
138   const std::vector<std::string> packages = defined_type.GetSplitPackage();
139   for (auto it = packages.rbegin(); it != packages.rend(); ++it) {
140     out << "}  // namespace " << *it << "\n";
141   }
142 }
143 
BuildVarName(const AidlArgument & a)144 string BuildVarName(const AidlArgument& a) {
145   string prefix = "out_";
146   if (a.GetDirection() & AidlArgument::IN_DIR) {
147     prefix = "in_";
148   }
149   return prefix + a.GetName();
150 }
151 
WriteLogForArgument(CodeWriter & w,const AidlArgument & a,bool is_server,const string & log_var,bool is_ndk)152 void WriteLogForArgument(CodeWriter& w, const AidlArgument& a, bool is_server,
153                          const string& log_var, bool is_ndk) {
154   const string var_name = is_server || is_ndk ? BuildVarName(a) : a.GetName();
155   const bool is_pointer = a.IsOut() && !is_server;
156   const string value_expr = (is_pointer ? "*" : "") + var_name;
157   w << log_var
158     << ".emplace_back(\"" + var_name + "\", ::android::internal::ToString(" + value_expr + "));\n";
159 }
160 
GenLogBeforeExecute(const string className,const AidlMethod & method,bool isServer,bool isNdk)161 const string GenLogBeforeExecute(const string className, const AidlMethod& method, bool isServer,
162                                  bool isNdk) {
163   string code;
164   CodeWriterPtr writer = CodeWriter::ForString(&code);
165   (*writer) << className << "::TransactionLog _transaction_log;\n";
166 
167   (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
168   (*writer).Indent();
169 
170   for (const auto& a : method.GetInArguments()) {
171     WriteLogForArgument(*writer, *a, isServer, "_transaction_log.input_args", isNdk);
172   }
173 
174   (*writer).Dedent();
175   (*writer) << "}\n";
176 
177   (*writer) << "auto _log_start = std::chrono::steady_clock::now();\n";
178   writer->Close();
179   return code;
180 }
181 
GenLogAfterExecute(const string className,const AidlInterface & interface,const AidlMethod & method,const string & statusVarName,const string & returnVarName,bool isServer,bool isNdk)182 const string GenLogAfterExecute(const string className, const AidlInterface& interface,
183                                 const AidlMethod& method, const string& statusVarName,
184                                 const string& returnVarName, bool isServer, bool isNdk) {
185   string code;
186   CodeWriterPtr writer = CodeWriter::ForString(&code);
187 
188   (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
189   (*writer).Indent();
190   const auto address = (isNdk && isServer) ? "_aidl_impl.get()" : "static_cast<const void*>(this)";
191   (*writer) << "auto _log_end = std::chrono::steady_clock::now();\n";
192   (*writer) << "_transaction_log.duration_ms = std::chrono::duration<double, std::milli>(_log_end "
193                "- _log_start).count();\n";
194   (*writer) << "_transaction_log.interface_name = \"" << interface.GetCanonicalName() << "\";\n";
195   (*writer) << "_transaction_log.method_name = \"" << method.GetName() << "\";\n";
196   (*writer) << "_transaction_log.stub_address = " << (isServer ? address : "nullptr") << ";\n";
197   (*writer) << "_transaction_log.proxy_address = " << (isServer ? "nullptr" : address) << ";\n";
198 
199   if (isNdk) {
200     (*writer) << "_transaction_log.exception_code = AStatus_getExceptionCode(" << statusVarName
201               << ".get());\n";
202     (*writer) << "_transaction_log.exception_message = AStatus_getMessage(" << statusVarName
203               << ".get());\n";
204     (*writer) << "_transaction_log.transaction_error = AStatus_getStatus(" << statusVarName
205               << ".get());\n";
206     (*writer) << "_transaction_log.service_specific_error_code = AStatus_getServiceSpecificError("
207               << statusVarName << ".get());\n";
208   } else {
209     (*writer) << "_transaction_log.exception_code = " << statusVarName << ".exceptionCode();\n";
210     (*writer) << "_transaction_log.exception_message = " << statusVarName
211               << ".exceptionMessage();\n";
212     (*writer) << "_transaction_log.transaction_error = " << statusVarName
213               << ".transactionError();\n";
214     (*writer) << "_transaction_log.service_specific_error_code = " << statusVarName
215               << ".serviceSpecificErrorCode();\n";
216   }
217 
218   for (const auto& a : method.GetOutArguments()) {
219     WriteLogForArgument(*writer, *a, isServer, "_transaction_log.output_args", isNdk);
220   }
221 
222   if (method.GetType().GetName() != "void") {
223     const string expr = (isServer ? "" : "*") + returnVarName;
224     (*writer) << "_transaction_log.result = ::android::internal::ToString(" << expr << ");\n";
225   }
226 
227   // call the user-provided function with the transaction log object
228   (*writer) << className << "::logFunc(_transaction_log);\n";
229 
230   (*writer).Dedent();
231   (*writer) << "}\n";
232 
233   writer->Close();
234   return code;
235 }
236 
237 // Returns Parent1::Parent2::Self. Namespaces are not included.
GetQualifiedName(const AidlDefinedType & type,ClassNames class_names)238 string GetQualifiedName(const AidlDefinedType& type, ClassNames class_names) {
239   string q_name = ClassName(type, class_names);
240   for (auto parent = type.GetParentType(); parent; parent = parent->GetParentType()) {
241     q_name = ClassName(*parent, ClassNames::MAYBE_INTERFACE) + "::" + q_name;
242   }
243   return q_name;
244 }
245 
246 // Generates enum's class declaration. This should be called in a proper scope. For example, in its
247 // namespace or parent type.
GenerateEnumClassDecl(CodeWriter & out,const AidlEnumDeclaration & enum_decl,const std::string & backing_type,ConstantValueDecorator decorator)248 void GenerateEnumClassDecl(CodeWriter& out, const AidlEnumDeclaration& enum_decl,
249                            const std::string& backing_type, ConstantValueDecorator decorator) {
250   out << "enum class";
251   GenerateDeprecated(out, enum_decl);
252   out << " " << enum_decl.GetName() << " : " << backing_type << " {\n";
253   out.Indent();
254   for (const auto& enumerator : enum_decl.GetEnumerators()) {
255     out << enumerator->GetName();
256     GenerateDeprecated(out, *enumerator);
257     out << " = " << enumerator->ValueString(enum_decl.GetBackingType(), decorator) << ",\n";
258   }
259   out.Dedent();
260   out << "};\n";
261 }
262 
IsEnumDeprecated(const AidlEnumDeclaration & enum_decl)263 static bool IsEnumDeprecated(const AidlEnumDeclaration& enum_decl) {
264   if (enum_decl.IsDeprecated()) {
265     return true;
266   }
267   for (const auto& e : enum_decl.GetEnumerators()) {
268     if (e->IsDeprecated()) {
269       return true;
270     }
271   }
272   return false;
273 }
274 
275 // enum_values template value is defined in its own namespace (android::internal or ndk::internal),
276 // so the enum_decl type should be fully qualified.
GenerateEnumValues(const AidlEnumDeclaration & enum_decl,const std::vector<std::string> & enclosing_namespaces_of_enum_decl)277 std::string GenerateEnumValues(const AidlEnumDeclaration& enum_decl,
278                                const std::vector<std::string>& enclosing_namespaces_of_enum_decl) {
279   const auto fq_name =
280       Join(Append(enclosing_namespaces_of_enum_decl, enum_decl.GetSplitPackage()), "::") +
281       "::" + GetQualifiedName(enum_decl);
282   const auto size = enum_decl.GetEnumerators().size();
283   std::ostringstream code;
284   code << "#pragma clang diagnostic push\n";
285   code << "#pragma clang diagnostic ignored \"-Wc++17-extensions\"\n";
286   if (IsEnumDeprecated(enum_decl)) {
287     code << "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n";
288   }
289   code << "template <>\n";
290   code << "constexpr inline std::array<" << fq_name << ", " << size << ">";
291   code << " enum_values<" << fq_name << "> = {\n";
292   for (const auto& enumerator : enum_decl.GetEnumerators()) {
293     code << "  " << fq_name << "::" << enumerator->GetName() << ",\n";
294   }
295   code << "};\n";
296   code << "#pragma clang diagnostic pop\n";
297   return code.str();
298 }
299 
300 // toString(enum_type) is defined in the same namespace of the type.
301 // So, if enum_decl is nested in parent type(s), it should be qualified with parent type(s).
GenerateEnumToString(const AidlEnumDeclaration & enum_decl,const std::string & backing_type)302 std::string GenerateEnumToString(const AidlEnumDeclaration& enum_decl,
303                                  const std::string& backing_type) {
304   const auto q_name = GetQualifiedName(enum_decl);
305   std::ostringstream code;
306   bool is_enum_deprecated = IsEnumDeprecated(enum_decl);
307   if (is_enum_deprecated) {
308     code << "#pragma clang diagnostic push\n";
309     code << "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n";
310   }
311   code << "[[nodiscard]] static inline std::string toString(" + q_name + " val) {\n";
312   code << "  switch(val) {\n";
313   std::set<std::string> unique_cases;
314   for (const auto& enumerator : enum_decl.GetEnumerators()) {
315     std::string c = enumerator->ValueString(enum_decl.GetBackingType(), AidlConstantValueDecorator);
316     // Only add a case if its value has not yet been used in the switch
317     // statement. C++ does not allow multiple cases with the same value, but
318     // enums does allow this. In this scenario, the first declared
319     // enumerator with the given value is printed.
320     if (unique_cases.count(c) == 0) {
321       unique_cases.insert(c);
322       code << "  case " << q_name << "::" << enumerator->GetName() << ":\n";
323       code << "    return \"" << enumerator->GetName() << "\";\n";
324     }
325   }
326   code << "  default:\n";
327   code << "    return std::to_string(static_cast<" << backing_type << ">(val));\n";
328   code << "  }\n";
329   code << "}\n";
330   if (is_enum_deprecated) {
331     code << "#pragma clang diagnostic pop\n";
332   }
333   return code.str();
334 }
335 
TemplateDecl(const AidlParcelable & defined_type)336 std::string TemplateDecl(const AidlParcelable& defined_type) {
337   std::string decl = "";
338   if (defined_type.IsGeneric()) {
339     std::vector<std::string> template_params;
340     for (const auto& parameter : defined_type.GetTypeParameters()) {
341       template_params.push_back(parameter);
342     }
343     decl = base::StringPrintf("template <typename %s>\n",
344                               base::Join(template_params, ", typename ").c_str());
345   }
346   return decl;
347 }
348 
GenerateParcelableComparisonOperators(CodeWriter & out,const AidlParcelable & parcelable)349 void GenerateParcelableComparisonOperators(CodeWriter& out, const AidlParcelable& parcelable) {
350   std::set<string> operators{"<", ">", "==", ">=", "<=", "!="};
351 
352   if (parcelable.AsUnionDeclaration() && parcelable.IsFixedSize()) {
353     auto name = parcelable.GetName();
354     auto max_tag = parcelable.GetFields().back()->GetName();
355     auto min_tag = parcelable.GetFields().front()->GetName();
356     constexpr auto tmpl = R"--(static int _cmp(const {name}& _lhs, const {name}& _rhs) {{
357   return _cmp_value(_lhs.getTag(), _rhs.getTag()) || _cmp_value_at<{max_tag}>(_lhs, _rhs);
358 }}
359 template <Tag _Tag>
360 static int _cmp_value_at(const {name}& _lhs, const {name}& _rhs) {{
361   if constexpr (_Tag == {min_tag}) {{
362     return _cmp_value(_lhs.get<_Tag>(), _rhs.get<_Tag>());
363   }} else {{
364     return (_lhs.getTag() == _Tag)
365       ? _cmp_value(_lhs.get<_Tag>(), _rhs.get<_Tag>())
366       : _cmp_value_at<static_cast<Tag>(static_cast<size_t>(_Tag)-1)>(_lhs, _rhs);
367   }}
368 }}
369 template <typename _Type>
370 static int _cmp_value(const _Type& _lhs, const _Type& _rhs) {{
371   return (_lhs == _rhs) ? 0 : (_lhs < _rhs) ? -1 : 1;
372 }}
373 )--";
374     out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("min_tag", min_tag),
375                        fmt::arg("max_tag", max_tag));
376     for (const auto& op : operators) {
377       out << "inline bool operator" << op << "(const " << name << "&_rhs) const {\n";
378       out << "  return _cmp(*this, _rhs) " << op << " 0;\n";
379       out << "}\n";
380     }
381     return;
382   }
383 
384   bool is_empty = false;
385 
386   auto comparable = [&](const string& prefix) {
387     vector<string> fields;
388     if (auto p = parcelable.AsStructuredParcelable(); p != nullptr) {
389       is_empty = p->GetFields().empty();
390       for (const auto& f : p->GetFields()) {
391         fields.push_back(prefix + f->GetName());
392       }
393       return "std::tie(" + Join(fields, ", ") + ")";
394     } else if (auto p = parcelable.AsUnionDeclaration(); p != nullptr) {
395       return prefix + "_value";
396     } else {
397       AIDL_FATAL(parcelable) << "Unknown paracelable type";
398     }
399   };
400 
401   string lhs = comparable("");
402   string rhs = comparable("_rhs.");
403 
404   // Delegate < and == to the fields.
405   for (const auto& op : {"==", "<"}) {
406     out << "inline bool operator" << op << "(const " << parcelable.GetName() << "&"
407         << (is_empty ? "" : " _rhs") << ") const {\n"
408         << "  return " << lhs << " " << op << " " << rhs << ";\n"
409         << "}\n";
410   }
411   // Delegate other ops to < and == for *this, which lets a custom parcelable
412   // to be used with structured parcelables without implementation all operations.
413   out << fmt::format(R"--(inline bool operator!=(const {name}& _rhs) const {{
414   return !(*this == _rhs);
415 }}
416 inline bool operator>(const {name}& _rhs) const {{
417   return _rhs < *this;
418 }}
419 inline bool operator>=(const {name}& _rhs) const {{
420   return !(*this < _rhs);
421 }}
422 inline bool operator<=(const {name}& _rhs) const {{
423   return !(_rhs < *this);
424 }}
425 )--",
426                      fmt::arg("name", parcelable.GetName()));
427   out << "\n";
428 }
429 
430 // Output may look like:
431 // inline std::string toString() const {
432 //   std::ostringstream _aidl_os;
433 //   _aidl_os << "MyData{";
434 //   _aidl_os << "field1: " << field1;
435 //   _aidl_os << ", field2: " << v.field2;
436 //   ...
437 //   _aidl_os << "}";
438 //   return _aidl_os.str();
439 // }
GenerateToString(CodeWriter & out,const AidlStructuredParcelable & parcelable)440 void GenerateToString(CodeWriter& out, const AidlStructuredParcelable& parcelable) {
441   out << "inline std::string toString() const {\n";
442   out.Indent();
443   out << "std::ostringstream _aidl_os;\n";
444   out << "_aidl_os << \"" << parcelable.GetName() << "{\";\n";
445   bool first = true;
446   for (const auto& f : parcelable.GetFields()) {
447     if (first) {
448       out << "_aidl_os << \"";
449       first = false;
450     } else {
451       out << "_aidl_os << \", ";
452     }
453     out << f->GetName() << ": \" << ::android::internal::ToString(" << f->GetName() << ");\n";
454   }
455   out << "_aidl_os << \"}\";\n";
456   out << "return _aidl_os.str();\n";
457   out.Dedent();
458   out << "}\n";
459 }
460 
461 // Output may look like:
462 // inline std::string toString() const {
463 //   std::ostringstream os;
464 //   os << "MyData{";
465 //   switch (v.getTag()) {
466 //   case MyData::field: os << "field: " << v.get<MyData::field>(); break;
467 //   ...
468 //   }
469 //   os << "}";
470 //   return os.str();
471 // }
GenerateToString(CodeWriter & out,const AidlUnionDecl & parcelable)472 void GenerateToString(CodeWriter& out, const AidlUnionDecl& parcelable) {
473   out << "inline std::string toString() const {\n";
474   out.Indent();
475   out << "std::ostringstream os;\n";
476   out << "os << \"" + parcelable.GetName() + "{\";\n";
477   out << "switch (getTag()) {\n";
478   for (const auto& f : parcelable.GetFields()) {
479     const string tag = f->GetName();
480     out << "case " << tag << ": os << \"" << tag << ": \" << "
481         << "::android::internal::ToString(get<" + tag + ">()); break;\n";
482   }
483   out << "}\n";
484   out << "os << \"}\";\n";
485   out << "return os.str();\n";
486   out.Dedent();
487   out << "}\n";
488 }
489 
GetDeprecatedAttribute(const AidlCommentable & type)490 std::string GetDeprecatedAttribute(const AidlCommentable& type) {
491   if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
492     if (deprecated->note.empty()) {
493       return "__attribute__((deprecated))";
494     }
495     return "__attribute__((deprecated(" + QuotedEscape(deprecated->note) + ")))";
496   }
497   return "";
498 }
499 
AlignmentOf(const AidlTypeSpecifier & type,const AidlTypenames & typenames)500 std::optional<size_t> AlignmentOf(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
501   static map<string, size_t> alignment = {
502       {"boolean", 1}, {"byte", 1}, {"char", 2}, {"double", 8},
503       {"float", 4},   {"int", 4},  {"long", 8},
504   };
505 
506   string name = type.GetName();
507   if (auto enum_decl = typenames.GetEnumDeclaration(type); enum_decl) {
508     AIDL_FATAL_IF(type.IsArray() && !type.IsFixedSizeArray(), type);
509     name = enum_decl->GetBackingType().GetName();
510   }
511   auto it = alignment.find(name);
512   if (it != alignment.end()) {
513     return it->second;
514   }
515   const AidlDefinedType* defined_type = type.GetDefinedType();
516   AIDL_FATAL_IF(defined_type == nullptr, type);
517   return AlignmentOfDefinedType(*defined_type, typenames);
518 }
519 
AlignmentOfDefinedType(const AidlDefinedType & defined_type,const AidlTypenames & typenames)520 std::optional<size_t> AlignmentOfDefinedType(const AidlDefinedType& defined_type,
521                                              const AidlTypenames& typenames) {
522   if (!defined_type.IsFixedSize()) {
523     return std::nullopt;
524   }
525   // Overall alignment is the maximum alignment of all fields
526   size_t align = 1;
527   for (const auto& variable : defined_type.GetFields()) {
528     auto field_alignment = cpp::AlignmentOf(variable->GetType(), typenames);
529     AIDL_FATAL_IF(field_alignment == std::nullopt, defined_type);
530     if (*field_alignment > align) {
531       align = *field_alignment;
532     }
533   }
534   return align;
535 }
536 
SizeOf(const AidlTypeSpecifier & type,const AidlTypenames & typenames)537 std::optional<size_t> SizeOf(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
538   static map<string, size_t> sizes = {
539       {"boolean", 1}, {"byte", 1}, {"char", 2}, {"double", 8},
540       {"float", 4},   {"int", 4},  {"long", 8},
541   };
542   string name = type.GetName();
543   if (auto enum_decl = typenames.GetEnumDeclaration(type); enum_decl) {
544     name = enum_decl->GetBackingType().GetName();
545   }
546   // If it's an array of a basic type, take its dimensions into account for the size
547   size_t dims = 1;
548   if (type.IsFixedSizeArray()) {
549     AIDL_FATAL_IF(type.IsGeneric(), type);
550     const ArrayType& array = type.GetArray();
551     auto dimensions = std::get<FixedSizeArray>(array).GetDimensionInts();
552     for (auto dim : dimensions) {
553       dims *= dim;
554     }
555   }
556   auto it = sizes.find(name);
557   if (it != sizes.end()) {
558     size_t size = it->second;
559     return size * dims;
560   }
561   const AidlDefinedType* defined_type = type.GetDefinedType();
562   AIDL_FATAL_IF(defined_type == nullptr, type);
563   auto defined_type_size = SizeOfDefinedType(*defined_type, typenames);
564   if (defined_type_size) {
565     return *defined_type_size * dims;
566   }
567   return std::nullopt;
568 }
569 
AlignTo(size_t val,size_t align)570 size_t AlignTo(size_t val, size_t align) {
571   return (val + (align - 1)) & ~(align - 1);
572 }
573 
SizeOfDefinedType(const AidlDefinedType & defined_type,const AidlTypenames & typenames)574 std::optional<size_t> SizeOfDefinedType(const AidlDefinedType& defined_type,
575                                         const AidlTypenames& typenames) {
576   if (!defined_type.IsFixedSize()) {
577     return std::nullopt;
578   }
579   if (auto union_decl = defined_type.AsUnionDeclaration(); union_decl) {
580     // If it's a union find the size of the largest field
581     size_t size = 0;
582     for (const auto& variable : union_decl->GetFields()) {
583       const auto& var_type = variable->GetType();
584       auto field_size = cpp::SizeOf(var_type, typenames);
585       AIDL_FATAL_IF(field_size == std::nullopt, var_type);
586       if (*field_size > size) {
587         size = *field_size;
588       }
589     }
590     // union tag size is 1 byte plus padding based on overall alignment
591     auto align = cpp::AlignmentOfDefinedType(defined_type, typenames);
592     AIDL_FATAL_IF(align == std::nullopt, defined_type);
593     size_t tag_size = AlignTo(1, *align);
594     // Size of the union is largest field size plus its padding and the tag size
595     return AlignTo(size, *align) + tag_size;
596   }
597 
598   // If it's not a union add the sizes of all fields and padding
599   size_t res = 0;
600   for (const auto& variable : defined_type.GetFields()) {
601     // add padding for the previous field based off of the alignment of the current field
602     const auto& var_type = variable->GetType();
603     auto alignment = cpp::AlignmentOf(var_type, typenames);
604     AIDL_FATAL_IF(alignment == std::nullopt, var_type);
605     res = AlignTo(res, *alignment);
606 
607     // add the size of the current field itself
608     auto var_size = cpp::SizeOf(var_type, typenames);
609     AIDL_FATAL_IF(var_size == std::nullopt, var_type);
610     res += *var_size;
611   }
612   // add padding for the last field based off of the alignment of the overall struct
613   auto parcelable_alignment = cpp::AlignmentOfDefinedType(defined_type, typenames);
614   AIDL_FATAL_IF(parcelable_alignment == std::nullopt, defined_type);
615   res = AlignTo(res, *parcelable_alignment);
616 
617   // structs with no members are 1-byte in C++
618   if (res == 0) {
619     return 1;
620   }
621   return res;
622 }
623 
GetHeaders(const AidlUnionDecl & decl)624 std::set<std::string> UnionWriter::GetHeaders(const AidlUnionDecl& decl) {
625   std::set<std::string> union_headers = {
626       "cassert",      // __assert for logging
627       "type_traits",  // std::is_same_v
628       "utility",      // std::mode/forward for value
629       "variant",      // union's impl
630   };
631   if (decl.IsFixedSize()) {
632     union_headers.insert("tuple");  // fixed-sized union's typelist
633   }
634   return union_headers;
635 }
636 
637 // fixed-sized union class looks like:
638 // class Union {
639 // public:
640 //   enum Tag : uint8_t {
641 //     field1 = 0,
642 //     field2,
643 //   };
644 //  ... methods ...
645 // private:
646 //   Tag _tag;
647 //   union {
648 //     type1 field1;
649 //     type2 field2;
650 //   } _value;
651 // };
652 
PrivateFields(CodeWriter & out) const653 void UnionWriter::PrivateFields(CodeWriter& out) const {
654   if (decl.IsFixedSize()) {
655     AIDL_FATAL_IF(decl.GetFields().empty(), decl) << "Union '" << decl.GetName() << "' is empty.";
656     const auto& first_field = decl.GetFields()[0];
657     const auto& default_name = first_field->GetName();
658     const auto& default_value = name_of(first_field->GetType(), typenames) + "(" +
659                                 first_field->ValueString(decorator) + ")";
660 
661     out << "Tag _tag = " << default_name << ";\n";
662     out << "union _value_t {\n";
663     out.Indent();
664     out << "_value_t() {}\n";
665     out << "~_value_t() {}\n";
666     for (const auto& f : decl.GetFields()) {
667       const auto& fn = f->GetName();
668       out << name_of(f->GetType(), typenames) << " " << fn;
669       if (decl.IsFixedSize()) {
670         auto alignment = AlignmentOf(f->GetType(), typenames);
671         if (alignment) {
672           out << " __attribute__((aligned (" << std::to_string(*alignment) << ")))";
673         }
674       }
675       if (fn == default_name) {
676         out << " = " << default_value;
677       }
678       out << ";\n";
679     }
680     out.Dedent();
681     out << "} _value;\n";
682   } else {
683     vector<string> field_types;
684     for (const auto& f : decl.GetFields()) {
685       field_types.push_back(name_of(f->GetType(), typenames));
686     }
687     out << "std::variant<" + Join(field_types, ", ") + "> _value;\n";
688   }
689 }
690 
PublicFields(CodeWriter & out) const691 void UnionWriter::PublicFields(CodeWriter& out) const {
692   out << "// Expose tag symbols for legacy code\n";
693   for (const auto& f : decl.GetFields()) {
694     out << "static const inline Tag";
695     GenerateDeprecated(out, *f);
696     out << " " << f->GetName() << " = Tag::" << f->GetName() << ";\n";
697   }
698 
699   const auto& name = decl.GetName();
700 
701   if (decl.IsFixedSize()) {
702     vector<string> field_types;
703     for (const auto& f : decl.GetFields()) {
704       field_types.push_back(name_of(f->GetType(), typenames));
705     }
706     auto typelist = Join(field_types, ", ");
707     constexpr auto tmpl = R"--(
708 template <Tag _Tag>
709 using _at = typename std::tuple_element<static_cast<size_t>(_Tag), std::tuple<{typelist}>>::type;
710 template <Tag _Tag, typename _Type>
711 static {name} make(_Type&& _arg) {{
712   {name} _inst;
713   _inst.set<_Tag>(std::forward<_Type>(_arg));
714   return _inst;
715 }}
716 constexpr Tag getTag() const {{
717   return _tag;
718 }}
719 template <Tag _Tag>
720 const _at<_Tag>& get() const {{
721   if (_Tag != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
722   return *(_at<_Tag>*)(&_value);
723 }}
724 template <Tag _Tag>
725 _at<_Tag>& get() {{
726   if (_Tag != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
727   return *(_at<_Tag>*)(&_value);
728 }}
729 template <Tag _Tag, typename _Type>
730 void set(_Type&& _arg) {{
731   _tag = _Tag;
732   get<_Tag>() = std::forward<_Type>(_arg);
733 }}
734 )--";
735     out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("typelist", typelist));
736   } else {
737     AIDL_FATAL_IF(decl.GetFields().empty(), decl) << "Union '" << name << "' is empty.";
738     const auto& first_field = decl.GetFields()[0];
739     const auto& default_name = first_field->GetName();
740     const auto& default_value = name_of(first_field->GetType(), typenames) + "(" +
741                                 first_field->ValueString(decorator) + ")";
742 
743     constexpr auto tmpl = R"--(
744 template<typename _Tp>
745 static constexpr bool _not_self = !std::is_same_v<std::remove_cv_t<std::remove_reference_t<_Tp>>, {name}>;
746 
747 {name}() : _value(std::in_place_index<static_cast<size_t>({default_name})>, {default_value}) {{ }}
748 
749 template <typename _Tp, typename = std::enable_if_t<_not_self<_Tp>>>
750 // NOLINTNEXTLINE(google-explicit-constructor)
751 constexpr {name}(_Tp&& _arg)
752     : _value(std::forward<_Tp>(_arg)) {{}}
753 
754 template <size_t _Np, typename... _Tp>
755 constexpr explicit {name}(std::in_place_index_t<_Np>, _Tp&&... _args)
756     : _value(std::in_place_index<_Np>, std::forward<_Tp>(_args)...) {{}}
757 
758 template <Tag _tag, typename... _Tp>
759 static {name} make(_Tp&&... _args) {{
760   return {name}(std::in_place_index<static_cast<size_t>(_tag)>, std::forward<_Tp>(_args)...);
761 }}
762 
763 template <Tag _tag, typename _Tp, typename... _Up>
764 static {name} make(std::initializer_list<_Tp> _il, _Up&&... _args) {{
765   return {name}(std::in_place_index<static_cast<size_t>(_tag)>, std::move(_il), std::forward<_Up>(_args)...);
766 }}
767 
768 Tag getTag() const {{
769   return static_cast<Tag>(_value.index());
770 }}
771 
772 template <Tag _tag>
773 const auto& get() const {{
774   if (getTag() != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
775   return std::get<static_cast<size_t>(_tag)>(_value);
776 }}
777 
778 template <Tag _tag>
779 auto& get() {{
780   if (getTag() != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
781   return std::get<static_cast<size_t>(_tag)>(_value);
782 }}
783 
784 template <Tag _tag, typename... _Tp>
785 void set(_Tp&&... _args) {{
786   _value.emplace<static_cast<size_t>(_tag)>(std::forward<_Tp>(_args)...);
787 }}
788 
789 )--";
790     out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("default_name", default_name),
791                        fmt::arg("default_value", default_value));
792   }
793 }
794 
ReadFromParcel(CodeWriter & out,const ParcelWriterContext & ctx) const795 void UnionWriter::ReadFromParcel(CodeWriter& out, const ParcelWriterContext& ctx) const {
796   // Even though @FixedSize union may use a smaller type than int32_t, we need to read/write it
797   // as if it is int32_t for compatibility with other bckends.
798   auto tag_type = typenames.MakeResolvedType(AIDL_LOCATION_HERE, "int", /* is_array= */ false);
799 
800   const string tag = "_aidl_tag";
801   const string value = "_aidl_value";
802   const string status = "_aidl_ret_status";
803 
804   auto read_var = [&](const string& var, const AidlTypeSpecifier& type) {
805     out << fmt::format("{} {};\n", name_of(type, typenames), var);
806     out << fmt::format("if (({} = ", status);
807     ctx.read_func(out, var, type);
808     out << fmt::format(") != {}) return {};\n", ctx.status_ok, status);
809   };
810 
811   out << fmt::format("{} {};\n", ctx.status_type, status);
812   read_var(tag, *tag_type);
813   out << fmt::format("switch (static_cast<Tag>({})) {{\n", tag);
814   for (const auto& variable : decl.GetFields()) {
815     out << fmt::format("case {}: {{\n", variable->GetName());
816     out.Indent();
817     if (variable->IsNew()) {
818       out << fmt::format("if (true) return {};\n", ctx.status_bad);
819     }
820     const auto& type = variable->GetType();
821     read_var(value, type);
822     out << fmt::format("if constexpr (std::is_trivially_copyable_v<{}>) {{\n",
823                        name_of(type, typenames));
824     out.Indent();
825     out << fmt::format("set<{}>({});\n", variable->GetName(), value);
826     out.Dedent();
827     out << "} else {\n";
828     out.Indent();
829     // Even when the `if constexpr` is false, the compiler runs the tidy check for the
830     // next line, which doesn't make sense. Silence the check for the unreachable code.
831     out << "// NOLINTNEXTLINE(performance-move-const-arg)\n";
832     out << fmt::format("set<{}>(std::move({}));\n", variable->GetName(), value);
833     out.Dedent();
834     out << "}\n";
835     out << fmt::format("return {}; }}\n", ctx.status_ok);
836     out.Dedent();
837   }
838   out << "}\n";
839   out << fmt::format("return {};\n", ctx.status_bad);
840 }
841 
WriteToParcel(CodeWriter & out,const ParcelWriterContext & ctx) const842 void UnionWriter::WriteToParcel(CodeWriter& out, const ParcelWriterContext& ctx) const {
843   // Even though @FixedSize union may use a smaller type than int32_t, we need to read/write it
844   // as if it is int32_t for compatibility with other bckends.
845   auto tag_type = typenames.MakeResolvedType(AIDL_LOCATION_HERE, "int", /* is_array= */ false);
846 
847   const string tag = "_aidl_tag";
848   const string value = "_aidl_value";
849   const string status = "_aidl_ret_status";
850 
851   out << fmt::format("{} {} = ", ctx.status_type, status);
852   ctx.write_func(out, "static_cast<int32_t>(getTag())", *tag_type);
853   out << ";\n";
854   out << fmt::format("if ({} != {}) return {};\n", status, ctx.status_ok, status);
855   out << "switch (getTag()) {\n";
856   for (const auto& variable : decl.GetFields()) {
857     if (variable->IsDeprecated()) {
858       out << "#pragma clang diagnostic push\n";
859       out << "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n";
860     }
861     if (variable->IsNew()) {
862       out << fmt::format("case {}: return true ? {} : ", variable->GetName(), ctx.status_bad);
863     } else {
864       out << fmt::format("case {}: return ", variable->GetName());
865     }
866     ctx.write_func(out, "get<" + variable->GetName() + ">()", variable->GetType());
867     out << ";\n";
868     if (variable->IsDeprecated()) {
869       out << "#pragma clang diagnostic pop\n";
870     }
871   }
872   out << "}\n";
873   out << "__assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"can't reach here\");\n";
874 }
875 
CppConstantValueDecorator(const AidlTypeSpecifier & type,const std::variant<std::string,std::vector<std::string>> & raw_value,bool is_ndk)876 std::string CppConstantValueDecorator(
877     const AidlTypeSpecifier& type,
878     const std::variant<std::string, std::vector<std::string>>& raw_value, bool is_ndk) {
879   if (type.IsArray()) {
880     auto values = std::get<std::vector<std::string>>(raw_value);
881     // Hexadecimal literals for byte arrays should be casted to uint8_t
882     if (type.GetName() == "byte" &&
883         std::any_of(values.begin(), values.end(),
884                     [](const auto& value) { return !value.empty() && value[0] == '-'; })) {
885       for (auto& value : values) {
886         // cast only if necessary
887         if (value[0] == '-') {
888           value = "uint8_t(" + value + ")";
889         }
890       }
891     }
892     std::string value = "{" + Join(values, ", ") + "}";
893 
894     if (type.IsFixedSizeArray()) {
895       // For arrays, use double braces because arrays can be nested.
896       //  e.g.) array<array<int, 2>, 3> ints = {{ {{1,2}}, {{3,4}}, {{5,6}} }};
897       // Vectors might need double braces, but since we don't have nested vectors (yet)
898       // single brace would work even for optional vectors.
899       value = "{" + value + "}";
900     }
901 
902     if (!type.IsMutated() && type.IsNullable()) {
903       // For outermost std::optional<>, we need an additional brace pair to initialize its value.
904       value = "{" + value + "}";
905     }
906     return value;
907   }
908 
909   const std::string& value = std::get<std::string>(raw_value);
910   if (AidlTypenames::IsBuiltinTypename(type.GetName())) {
911     if (type.GetName() == "boolean") {
912       return value;
913     } else if (type.GetName() == "byte") {
914       return value;
915     } else if (type.GetName() == "char") {
916       // TODO: consider 'L'-prefix for wide char literal
917       return value;
918     } else if (type.GetName() == "double") {
919       return value;
920     } else if (type.GetName() == "float") {
921       return value;  // value has 'f' suffix
922     } else if (type.GetName() == "int") {
923       return value;
924     } else if (type.GetName() == "long") {
925       return value + "L";
926     } else if (type.GetName() == "String") {
927       if (is_ndk || type.IsUtf8InCpp()) {
928         return value;
929       } else {
930         return "::android::String16(" + value + ")";
931       }
932     }
933     AIDL_FATAL(type) << "Unknown built-in type: " << type.GetName();
934   }
935 
936   auto defined_type = type.GetDefinedType();
937   AIDL_FATAL_IF(!defined_type, type) << "Invalid type for \"" << value << "\"";
938   auto enum_type = defined_type->AsEnumDeclaration();
939   AIDL_FATAL_IF(!enum_type, type) << "Invalid type for \"" << value << "\"";
940 
941   auto cpp_type_name = "::" + Join(Split(enum_type->GetCanonicalName(), "."), "::");
942   if (is_ndk) {
943     cpp_type_name = "::aidl" + cpp_type_name;
944   }
945   return cpp_type_name + "::" + value.substr(value.find_last_of('.') + 1);
946 }
947 
948 // Collect all forward declarations for the type's interface header.
949 // Nested types are visited as well via VisitTopDown.
GenerateForwardDecls(CodeWriter & out,const AidlDefinedType & root_type,bool is_ndk)950 void GenerateForwardDecls(CodeWriter& out, const AidlDefinedType& root_type, bool is_ndk) {
951   struct Visitor : AidlVisitor {
952     using PackagePath = std::vector<std::string>;
953     struct ClassDeclInfo {
954       std::string template_decl;
955     };
956     std::map<PackagePath, std::map<std::string, ClassDeclInfo>> classes;
957     // Collect class names for each interface or parcelable type
958     void Visit(const AidlTypeSpecifier& type) override {
959       const auto defined_type = type.GetDefinedType();
960       if (defined_type && !defined_type->GetParentType()) {
961         // Forward declarations are not supported for nested types
962         auto package = defined_type->GetSplitPackage();
963         if (defined_type->AsInterface() != nullptr) {
964           auto name = ClassName(*defined_type, ClassNames::INTERFACE);
965           classes[package][std::move(name)] = ClassDeclInfo();
966         } else if (auto* p = defined_type->AsStructuredParcelable(); p != nullptr) {
967           auto name = defined_type->GetName();
968           ClassDeclInfo info;
969           info.template_decl = TemplateDecl(*p);
970           classes[package][std::move(name)] = std::move(info);
971         }
972       }
973     }
974   } v;
975   VisitTopDown(v, root_type);
976 
977   if (v.classes.empty()) {
978     return;
979   }
980 
981   for (const auto& it : v.classes) {
982     auto package = it.first;
983     auto& classes = it.second;
984 
985     if (is_ndk) {
986       package.insert(package.begin(), "aidl");
987     }
988 
989     std::string namespace_name = Join(package, "::");
990     if (!namespace_name.empty()) {
991       out << "namespace " << namespace_name << " {\n";
992     }
993     for (const auto& [name, info] : classes) {
994       out << info.template_decl << "class " << name << ";\n";
995     }
996     if (!namespace_name.empty()) {
997       out << "}  // namespace " << namespace_name << "\n";
998     }
999   }
1000 }
1001 }  // namespace cpp
1002 }  // namespace aidl
1003 }  // namespace android
1004