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