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 <set>
23 #include <unordered_map>
24 
25 #include "ast_cpp.h"
26 #include "comments.h"
27 #include "logging.h"
28 #include "os.h"
29 
30 using ::android::base::Join;
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 
ClassName(const AidlDefinedType & defined_type,ClassNames type)52 string ClassName(const AidlDefinedType& defined_type, ClassNames type) {
53   string base_name = defined_type.GetName();
54   if (base_name.length() >= 2 && base_name[0] == 'I' && isupper(base_name[1])) {
55     base_name = base_name.substr(1);
56   }
57 
58   switch (type) {
59     case ClassNames::CLIENT:
60       return "Bp" + base_name;
61     case ClassNames::SERVER:
62       return "Bn" + base_name;
63     case ClassNames::INTERFACE:
64       return "I" + base_name;
65     case ClassNames::DEFAULT_IMPL:
66       return "I" + base_name + "Default";
67     case ClassNames::BASE:
68       return base_name;
69     case ClassNames::RAW:
70       [[fallthrough]];
71     default:
72       return defined_type.GetName();
73   }
74 }
75 
HeaderFile(const AidlDefinedType & defined_type,ClassNames class_type,bool use_os_sep)76 std::string HeaderFile(const AidlDefinedType& defined_type, ClassNames class_type,
77                        bool use_os_sep) {
78   std::string file_path = defined_type.GetPackage();
79   for (char& c : file_path) {
80     if (c == '.') {
81       c = (use_os_sep) ? OS_PATH_SEPARATOR : '/';
82     }
83   }
84   if (!file_path.empty()) {
85     file_path += (use_os_sep) ? OS_PATH_SEPARATOR : '/';
86   }
87   file_path += ClassName(defined_type, class_type);
88   file_path += ".h";
89 
90   return file_path;
91 }
92 
EnterNamespace(CodeWriter & out,const AidlDefinedType & defined_type)93 void EnterNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
94   const std::vector<std::string> packages = defined_type.GetSplitPackage();
95   for (const std::string& package : packages) {
96     out << "namespace " << package << " {\n";
97   }
98 }
LeaveNamespace(CodeWriter & out,const AidlDefinedType & defined_type)99 void LeaveNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
100   const std::vector<std::string> packages = defined_type.GetSplitPackage();
101   for (auto it = packages.rbegin(); it != packages.rend(); ++it) {
102     out << "}  // namespace " << *it << "\n";
103   }
104 }
105 
BuildVarName(const AidlArgument & a)106 string BuildVarName(const AidlArgument& a) {
107   string prefix = "out_";
108   if (a.GetDirection() & AidlArgument::IN_DIR) {
109     prefix = "in_";
110   }
111   return prefix + a.GetName();
112 }
113 
WriteLogForArgument(CodeWriter & w,const AidlArgument & a,bool is_server,const string & log_var,bool is_ndk)114 void WriteLogForArgument(CodeWriter& w, const AidlArgument& a, bool is_server,
115                          const string& log_var, bool is_ndk) {
116   const string var_name = is_server || is_ndk ? BuildVarName(a) : a.GetName();
117   const bool is_pointer = a.IsOut() && !is_server;
118   const string value_expr = (is_pointer ? "*" : "") + var_name;
119   w << log_var
120     << ".emplace_back(\"" + var_name + "\", ::android::internal::ToString(" + value_expr + "));\n";
121 }
122 
GenLogBeforeExecute(const string className,const AidlMethod & method,bool isServer,bool isNdk)123 const string GenLogBeforeExecute(const string className, const AidlMethod& method, bool isServer,
124                                  bool isNdk) {
125   string code;
126   CodeWriterPtr writer = CodeWriter::ForString(&code);
127   (*writer) << className << "::TransactionLog _transaction_log;\n";
128 
129   (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
130   (*writer).Indent();
131 
132   for (const auto& a : method.GetInArguments()) {
133     WriteLogForArgument(*writer, *a, isServer, "_transaction_log.input_args", isNdk);
134   }
135 
136   (*writer).Dedent();
137   (*writer) << "}\n";
138 
139   (*writer) << "auto _log_start = std::chrono::steady_clock::now();\n";
140   writer->Close();
141   return code;
142 }
143 
GenLogAfterExecute(const string className,const AidlInterface & interface,const AidlMethod & method,const string & statusVarName,const string & returnVarName,bool isServer,bool isNdk)144 const string GenLogAfterExecute(const string className, const AidlInterface& interface,
145                                 const AidlMethod& method, const string& statusVarName,
146                                 const string& returnVarName, bool isServer, bool isNdk) {
147   string code;
148   CodeWriterPtr writer = CodeWriter::ForString(&code);
149 
150   (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
151   (*writer).Indent();
152   const auto address = (isNdk && isServer) ? "_aidl_impl.get()" : "static_cast<const void*>(this)";
153   (*writer) << "auto _log_end = std::chrono::steady_clock::now();\n";
154   (*writer) << "_transaction_log.duration_ms = std::chrono::duration<double, std::milli>(_log_end "
155                "- _log_start).count();\n";
156   (*writer) << "_transaction_log.interface_name = \"" << interface.GetCanonicalName() << "\";\n";
157   (*writer) << "_transaction_log.method_name = \"" << method.GetName() << "\";\n";
158   (*writer) << "_transaction_log.stub_address = " << (isServer ? address : "nullptr") << ";\n";
159   (*writer) << "_transaction_log.proxy_address = " << (isServer ? "nullptr" : address) << ";\n";
160 
161   if (isNdk) {
162     (*writer) << "_transaction_log.exception_code = AStatus_getExceptionCode(" << statusVarName
163               << ".get());\n";
164     (*writer) << "_transaction_log.exception_message = AStatus_getMessage(" << statusVarName
165               << ".get());\n";
166     (*writer) << "_transaction_log.transaction_error = AStatus_getStatus(" << statusVarName
167               << ".get());\n";
168     (*writer) << "_transaction_log.service_specific_error_code = AStatus_getServiceSpecificError("
169               << statusVarName << ".get());\n";
170   } else {
171     (*writer) << "_transaction_log.exception_code = " << statusVarName << ".exceptionCode();\n";
172     (*writer) << "_transaction_log.exception_message = " << statusVarName
173               << ".exceptionMessage();\n";
174     (*writer) << "_transaction_log.transaction_error = " << statusVarName
175               << ".transactionError();\n";
176     (*writer) << "_transaction_log.service_specific_error_code = " << statusVarName
177               << ".serviceSpecificErrorCode();\n";
178   }
179 
180   for (const auto& a : method.GetOutArguments()) {
181     WriteLogForArgument(*writer, *a, isServer, "_transaction_log.output_args", isNdk);
182   }
183 
184   if (method.GetType().GetName() != "void") {
185     const string expr = (isServer ? "" : "*") + returnVarName;
186     (*writer) << "_transaction_log.result = ::android::internal::ToString(" << expr << ");\n";
187   }
188 
189   // call the user-provided function with the transaction log object
190   (*writer) << className << "::logFunc(_transaction_log);\n";
191 
192   (*writer).Dedent();
193   (*writer) << "}\n";
194 
195   writer->Close();
196   return code;
197 }
198 
GenerateEnumValues(const AidlEnumDeclaration & enum_decl,const std::vector<std::string> & enclosing_namespaces_of_enum_decl)199 std::string GenerateEnumValues(const AidlEnumDeclaration& enum_decl,
200                                const std::vector<std::string>& enclosing_namespaces_of_enum_decl) {
201   const auto fq_name =
202       Join(Append(enclosing_namespaces_of_enum_decl, enum_decl.GetSplitPackage()), "::") +
203       "::" + enum_decl.GetName();
204   const auto size = enum_decl.GetEnumerators().size();
205   std::ostringstream code;
206   code << "#pragma clang diagnostic push\n";
207   code << "#pragma clang diagnostic ignored \"-Wc++17-extensions\"\n";
208   code << "template <>\n";
209   code << "constexpr inline std::array<" << fq_name << ", " << size << ">";
210   GenerateDeprecated(code, enum_decl);
211   code << " enum_values<" << fq_name << "> = {\n";
212   for (const auto& enumerator : enum_decl.GetEnumerators()) {
213     code << "  " << fq_name << "::" << enumerator->GetName() << ",\n";
214   }
215   code << "};\n";
216   code << "#pragma clang diagnostic pop\n";
217   return code.str();
218 }
219 
TemplateDecl(const AidlParcelable & defined_type)220 std::string TemplateDecl(const AidlParcelable& defined_type) {
221   std::string decl = "";
222   if (defined_type.IsGeneric()) {
223     std::vector<std::string> template_params;
224     for (const auto& parameter : defined_type.GetTypeParameters()) {
225       template_params.push_back(parameter);
226     }
227     decl = base::StringPrintf("template <typename %s>\n",
228                               base::Join(template_params, ", typename ").c_str());
229   }
230   return decl;
231 }
232 
GenerateParcelableComparisonOperators(CodeWriter & out,const AidlParcelable & parcelable)233 void GenerateParcelableComparisonOperators(CodeWriter& out, const AidlParcelable& parcelable) {
234   std::set<string> operators{"<", ">", "==", ">=", "<=", "!="};
235   bool is_empty = false;
236 
237   auto comparable = [&](const string& prefix) {
238     vector<string> fields;
239     if (auto p = parcelable.AsStructuredParcelable(); p != nullptr) {
240       is_empty = p->GetFields().empty();
241       for (const auto& f : p->GetFields()) {
242         fields.push_back(prefix + f->GetName());
243       }
244       return "std::tie(" + Join(fields, ", ") + ")";
245     } else if (auto p = parcelable.AsUnionDeclaration(); p != nullptr) {
246       return prefix + "_value";
247     } else {
248       AIDL_FATAL(parcelable) << "Unknown paracelable type";
249     }
250   };
251 
252   string lhs = comparable("");
253   string rhs = comparable("rhs.");
254   for (const auto& op : operators) {
255     out << "inline bool operator" << op << "(const " << parcelable.GetName() << "&"
256         << (is_empty ? "" : " rhs") << ") const {\n"
257         << "  return " << lhs << " " << op << " " << rhs << ";\n"
258         << "}\n";
259   }
260   out << "\n";
261 }
262 
263 // Output may look like:
264 // inline std::string toString() const {
265 //   std::ostringstream os;
266 //   os << "MyData{";
267 //   os << "field1: " << field1;
268 //   os << ", field2: " << v.field2;
269 //   ...
270 //   os << "}";
271 //   return os.str();
272 // }
GenerateToString(CodeWriter & out,const AidlStructuredParcelable & parcelable)273 void GenerateToString(CodeWriter& out, const AidlStructuredParcelable& parcelable) {
274   out << "inline std::string toString() const {\n";
275   out.Indent();
276   out << "std::ostringstream os;\n";
277   out << "os << \"" << parcelable.GetName() << "{\";\n";
278   bool first = true;
279   for (const auto& f : parcelable.GetFields()) {
280     if (first) {
281       out << "os << \"";
282       first = false;
283     } else {
284       out << "os << \", ";
285     }
286     out << f->GetName() << ": \" << ::android::internal::ToString(" << f->GetName() << ");\n";
287   }
288   out << "os << \"}\";\n";
289   out << "return os.str();\n";
290   out.Dedent();
291   out << "}\n";
292 }
293 
294 // Output may look like:
295 // inline std::string toString() const {
296 //   std::ostringstream os;
297 //   os << "MyData{";
298 //   switch (v.getTag()) {
299 //   case MyData::field: os << "field: " << v.get<MyData::field>(); break;
300 //   ...
301 //   }
302 //   os << "}";
303 //   return os.str();
304 // }
GenerateToString(CodeWriter & out,const AidlUnionDecl & parcelable)305 void GenerateToString(CodeWriter& out, const AidlUnionDecl& parcelable) {
306   out << "inline std::string toString() const {\n";
307   out.Indent();
308   out << "std::ostringstream os;\n";
309   out << "os << \"" + parcelable.GetName() + "{\";\n";
310   out << "switch (getTag()) {\n";
311   for (const auto& f : parcelable.GetFields()) {
312     const string tag = f->GetName();
313     out << "case " << tag << ": os << \"" << tag << ": \" << "
314         << "::android::internal::ToString(get<" + tag + ">()); break;\n";
315   }
316   out << "}\n";
317   out << "os << \"}\";\n";
318   out << "return os.str();\n";
319   out.Dedent();
320   out << "}\n";
321 }
322 
GetDeprecatedAttribute(const AidlCommentable & type)323 std::string GetDeprecatedAttribute(const AidlCommentable& type) {
324   if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
325     if (deprecated->note.empty()) {
326       return "__attribute__((deprecated))";
327     }
328     return "__attribute__((deprecated(" + QuotedEscape(deprecated->note) + ")))";
329   }
330   return "";
331 }
332 
333 const vector<string> UnionWriter::headers{
334     "cassert",      // __assert for logging
335     "type_traits",  // std::is_same_v
336     "utility",      // std::mode/forward for value
337     "variant",      // std::variant for value
338 };
339 
PrivateFields(CodeWriter & out) const340 void UnionWriter::PrivateFields(CodeWriter& out) const {
341   vector<string> field_types;
342   for (const auto& f : decl.GetFields()) {
343     field_types.push_back(name_of(f->GetType(), typenames));
344   }
345   out << "std::variant<" + Join(field_types, ", ") + "> _value;\n";
346 }
347 
PublicFields(CodeWriter & out) const348 void UnionWriter::PublicFields(CodeWriter& out) const {
349   AidlTypeSpecifier tag_type(AIDL_LOCATION_HERE, "int", /* is_array= */ false,
350                              /* type_params= */ nullptr, Comments{});
351   tag_type.Resolve(typenames);
352 
353   out << "enum Tag : " << name_of(tag_type, typenames) << " {\n";
354   bool is_first = true;
355   for (const auto& f : decl.GetFields()) {
356     out << "  " << f->GetName();
357     GenerateDeprecated(out, *f);
358     if (is_first) out << " = 0";
359     out << ",  // " << f->Signature() << ";\n";
360     is_first = false;
361   }
362   out << "};\n";
363 
364   const auto& name = decl.GetName();
365 
366   AIDL_FATAL_IF(decl.GetFields().empty(), decl) << "Union '" << name << "' is empty.";
367   const auto& first_field = decl.GetFields()[0];
368   const auto& default_name = first_field->GetName();
369   const auto& default_value =
370       name_of(first_field->GetType(), typenames) + "(" + first_field->ValueString(decorator) + ")";
371 
372   auto tmpl = R"--(
373 template<typename _Tp>
374 static constexpr bool _not_self = !std::is_same_v<std::remove_cv_t<std::remove_reference_t<_Tp>>, {name}>;
375 
376 {name}() : _value(std::in_place_index<{default_name}>, {default_value}) {{ }}
377 {name}(const {name}&) = default;
378 {name}({name}&&) = default;
379 {name}& operator=(const {name}&) = default;
380 {name}& operator=({name}&&) = default;
381 
382 template <typename _Tp, typename = std::enable_if_t<_not_self<_Tp>>>
383 // NOLINTNEXTLINE(google-explicit-constructor)
384 constexpr {name}(_Tp&& _arg)
385     : _value(std::forward<_Tp>(_arg)) {{}}
386 
387 template <size_t _Np, typename... _Tp>
388 constexpr explicit {name}(std::in_place_index_t<_Np>, _Tp&&... _args)
389     : _value(std::in_place_index<_Np>, std::forward<_Tp>(_args)...) {{}}
390 
391 template <Tag _tag, typename... _Tp>
392 static {name} make(_Tp&&... _args) {{
393   return {name}(std::in_place_index<_tag>, std::forward<_Tp>(_args)...);
394 }}
395 
396 template <Tag _tag, typename _Tp, typename... _Up>
397 static {name} make(std::initializer_list<_Tp> _il, _Up&&... _args) {{
398   return {name}(std::in_place_index<_tag>, std::move(_il), std::forward<_Up>(_args)...);
399 }}
400 
401 Tag getTag() const {{
402   return static_cast<Tag>(_value.index());
403 }}
404 
405 template <Tag _tag>
406 const auto& get() const {{
407   if (getTag() != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
408   return std::get<_tag>(_value);
409 }}
410 
411 template <Tag _tag>
412 auto& get() {{
413   if (getTag() != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
414   return std::get<_tag>(_value);
415 }}
416 
417 template <Tag _tag, typename... _Tp>
418 void set(_Tp&&... _args) {{
419   _value.emplace<_tag>(std::forward<_Tp>(_args)...);
420 }}
421 
422 )--";
423   out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("default_name", default_name),
424                      fmt::arg("default_value", default_value));
425 }
426 
ReadFromParcel(CodeWriter & out,const ParcelWriterContext & ctx) const427 void UnionWriter::ReadFromParcel(CodeWriter& out, const ParcelWriterContext& ctx) const {
428   AidlTypeSpecifier tag_type(AIDL_LOCATION_HERE, "int", /* is_array= */ false,
429                              /* type_params= */ nullptr, Comments{});
430   tag_type.Resolve(typenames);
431 
432   const string tag = "_aidl_tag";
433   const string value = "_aidl_value";
434   const string status = "_aidl_ret_status";
435 
436   auto read_var = [&](const string& var, const AidlTypeSpecifier& type) {
437     out << fmt::format("{} {};\n", name_of(type, typenames), var);
438     out << fmt::format("if (({} = ", status);
439     ctx.read_func(out, var, type);
440     out << fmt::format(") != {}) return {};\n", ctx.status_ok, status);
441   };
442 
443   out << fmt::format("{} {};\n", ctx.status_type, status);
444   read_var(tag, tag_type);
445   out << fmt::format("switch ({}) {{\n", tag);
446   for (const auto& variable : decl.GetFields()) {
447     out << fmt::format("case {}: {{\n", variable->GetName());
448     out.Indent();
449     const auto& type = variable->GetType();
450     read_var(value, type);
451     out << fmt::format("if constexpr (std::is_trivially_copyable_v<{}>) {{\n",
452                        name_of(type, typenames));
453     out.Indent();
454     out << fmt::format("set<{}>({});\n", variable->GetName(), value);
455     out.Dedent();
456     out << "} else {\n";
457     out.Indent();
458     // Even when the `if constexpr` is false, the compiler runs the tidy check for the
459     // next line, which doesn't make sense. Silence the check for the unreachable code.
460     out << "// NOLINTNEXTLINE(performance-move-const-arg)\n";
461     out << fmt::format("set<{}>(std::move({}));\n", variable->GetName(), value);
462     out.Dedent();
463     out << "}\n";
464     out << fmt::format("return {}; }}\n", ctx.status_ok);
465     out.Dedent();
466   }
467   out << "}\n";
468   out << fmt::format("return {};\n", ctx.status_bad);
469 }
470 
WriteToParcel(CodeWriter & out,const ParcelWriterContext & ctx) const471 void UnionWriter::WriteToParcel(CodeWriter& out, const ParcelWriterContext& ctx) const {
472   AidlTypeSpecifier tag_type(AIDL_LOCATION_HERE, "int", /* is_array= */ false,
473                              /* type_params= */ nullptr, Comments{});
474   tag_type.Resolve(typenames);
475 
476   const string tag = "_aidl_tag";
477   const string value = "_aidl_value";
478   const string status = "_aidl_ret_status";
479 
480   out << fmt::format("{} {} = ", ctx.status_type, status);
481   ctx.write_func(out, "getTag()", tag_type);
482   out << ";\n";
483   out << fmt::format("if ({} != {}) return {};\n", status, ctx.status_ok, status);
484   out << "switch (getTag()) {\n";
485   for (const auto& variable : decl.GetFields()) {
486     out << fmt::format("case {}: return ", variable->GetName());
487     ctx.write_func(out, "get<" + variable->GetName() + ">()", variable->GetType());
488     out << ";\n";
489   }
490   out << "}\n";
491   out << "__assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"can't reach here\");\n";
492 }
493 
494 }  // namespace cpp
495 }  // namespace aidl
496 }  // namespace android
497