aidl_to_cpp_common.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 <unordered_map>
  17. #include "aidl_to_cpp_common.h"
  18. #include "logging.h"
  19. #include "os.h"
  20. namespace android {
  21. namespace aidl {
  22. namespace cpp {
  23. string ClassName(const AidlDefinedType& defined_type, ClassNames type) {
  24. string base_name = defined_type.GetName();
  25. if (base_name.length() >= 2 && base_name[0] == 'I' && isupper(base_name[1])) {
  26. base_name = base_name.substr(1);
  27. }
  28. switch (type) {
  29. case ClassNames::CLIENT:
  30. return "Bp" + base_name;
  31. case ClassNames::SERVER:
  32. return "Bn" + base_name;
  33. case ClassNames::INTERFACE:
  34. return "I" + base_name;
  35. case ClassNames::DEFAULT_IMPL:
  36. return "I" + base_name + "Default";
  37. case ClassNames::BASE:
  38. return base_name;
  39. case ClassNames::RAW:
  40. [[fallthrough]];
  41. default:
  42. return defined_type.GetName();
  43. }
  44. }
  45. std::string HeaderFile(const AidlDefinedType& defined_type, ClassNames class_type,
  46. bool use_os_sep) {
  47. std::string file_path = defined_type.GetPackage();
  48. for (char& c : file_path) {
  49. if (c == '.') {
  50. c = (use_os_sep) ? OS_PATH_SEPARATOR : '/';
  51. }
  52. }
  53. if (!file_path.empty()) {
  54. file_path += (use_os_sep) ? OS_PATH_SEPARATOR : '/';
  55. }
  56. file_path += ClassName(defined_type, class_type);
  57. file_path += ".h";
  58. return file_path;
  59. }
  60. void EnterNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
  61. const std::vector<std::string> packages = defined_type.GetSplitPackage();
  62. for (const std::string& package : packages) {
  63. out << "namespace " << package << " {\n";
  64. }
  65. }
  66. void LeaveNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
  67. const std::vector<std::string> packages = defined_type.GetSplitPackage();
  68. for (auto it = packages.rbegin(); it != packages.rend(); ++it) {
  69. out << "} // namespace " << *it << "\n";
  70. }
  71. }
  72. string BuildVarName(const AidlArgument& a) {
  73. string prefix = "out_";
  74. if (a.GetDirection() & AidlArgument::IN_DIR) {
  75. prefix = "in_";
  76. }
  77. return prefix + a.GetName();
  78. }
  79. struct TypeInfo {
  80. // name of the type in C++ output
  81. std::string cpp_name;
  82. // function that writes an expression to convert a variable to a Json::Value
  83. // object
  84. std::function<void(CodeWriter& w, const string& var_name, bool isNdk)> toJsonValueExpr;
  85. };
  86. const static std::unordered_map<std::string, TypeInfo> kTypeInfoMap = {
  87. {"void", {"void", nullptr}},
  88. {"boolean",
  89. {
  90. "bool",
  91. [](CodeWriter& c, const string& var_name, bool) {
  92. c << "Json::Value(" << var_name << "? \"true\" : \"false\")";
  93. },
  94. }},
  95. {"byte",
  96. {
  97. "int8_t",
  98. [](CodeWriter& c, const string& var_name, bool) {
  99. c << "Json::Value(" << var_name << ")";
  100. },
  101. }},
  102. {"char",
  103. {
  104. "char16_t",
  105. [](CodeWriter& c, const string& var_name, bool isNdk) {
  106. if (isNdk) {
  107. c << "Json::Value(" << var_name << ")";
  108. } else {
  109. c << "Json::Value(std::string(android::String8(&" << var_name << ", 1)))";
  110. }
  111. },
  112. }},
  113. {"int",
  114. {
  115. "int32_t",
  116. [](CodeWriter& c, const string& var_name, bool) {
  117. c << "Json::Value(" << var_name << ")";
  118. },
  119. }},
  120. {"long",
  121. {
  122. "int64_t",
  123. [](CodeWriter& c, const string& var_name, bool) {
  124. c << "Json::Value(static_cast<Json::Int64>(" << var_name << "))";
  125. },
  126. }},
  127. {"float",
  128. {
  129. "float",
  130. [](CodeWriter& c, const string& var_name, bool) {
  131. c << "Json::Value(" << var_name << ")";
  132. },
  133. }},
  134. {"double",
  135. {
  136. "double",
  137. [](CodeWriter& c, const string& var_name, bool) {
  138. c << "Json::Value(" << var_name << ")";
  139. },
  140. }},
  141. {"String",
  142. {
  143. "std::string",
  144. [](CodeWriter& c, const string& var_name, bool) {
  145. c << "Json::Value(" << var_name << ")";
  146. },
  147. }}
  148. // missing List, Map, ParcelFileDescriptor, IBinder
  149. };
  150. TypeInfo GetTypeInfo(const AidlTypeSpecifier& aidl) {
  151. CHECK(aidl.IsResolved()) << aidl.ToString();
  152. const string& aidl_name = aidl.GetName();
  153. TypeInfo info;
  154. if (AidlTypenames::IsBuiltinTypename(aidl_name)) {
  155. auto it = kTypeInfoMap.find(aidl_name);
  156. if (it != kTypeInfoMap.end()) {
  157. info = it->second;
  158. }
  159. }
  160. // Missing interface and parcelable type
  161. return info;
  162. }
  163. inline bool CanWriteLog(const TypeInfo& t) {
  164. return t.cpp_name != "";
  165. }
  166. bool CanWriteLog(const AidlTypeSpecifier& aidl) {
  167. return CanWriteLog(GetTypeInfo(aidl));
  168. }
  169. void WriteLogFor(CodeWriter& writer, const AidlTypeSpecifier& type, const std::string& name,
  170. bool isPointer, const std::string& log, bool isNdk) {
  171. const TypeInfo info = GetTypeInfo(type);
  172. if (!CanWriteLog(info)) {
  173. return;
  174. }
  175. const string var_object_expr = ((isPointer ? "*" : "")) + name;
  176. if (type.IsArray()) {
  177. writer << log << " = Json::Value(Json::arrayValue);\n";
  178. writer << "for (const auto& v: " << var_object_expr << ") " << log << ".append(";
  179. info.toJsonValueExpr(writer, "v", isNdk);
  180. writer << ");";
  181. } else {
  182. writer << log << " = ";
  183. info.toJsonValueExpr(writer, var_object_expr, isNdk);
  184. writer << ";";
  185. }
  186. writer << "\n";
  187. }
  188. void WriteLogForArguments(CodeWriterPtr& writer, const AidlArgument& a, bool isServer,
  189. string logVarName, bool isNdk) {
  190. if (!CanWriteLog(a.GetType())) {
  191. return;
  192. }
  193. string logElementVarName = "_log_arg_element";
  194. (*writer) << "{\n";
  195. (*writer).Indent();
  196. (*writer) << "Json::Value " << logElementVarName << "(Json::objectValue);\n";
  197. string varName = isServer || isNdk ? BuildVarName(a) : a.GetName();
  198. (*writer) << logElementVarName << "[\"name\"] = \"" << varName << "\";\n";
  199. bool isPointer = a.IsOut() && !isServer;
  200. WriteLogFor(*(writer.get()), a.GetType(), varName, isPointer, logElementVarName + "[\"value\"]",
  201. isNdk);
  202. (*writer) << logVarName << ".append(" << logElementVarName << ");\n";
  203. (*writer) << "}\n";
  204. (*writer).Dedent();
  205. }
  206. const string GenLogBeforeExecute(const string className, const AidlMethod& method, bool isServer,
  207. bool isNdk) {
  208. string code;
  209. CodeWriterPtr writer = CodeWriter::ForString(&code);
  210. (*writer) << "Json::Value _log_input_args(Json::arrayValue);\n";
  211. (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
  212. (*writer).Indent();
  213. for (const auto& a : method.GetArguments()) {
  214. if (a->IsIn()) {
  215. WriteLogForArguments(writer, *a, isServer, "_log_input_args", isNdk);
  216. }
  217. }
  218. (*writer).Dedent();
  219. (*writer) << "}\n";
  220. (*writer) << "auto _log_start = std::chrono::steady_clock::now();\n";
  221. writer->Close();
  222. return code;
  223. }
  224. const string GenLogAfterExecute(const string className, const AidlInterface& interface,
  225. const AidlMethod& method, const string& statusVarName,
  226. const string& returnVarName, bool isServer, bool isNdk) {
  227. string code;
  228. CodeWriterPtr writer = CodeWriter::ForString(&code);
  229. (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
  230. (*writer).Indent();
  231. // Write the log as a Json object. For example,
  232. //
  233. // Json log object for following interface description
  234. //
  235. // package foo.bar;
  236. // interface IFoo {
  237. // String TestMethod(int arg1, inout String[] arg2, out double arg3);
  238. // }
  239. //
  240. // would be:
  241. //
  242. // {
  243. // duration_ms: 100.42,
  244. // interface_name: "foo.bar.IFoo",
  245. // method_name: "TestMethod",
  246. // (proxy|stub)_address: "0x12345678",
  247. // input_args: [
  248. // {name: "arg1", value: 30,},
  249. // {name: "arg2", value: ["apple", "grape"],},
  250. // ],
  251. // output_args: [
  252. // {name: "arg2", value: ["mango", "banana"],},
  253. // {name: "arg3", value: "10.5",},
  254. // ],
  255. // _aidl_return: "ok",
  256. // binder_status: {
  257. // exception_code: -8,
  258. // exception_message: "Something wrong",
  259. // transaction_error: 0,
  260. // service_specific_error_code: -42,
  261. // },
  262. // }
  263. (*writer) << "auto _log_end = std::chrono::steady_clock::now();\n";
  264. (*writer) << "Json::Value _log_transaction(Json::objectValue);\n";
  265. (*writer) << "_log_transaction[\"duration_ms\"] = "
  266. << "std::chrono::duration<double, std::milli>(_log_end - "
  267. "_log_start).count();\n";
  268. (*writer) << "_log_transaction[\"interface_name\"] = "
  269. << "Json::Value(\"" << interface.GetCanonicalName() << "\");\n";
  270. (*writer) << "_log_transaction[\"method_name\"] = "
  271. << "Json::Value(\"" << method.GetName() << "\");\n";
  272. (*writer) << "_log_transaction[\"" << (isServer ? "stub_address" : "proxy_address") << "\"] = ";
  273. (*writer) << "Json::Value("
  274. << "(std::ostringstream() << "
  275. << (isNdk && isServer ? "_aidl_impl" : "static_cast<const void*>(this)") << ").str()"
  276. << ");\n";
  277. (*writer) << "_log_transaction[\"input_args\"] = _log_input_args;\n";
  278. (*writer) << "Json::Value _log_output_args(Json::arrayValue);\n";
  279. (*writer) << "Json::Value _log_status(Json::objectValue);\n";
  280. if (isNdk) {
  281. (*writer) << "_log_status[\"exception_code\"] = Json::Value(AStatus_getExceptionCode("
  282. << statusVarName << ".get()));\n";
  283. (*writer) << "_log_status[\"exception_message\"] = Json::Value(AStatus_getMessage("
  284. << statusVarName << ".get()));\n";
  285. (*writer) << "_log_status[\"transaction_error\"] = Json::Value(AStatus_getStatus("
  286. << statusVarName << ".get()));\n";
  287. (*writer) << "_log_status[\"service_specific_error_code\"] = "
  288. "Json::Value(AStatus_getServiceSpecificError("
  289. << statusVarName << ".get()));\n";
  290. } else {
  291. (*writer) << "_log_status[\"exception_code\"] = Json::Value(" << statusVarName
  292. << ".exceptionCode());\n";
  293. (*writer) << "_log_status[\"exception_message\"] = Json::Value(" << statusVarName
  294. << ".exceptionMessage());\n";
  295. (*writer) << "_log_status[\"transaction_error\"] = Json::Value(" << statusVarName
  296. << ".transactionError());\n";
  297. (*writer) << "_log_status[\"service_specific_error_code\"] = Json::Value(" << statusVarName
  298. << ".serviceSpecificErrorCode());\n";
  299. }
  300. (*writer) << "_log_transaction[\"binder_status\"] = _log_status;\n";
  301. for (const auto& a : method.GetOutArguments()) {
  302. WriteLogForArguments(writer, *a, isServer, "_log_output_args", isNdk);
  303. }
  304. (*writer) << "_log_transaction[\"output_args\"] = _log_output_args;\n";
  305. if (method.GetType().GetName() != "void") {
  306. WriteLogFor(*(writer.get()), method.GetType(), returnVarName, !isServer,
  307. "_log_transaction[\"" + returnVarName + "\"]", isNdk);
  308. }
  309. // call the user-provided function with the Json object for the entire
  310. // transaction
  311. (*writer) << className << "::logFunc(_log_transaction);\n";
  312. (*writer).Dedent();
  313. (*writer) << "}\n";
  314. writer->Close();
  315. return code;
  316. }
  317. } // namespace cpp
  318. } // namespace aidl
  319. } // namespace android