Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2020, The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "generate_rust.h" |
| 18 | |
| 19 | #include <stdio.h> |
| 20 | #include <stdlib.h> |
| 21 | #include <string.h> |
| 22 | #include <map> |
| 23 | #include <memory> |
| 24 | #include <sstream> |
| 25 | |
| 26 | #include <android-base/stringprintf.h> |
Andrei Homescu | e61feb5 | 2020-08-18 15:44:24 -0700 | [diff] [blame] | 27 | #include <android-base/strings.h> |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 28 | |
| 29 | #include "aidl_to_cpp_common.h" |
| 30 | #include "aidl_to_rust.h" |
| 31 | #include "code_writer.h" |
| 32 | #include "logging.h" |
| 33 | |
Andrei Homescu | e61feb5 | 2020-08-18 15:44:24 -0700 | [diff] [blame] | 34 | using android::base::Join; |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 35 | using std::ostringstream; |
| 36 | using std::shared_ptr; |
| 37 | using std::string; |
| 38 | using std::unique_ptr; |
| 39 | using std::vector; |
| 40 | |
| 41 | namespace android { |
| 42 | namespace aidl { |
| 43 | namespace rust { |
| 44 | |
| 45 | static constexpr const char kArgumentPrefix[] = "_arg_"; |
| 46 | static constexpr const char kGetInterfaceVersion[] = "getInterfaceVersion"; |
| 47 | static constexpr const char kGetInterfaceHash[] = "getInterfaceHash"; |
| 48 | |
| 49 | void GenerateMangledAlias(CodeWriter& out, const AidlDefinedType* type) { |
| 50 | ostringstream alias; |
| 51 | for (const auto& component : type->GetSplitPackage()) { |
| 52 | alias << "_" << component.size() << "_" << component; |
| 53 | } |
| 54 | alias << "_" << type->GetName().size() << "_" << type->GetName(); |
| 55 | out << "pub(crate) mod mangled { pub use super::" << type->GetName() << " as " << alias.str() |
| 56 | << "; }\n"; |
| 57 | } |
| 58 | |
| 59 | string BuildArg(const AidlArgument& arg, const AidlTypenames& typenames) { |
| 60 | // We pass in parameters that are not primitives by const reference. |
| 61 | // Arrays get passed in as slices, which is handled in RustNameOf. |
| 62 | auto arg_mode = ArgumentStorageMode(arg, typenames); |
| 63 | auto arg_type = RustNameOf(arg.GetType(), typenames, arg_mode); |
| 64 | return kArgumentPrefix + arg.GetName() + ": " + arg_type; |
| 65 | } |
| 66 | |
| 67 | string BuildMethod(const AidlMethod& method, const AidlTypenames& typenames) { |
| 68 | auto method_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE); |
| 69 | auto return_type = string{"binder::public_api::Result<"} + method_type + ">"; |
| 70 | string parameters = "&self"; |
| 71 | for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) { |
| 72 | parameters += ", "; |
| 73 | parameters += BuildArg(*arg, typenames); |
| 74 | } |
| 75 | return "fn " + method.GetName() + "(" + parameters + ") -> " + return_type; |
| 76 | } |
| 77 | |
Steven Moreland | a7764e5 | 2020-10-27 17:29:29 +0000 | [diff] [blame] | 78 | void GenerateClientMethod(CodeWriter& out, const AidlInterface& iface, const AidlMethod& method, |
| 79 | const AidlTypenames& typenames, const Options& options, |
| 80 | const std::string& trait_name) { |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 81 | // Generate the method |
| 82 | out << BuildMethod(method, typenames) << " {\n"; |
| 83 | out.Indent(); |
| 84 | |
| 85 | if (!method.IsUserDefined()) { |
| 86 | if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) { |
| 87 | // Check if the version is in the cache |
| 88 | out << "let _aidl_version = " |
| 89 | "self.cached_version.load(std::sync::atomic::Ordering::Relaxed);\n"; |
| 90 | out << "if _aidl_version != -1 { return Ok(_aidl_version); }\n"; |
| 91 | } |
| 92 | |
| 93 | if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) { |
| 94 | out << "{\n"; |
| 95 | out << " let _aidl_hash_lock = self.cached_hash.lock().unwrap();\n"; |
| 96 | out << " if let Some(ref _aidl_hash) = *_aidl_hash_lock {\n"; |
| 97 | out << " return Ok(_aidl_hash.clone());\n"; |
| 98 | out << " }\n"; |
| 99 | out << "}\n"; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // Call transact() |
Steven Moreland | a7764e5 | 2020-10-27 17:29:29 +0000 | [diff] [blame] | 104 | vector<string> flags; |
| 105 | if (method.IsOneway()) flags.push_back("binder::SpIBinder::FLAG_ONEWAY"); |
| 106 | if (iface.IsSensitiveData()) flags.push_back("binder::SpIBinder::FLAG_CLEAR_BUF"); |
| 107 | |
| 108 | string transact_flags = flags.empty() ? "0" : Join(flags, " | "); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 109 | out << "let _aidl_reply = self.binder.transact(" |
| 110 | << "transactions::" << method.GetName() << ", " << transact_flags << ", |_aidl_data| {\n"; |
| 111 | out.Indent(); |
| 112 | |
Steven Moreland | a7764e5 | 2020-10-27 17:29:29 +0000 | [diff] [blame] | 113 | if (iface.IsSensitiveData()) { |
| 114 | out << "_aidl_data.mark_sensitive();\n"; |
| 115 | } |
| 116 | |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 117 | // Arguments |
| 118 | for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) { |
| 119 | auto arg_name = kArgumentPrefix + arg->GetName(); |
| 120 | if (arg->IsIn()) { |
| 121 | // If the argument is already a reference, don't reference it again |
| 122 | // (unless we turned it into an Option<&T>) |
| 123 | auto ref_mode = ArgumentReferenceMode(*arg, typenames); |
| 124 | if (IsReference(ref_mode)) { |
| 125 | out << "_aidl_data.write(" << arg_name << ")?;\n"; |
| 126 | } else { |
| 127 | out << "_aidl_data.write(&" << arg_name << ")?;\n"; |
| 128 | } |
| 129 | } else if (arg->GetType().IsArray()) { |
| 130 | // For out-only arrays, send the array size |
| 131 | if (arg->GetType().IsNullable()) { |
| 132 | out << "_aidl_data.write_slice_size(" << arg_name << ".as_deref())?;\n"; |
| 133 | } else { |
| 134 | out << "_aidl_data.write_slice_size(Some(" << arg_name << "))?;\n"; |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // Return Ok(()) if all the `_aidl_data.write(...)?;` calls pass |
| 140 | out << "Ok(())\n"; |
| 141 | out.Dedent(); |
| 142 | out << "});\n"; |
| 143 | |
| 144 | // Check for UNKNOWN_TRANSACTION and call the default impl |
| 145 | string default_args; |
| 146 | for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) { |
| 147 | if (!default_args.empty()) { |
| 148 | default_args += ", "; |
| 149 | } |
| 150 | default_args += kArgumentPrefix; |
| 151 | default_args += arg->GetName(); |
| 152 | } |
| 153 | out << "if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {\n"; |
| 154 | out << " if let Some(_aidl_default_impl) = <Self as " << trait_name << ">::getDefaultImpl() {\n"; |
| 155 | out << " return _aidl_default_impl." << method.GetName() << "(" << default_args << ");\n"; |
| 156 | out << " }\n"; |
| 157 | out << "}\n"; |
| 158 | |
| 159 | // Return all other errors |
| 160 | out << "let _aidl_reply = _aidl_reply?;\n"; |
| 161 | |
| 162 | string return_val = "()"; |
| 163 | if (!method.IsOneway()) { |
| 164 | // Check for errors |
| 165 | out << "let _aidl_status: binder::Status = _aidl_reply.read()?;\n"; |
| 166 | out << "if !_aidl_status.is_ok() { return Err(_aidl_status); }\n"; |
| 167 | |
| 168 | // Return reply value |
| 169 | if (method.GetType().GetName() != "void") { |
| 170 | auto return_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE); |
| 171 | out << "let _aidl_return: " << return_type << " = _aidl_reply.read()?;\n"; |
| 172 | return_val = "_aidl_return"; |
| 173 | |
| 174 | if (!method.IsUserDefined()) { |
| 175 | if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) { |
| 176 | out << "self.cached_version.store(_aidl_return, std::sync::atomic::Ordering::Relaxed);\n"; |
| 177 | } |
| 178 | if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) { |
| 179 | out << "*self.cached_hash.lock().unwrap() = Some(_aidl_return.clone());\n"; |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | for (const AidlArgument* arg : method.GetOutArguments()) { |
| 185 | out << "*" << kArgumentPrefix << arg->GetName() << " = _aidl_reply.read()?;\n"; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | // Return the result |
| 190 | out << "Ok(" << return_val << ")\n"; |
| 191 | out.Dedent(); |
| 192 | out << "}\n"; |
| 193 | } |
| 194 | |
| 195 | void GenerateServerTransaction(CodeWriter& out, const AidlMethod& method, |
| 196 | const AidlTypenames& typenames) { |
| 197 | out << "transactions::" << method.GetName() << " => {\n"; |
| 198 | out.Indent(); |
| 199 | |
| 200 | string args; |
| 201 | for (const auto& arg : method.GetArguments()) { |
| 202 | string arg_name = kArgumentPrefix + arg->GetName(); |
| 203 | StorageMode arg_mode; |
| 204 | if (arg->IsIn()) { |
| 205 | arg_mode = StorageMode::VALUE; |
| 206 | } else { |
| 207 | // We need a value we can call Default::default() on |
| 208 | arg_mode = StorageMode::DEFAULT_VALUE; |
| 209 | } |
| 210 | auto arg_type = RustNameOf(arg->GetType(), typenames, arg_mode); |
| 211 | |
| 212 | string arg_mut = arg->IsOut() ? "mut " : ""; |
| 213 | string arg_init = arg->IsIn() ? "_aidl_data.read()?" : "Default::default()"; |
| 214 | out << "let " << arg_mut << arg_name << ": " << arg_type << " = " << arg_init << ";\n"; |
| 215 | if (!arg->IsIn() && arg->GetType().IsArray()) { |
| 216 | // _aidl_data.resize_[nullable_]out_vec(&mut _arg_foo)?; |
| 217 | auto resize_name = arg->GetType().IsNullable() ? "resize_nullable_out_vec" : "resize_out_vec"; |
| 218 | out << "_aidl_data." << resize_name << "(&mut " << arg_name << ")?;\n"; |
| 219 | } |
| 220 | |
| 221 | auto ref_mode = ArgumentReferenceMode(*arg, typenames); |
| 222 | if (!args.empty()) { |
| 223 | args += ", "; |
| 224 | } |
| 225 | args += TakeReference(ref_mode, arg_name); |
| 226 | } |
| 227 | out << "let _aidl_return = _aidl_service." << method.GetName() << "(" << args << ");\n"; |
| 228 | |
| 229 | if (!method.IsOneway()) { |
| 230 | out << "match &_aidl_return {\n"; |
| 231 | out.Indent(); |
| 232 | out << "Ok(_aidl_return) => {\n"; |
| 233 | out.Indent(); |
| 234 | out << "_aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;\n"; |
| 235 | if (method.GetType().GetName() != "void") { |
| 236 | out << "_aidl_reply.write(_aidl_return)?;\n"; |
| 237 | } |
| 238 | |
| 239 | // Serialize out arguments |
| 240 | for (const AidlArgument* arg : method.GetOutArguments()) { |
| 241 | string arg_name = kArgumentPrefix + arg->GetName(); |
| 242 | |
| 243 | auto& arg_type = arg->GetType(); |
| 244 | if (!arg->IsIn() && arg_type.IsArray() && arg_type.GetName() == "ParcelFileDescriptor") { |
| 245 | // We represent arrays of ParcelFileDescriptor as |
| 246 | // Vec<Option<ParcelFileDescriptor>> when they're out-arguments, |
| 247 | // but we need all of them to be initialized to Some; if there's |
| 248 | // any None, return UNEXPECTED_NULL (this is what libbinder_ndk does) |
| 249 | out << "if " << arg_name << ".iter().any(Option::is_none) { " |
| 250 | << "return Err(binder::StatusCode::UNEXPECTED_NULL); }\n"; |
| 251 | } else if (!arg->IsIn() && !TypeHasDefault(arg_type, typenames)) { |
| 252 | // Unwrap out-only arguments that we wrapped in Option<T> |
| 253 | out << "let " << arg_name << " = " << arg_name |
| 254 | << ".ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n"; |
| 255 | } |
| 256 | |
| 257 | out << "_aidl_reply.write(&" << arg_name << ")?;\n"; |
| 258 | } |
| 259 | out.Dedent(); |
| 260 | out << "}\n"; |
| 261 | out << "Err(_aidl_status) => _aidl_reply.write(_aidl_status)?\n"; |
| 262 | out.Dedent(); |
| 263 | out << "}\n"; |
| 264 | } |
| 265 | out << "Ok(())\n"; |
| 266 | out.Dedent(); |
| 267 | out << "}\n"; |
| 268 | } |
| 269 | |
| 270 | void GenerateServerItems(CodeWriter& out, const AidlInterface* iface, |
| 271 | const AidlTypenames& typenames) { |
| 272 | auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE); |
| 273 | auto server_name = ClassName(*iface, cpp::ClassNames::SERVER); |
| 274 | |
| 275 | // Forward all IFoo functions from Binder to the inner object |
| 276 | out << "impl " << trait_name << " for binder::Binder<" << server_name << "> {\n"; |
| 277 | out.Indent(); |
| 278 | for (const auto& method : iface->GetMethods()) { |
| 279 | string args; |
| 280 | for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) { |
| 281 | if (!args.empty()) { |
| 282 | args += ", "; |
| 283 | } |
| 284 | args += kArgumentPrefix; |
| 285 | args += arg->GetName(); |
| 286 | } |
| 287 | out << BuildMethod(*method, typenames) << " { " |
| 288 | << "self.0." << method->GetName() << "(" << args << ") }\n"; |
| 289 | } |
| 290 | out.Dedent(); |
| 291 | out << "}\n"; |
| 292 | |
| 293 | out << "fn on_transact(" |
| 294 | "_aidl_service: &dyn " |
| 295 | << trait_name |
| 296 | << ", " |
| 297 | "_aidl_code: binder::TransactionCode, " |
| 298 | "_aidl_data: &binder::parcel::Parcel, " |
| 299 | "_aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {\n"; |
| 300 | out.Indent(); |
| 301 | out << "match _aidl_code {\n"; |
| 302 | out.Indent(); |
| 303 | for (const auto& method : iface->GetMethods()) { |
| 304 | GenerateServerTransaction(out, *method, typenames); |
| 305 | } |
| 306 | out << "_ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n"; |
| 307 | out.Dedent(); |
| 308 | out << "}\n"; |
| 309 | out.Dedent(); |
| 310 | out << "}\n"; |
| 311 | } |
| 312 | |
| 313 | bool GenerateRustInterface(const string& filename, const AidlInterface* iface, |
| 314 | const AidlTypenames& typenames, const IoDelegate& io_delegate, |
| 315 | const Options& options) { |
| 316 | CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename); |
| 317 | |
| 318 | *code_writer << "#![allow(non_upper_case_globals)]\n"; |
| 319 | *code_writer << "#![allow(non_snake_case)]\n"; |
| 320 | // Import IBinder for transact() |
| 321 | *code_writer << "#[allow(unused_imports)] use binder::IBinder;\n"; |
| 322 | |
| 323 | auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE); |
| 324 | auto client_name = ClassName(*iface, cpp::ClassNames::CLIENT); |
| 325 | auto server_name = ClassName(*iface, cpp::ClassNames::SERVER); |
| 326 | *code_writer << "use binder::declare_binder_interface;\n"; |
| 327 | *code_writer << "declare_binder_interface! {\n"; |
| 328 | code_writer->Indent(); |
| 329 | *code_writer << trait_name << "[\"" << iface->GetDescriptor() << "\"] {\n"; |
| 330 | code_writer->Indent(); |
| 331 | *code_writer << "native: " << server_name << "(on_transact),\n"; |
| 332 | *code_writer << "proxy: " << client_name << " {\n"; |
| 333 | code_writer->Indent(); |
| 334 | if (options.Version() > 0) { |
| 335 | string comma = options.Hash().empty() ? "" : ","; |
| 336 | *code_writer << "cached_version: " |
| 337 | "std::sync::atomic::AtomicI32 = " |
| 338 | "std::sync::atomic::AtomicI32::new(-1)" |
| 339 | << comma << "\n"; |
| 340 | } |
| 341 | if (!options.Hash().empty()) { |
| 342 | *code_writer << "cached_hash: " |
| 343 | "std::sync::Mutex<Option<String>> = " |
| 344 | "std::sync::Mutex::new(None)\n"; |
| 345 | } |
| 346 | code_writer->Dedent(); |
| 347 | *code_writer << "},\n"; |
| 348 | code_writer->Dedent(); |
| 349 | *code_writer << "}\n"; |
| 350 | code_writer->Dedent(); |
| 351 | *code_writer << "}\n"; |
| 352 | |
| 353 | *code_writer << "pub trait " << trait_name << ": binder::Interface + Send {\n"; |
| 354 | code_writer->Indent(); |
| 355 | *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \"" |
| 356 | << iface->GetDescriptor() << "\" }\n"; |
| 357 | |
| 358 | for (const auto& method : iface->GetMethods()) { |
| 359 | // Generate the method |
| 360 | *code_writer << BuildMethod(*method, typenames) << " {\n"; |
| 361 | code_writer->Indent(); |
| 362 | if (method->IsUserDefined()) { |
| 363 | // Return Err(UNKNOWN_TRANSACTION) by default |
| 364 | *code_writer << "Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())\n"; |
| 365 | } else { |
| 366 | // Generate default implementations for meta methods |
| 367 | // FIXME: is this fine, or do we want to leave the defaults out |
| 368 | // and force users to implement them manually (or with a helper macro we |
| 369 | // provide) on the server side? |
| 370 | if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) { |
| 371 | *code_writer << "Ok(VERSION)\n"; |
| 372 | } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) { |
| 373 | *code_writer << "Ok(HASH.into())\n"; |
| 374 | } |
| 375 | } |
| 376 | code_writer->Dedent(); |
| 377 | *code_writer << "}\n"; |
| 378 | } |
| 379 | |
| 380 | // Emit the default implementation code inside the trait |
| 381 | auto default_name = ClassName(*iface, cpp::ClassNames::DEFAULT_IMPL); |
| 382 | *code_writer << "fn getDefaultImpl()" |
| 383 | << " -> " << default_name << " where Self: Sized {\n"; |
| 384 | *code_writer << " DEFAULT_IMPL.lock().unwrap().clone()\n"; |
| 385 | *code_writer << "}\n"; |
| 386 | *code_writer << "fn setDefaultImpl(d: " << default_name << ")" |
| 387 | << " -> " << default_name << " where Self: Sized {\n"; |
| 388 | *code_writer << " std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)\n"; |
| 389 | *code_writer << "}\n"; |
| 390 | code_writer->Dedent(); |
| 391 | *code_writer << "}\n"; |
| 392 | |
| 393 | // Generate the transaction code constants |
| 394 | // The constants get their own sub-module to avoid conflicts |
| 395 | *code_writer << "pub mod transactions {\n"; |
| 396 | code_writer->Indent(); |
| 397 | // Import IBinder so we can access FIRST_CALL_TRANSACTION |
| 398 | *code_writer << "#[allow(unused_imports)] use binder::IBinder;\n"; |
| 399 | for (const auto& method : iface->GetMethods()) { |
| 400 | // Generate the transaction code constant |
| 401 | *code_writer << "pub const " << method->GetName() |
| 402 | << ": binder::TransactionCode = " |
| 403 | "binder::SpIBinder::FIRST_CALL_TRANSACTION + " + |
| 404 | std::to_string(method->GetId()) + ";\n"; |
| 405 | } |
| 406 | code_writer->Dedent(); |
| 407 | *code_writer << "}\n"; |
| 408 | |
| 409 | // Emit the default implementation code outside the trait |
| 410 | *code_writer << "pub type " << default_name << " = Option<std::sync::Arc<dyn " << trait_name |
| 411 | << " + Sync>>;\n"; |
| 412 | *code_writer << "use lazy_static::lazy_static;\n"; |
| 413 | *code_writer << "lazy_static! {\n"; |
| 414 | *code_writer << " static ref DEFAULT_IMPL: std::sync::Mutex<" << default_name |
| 415 | << "> = std::sync::Mutex::new(None);\n"; |
| 416 | *code_writer << "}\n"; |
| 417 | |
| 418 | // Emit the interface constants |
| 419 | for (const auto& constant : iface->GetConstantDeclarations()) { |
Steven Moreland | e689da2 | 2020-11-10 02:06:30 +0000 | [diff] [blame] | 420 | const AidlTypeSpecifier& type = constant->GetType(); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 421 | const AidlConstantValue& value = constant->GetValue(); |
Steven Moreland | e689da2 | 2020-11-10 02:06:30 +0000 | [diff] [blame] | 422 | |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 423 | string const_type; |
Jooyung Han | 965e31d | 2020-11-27 12:30:16 +0900 | [diff] [blame] | 424 | if (type.Signature() == "String") { |
Steven Moreland | e689da2 | 2020-11-10 02:06:30 +0000 | [diff] [blame] | 425 | const_type = "&str"; |
Jooyung Han | 965e31d | 2020-11-27 12:30:16 +0900 | [diff] [blame] | 426 | } else if (type.Signature() == "byte" || type.Signature() == "int" || |
| 427 | type.Signature() == "long") { |
Steven Moreland | e689da2 | 2020-11-10 02:06:30 +0000 | [diff] [blame] | 428 | const_type = RustNameOf(type, typenames, StorageMode::VALUE); |
| 429 | } else { |
Jooyung Han | 965e31d | 2020-11-27 12:30:16 +0900 | [diff] [blame] | 430 | AIDL_FATAL(value) << "Unrecognized constant type: " << type.Signature(); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 431 | } |
Steven Moreland | e689da2 | 2020-11-10 02:06:30 +0000 | [diff] [blame] | 432 | |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 433 | *code_writer << "pub const " << constant->GetName() << ": " << const_type << " = " |
| 434 | << constant->ValueString(ConstantValueDecoratorRef) << ";\n"; |
| 435 | } |
| 436 | |
| 437 | GenerateMangledAlias(*code_writer, iface); |
| 438 | |
| 439 | // Emit VERSION and HASH |
| 440 | // These need to be top-level item constants instead of associated consts |
| 441 | // because the latter are incompatible with trait objects, see |
| 442 | // https://doc.rust-lang.org/reference/items/traits.html#object-safety |
| 443 | if (options.Version() > 0) { |
| 444 | *code_writer << "pub const VERSION: i32 = " << std::to_string(options.Version()) << ";\n"; |
| 445 | } |
| 446 | if (!options.Hash().empty()) { |
| 447 | *code_writer << "pub const HASH: &str = \"" << options.Hash() << "\";\n"; |
| 448 | } |
| 449 | |
| 450 | // Generate the client-side methods |
| 451 | *code_writer << "impl " << trait_name << " for " << client_name << " {\n"; |
| 452 | code_writer->Indent(); |
| 453 | for (const auto& method : iface->GetMethods()) { |
Steven Moreland | a7764e5 | 2020-10-27 17:29:29 +0000 | [diff] [blame] | 454 | GenerateClientMethod(*code_writer, *iface, *method, typenames, options, trait_name); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 455 | } |
| 456 | code_writer->Dedent(); |
| 457 | *code_writer << "}\n"; |
| 458 | |
| 459 | // Generate the server-side methods |
| 460 | GenerateServerItems(*code_writer, iface, typenames); |
| 461 | |
| 462 | return true; |
| 463 | } |
| 464 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 465 | void GenerateParcelBody(CodeWriter& out, const AidlStructuredParcelable* parcel, |
| 466 | const AidlTypenames& typenames) { |
| 467 | out << "pub struct " << parcel->GetName() << " {\n"; |
| 468 | out.Indent(); |
| 469 | for (const auto& variable : parcel->GetFields()) { |
| 470 | auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD); |
| 471 | out << "pub " << variable->GetName() << ": " << field_type << ",\n"; |
| 472 | } |
| 473 | out.Dedent(); |
| 474 | out << "}\n"; |
| 475 | } |
| 476 | |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 477 | void GenerateParcelDefault(CodeWriter& out, const AidlStructuredParcelable* parcel) { |
| 478 | out << "impl Default for " << parcel->GetName() << " {\n"; |
| 479 | out.Indent(); |
| 480 | out << "fn default() -> Self {\n"; |
| 481 | out.Indent(); |
| 482 | out << "Self {\n"; |
| 483 | out.Indent(); |
| 484 | for (const auto& variable : parcel->GetFields()) { |
| 485 | if (variable->GetDefaultValue()) { |
| 486 | out << variable->GetName() << ": " << variable->ValueString(ConstantValueDecorator) << ",\n"; |
| 487 | } else { |
| 488 | out << variable->GetName() << ": Default::default(),\n"; |
| 489 | } |
| 490 | } |
| 491 | out.Dedent(); |
| 492 | out << "}\n"; |
| 493 | out.Dedent(); |
| 494 | out << "}\n"; |
| 495 | out.Dedent(); |
| 496 | out << "}\n"; |
| 497 | } |
| 498 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 499 | void GenerateParcelSerializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel, |
| 500 | const AidlTypenames& typenames) { |
| 501 | out << "parcel.sized_write(|subparcel| {\n"; |
| 502 | out.Indent(); |
| 503 | for (const auto& variable : parcel->GetFields()) { |
| 504 | if (!TypeHasDefault(variable->GetType(), typenames)) { |
| 505 | out << "let __field_ref = this." << variable->GetName() |
| 506 | << ".as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n"; |
| 507 | out << "subparcel.write(__field_ref)?;\n"; |
| 508 | } else { |
| 509 | out << "subparcel.write(&this." << variable->GetName() << ")?;\n"; |
| 510 | } |
| 511 | } |
| 512 | out << "Ok(())\n"; |
| 513 | out.Dedent(); |
| 514 | out << "})\n"; |
| 515 | } |
| 516 | |
| 517 | void GenerateParcelDeserializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel, |
| 518 | const AidlTypenames& typenames) { |
| 519 | out << "let start_pos = parcel.get_data_position();\n"; |
| 520 | out << "let parcelable_size: i32 = parcel.read()?;\n"; |
| 521 | out << "if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }\n"; |
| 522 | |
| 523 | // Pre-emit the common field epilogue code, shared between all fields: |
| 524 | ostringstream epilogue; |
| 525 | epilogue << "if (parcel.get_data_position() - start_pos) == parcelable_size {\n"; |
| 526 | // We assume the lhs can never be > parcelable_size, because then the read |
| 527 | // immediately preceding this check would have returned NOT_ENOUGH_DATA |
| 528 | epilogue << " return Ok(Some(result));\n"; |
| 529 | epilogue << "}\n"; |
| 530 | string epilogue_str = epilogue.str(); |
| 531 | |
| 532 | out << "let mut result = Self::default();\n"; |
| 533 | for (const auto& variable : parcel->GetFields()) { |
| 534 | if (!TypeHasDefault(variable->GetType(), typenames)) { |
| 535 | out << "result." << variable->GetName() << " = Some(parcel.read()?);\n"; |
| 536 | } else { |
| 537 | out << "result." << variable->GetName() << " = parcel.read()?;\n"; |
| 538 | } |
| 539 | out << epilogue_str; |
| 540 | } |
| 541 | |
| 542 | out << "Ok(Some(result))\n"; |
| 543 | } |
| 544 | |
| 545 | void GenerateParcelBody(CodeWriter& out, const AidlUnionDecl* parcel, |
| 546 | const AidlTypenames& typenames) { |
| 547 | out << "pub enum " << parcel->GetName() << " {\n"; |
| 548 | out.Indent(); |
| 549 | for (const auto& variable : parcel->GetFields()) { |
| 550 | auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD); |
| 551 | out << variable->GetCapitalizedName() << "(" << field_type << "),\n"; |
| 552 | } |
| 553 | out.Dedent(); |
| 554 | out << "}\n"; |
| 555 | } |
| 556 | |
| 557 | void GenerateParcelDefault(CodeWriter& out, const AidlUnionDecl* parcel) { |
| 558 | out << "impl Default for " << parcel->GetName() << " {\n"; |
| 559 | out.Indent(); |
| 560 | out << "fn default() -> Self {\n"; |
| 561 | out.Indent(); |
| 562 | |
| 563 | AIDL_FATAL_IF(parcel->GetFields().empty(), *parcel) |
| 564 | << "Union '" << parcel->GetName() << "' is empty."; |
| 565 | const auto& first_field = parcel->GetFields()[0]; |
| 566 | const auto& first_value = first_field->ValueString(ConstantValueDecorator); |
| 567 | |
| 568 | out << "Self::"; |
| 569 | if (first_field->GetDefaultValue()) { |
| 570 | out << first_field->GetCapitalizedName() << "(" << first_value << ")\n"; |
| 571 | } else { |
| 572 | out << first_field->GetCapitalizedName() << "(Default::default())\n"; |
| 573 | } |
| 574 | |
| 575 | out.Dedent(); |
| 576 | out << "}\n"; |
| 577 | out.Dedent(); |
| 578 | out << "}\n"; |
| 579 | } |
| 580 | |
| 581 | void GenerateParcelSerializeBody(CodeWriter& out, const AidlUnionDecl* parcel, |
| 582 | const AidlTypenames& typenames) { |
| 583 | out << "match this {\n"; |
| 584 | out.Indent(); |
| 585 | int tag = 0; |
| 586 | for (const auto& variable : parcel->GetFields()) { |
| 587 | out << "Self::" << variable->GetCapitalizedName() << "(v) => {\n"; |
| 588 | out.Indent(); |
| 589 | out << "parcel.write(&" << std::to_string(tag++) << "i32)?;\n"; |
| 590 | if (!TypeHasDefault(variable->GetType(), typenames)) { |
| 591 | out << "let __field_ref = v.as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n"; |
| 592 | out << "parcel.write(__field_ref)\n"; |
| 593 | } else { |
| 594 | out << "parcel.write(v)\n"; |
| 595 | } |
| 596 | out.Dedent(); |
| 597 | out << "}\n"; |
| 598 | } |
| 599 | out.Dedent(); |
| 600 | out << "}\n"; |
| 601 | } |
| 602 | |
| 603 | void GenerateParcelDeserializeBody(CodeWriter& out, const AidlUnionDecl* parcel, |
| 604 | const AidlTypenames& typenames) { |
| 605 | out << "let tag: i32 = parcel.read()?;\n"; |
| 606 | out << "match tag {\n"; |
| 607 | out.Indent(); |
| 608 | int tag = 0; |
| 609 | for (const auto& variable : parcel->GetFields()) { |
| 610 | auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD); |
| 611 | |
| 612 | out << std::to_string(tag++) << " => {\n"; |
| 613 | out.Indent(); |
| 614 | out << "let value: " << field_type << " = "; |
| 615 | if (!TypeHasDefault(variable->GetType(), typenames)) { |
| 616 | out << "Some(parcel.read()?);\n"; |
| 617 | } else { |
| 618 | out << "parcel.read()?;\n"; |
| 619 | } |
| 620 | out << "Ok(Some(Self::" << variable->GetCapitalizedName() << "(value)))\n"; |
| 621 | out.Dedent(); |
| 622 | out << "}\n"; |
| 623 | } |
| 624 | out << "_ => {\n"; |
| 625 | out << " Err(binder::StatusCode::BAD_VALUE)\n"; |
| 626 | out << "}\n"; |
| 627 | out.Dedent(); |
| 628 | out << "}\n"; |
| 629 | } |
| 630 | |
| 631 | template <typename ParcelableType> |
| 632 | void GenerateParcelSerialize(CodeWriter& out, const ParcelableType* parcel, |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 633 | const AidlTypenames& typenames) { |
| 634 | out << "impl binder::parcel::Serialize for " << parcel->GetName() << " {\n"; |
| 635 | out << " fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {\n"; |
| 636 | out << " <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)\n"; |
| 637 | out << " }\n"; |
| 638 | out << "}\n"; |
| 639 | |
| 640 | out << "impl binder::parcel::SerializeArray for " << parcel->GetName() << " {}\n"; |
| 641 | |
| 642 | out << "impl binder::parcel::SerializeOption for " << parcel->GetName() << " {\n"; |
| 643 | out.Indent(); |
| 644 | out << "fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> " |
| 645 | "binder::Result<()> {\n"; |
| 646 | out.Indent(); |
| 647 | out << "let this = if let Some(this) = this {\n"; |
| 648 | out << " parcel.write(&1i32)?;\n"; |
| 649 | out << " this\n"; |
| 650 | out << "} else {\n"; |
| 651 | out << " return parcel.write(&0i32);\n"; |
| 652 | out << "};\n"; |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 653 | |
| 654 | GenerateParcelSerializeBody(out, parcel, typenames); |
| 655 | |
Andrei Homescu | ad9d0da | 2020-08-06 18:43:40 -0700 | [diff] [blame] | 656 | out.Dedent(); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 657 | out << "}\n"; |
| 658 | out.Dedent(); |
| 659 | out << "}\n"; |
| 660 | } |
| 661 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 662 | template <typename ParcelableType> |
| 663 | void GenerateParcelDeserialize(CodeWriter& out, const ParcelableType* parcel, |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 664 | const AidlTypenames& typenames) { |
| 665 | out << "impl binder::parcel::Deserialize for " << parcel->GetName() << " {\n"; |
| 666 | out << " fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {\n"; |
| 667 | out << " <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)\n"; |
| 668 | out << " .transpose()\n"; |
| 669 | out << " .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))\n"; |
| 670 | out << " }\n"; |
| 671 | out << "}\n"; |
| 672 | |
| 673 | out << "impl binder::parcel::DeserializeArray for " << parcel->GetName() << " {}\n"; |
| 674 | |
| 675 | out << "impl binder::parcel::DeserializeOption for " << parcel->GetName() << " {\n"; |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 676 | out.Indent(); |
| 677 | out << "fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> " |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 678 | "{\n"; |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 679 | out.Indent(); |
| 680 | out << "let status: i32 = parcel.read()?;\n"; |
| 681 | out << "if status == 0 { return Ok(None); }\n"; |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 682 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 683 | GenerateParcelDeserializeBody(out, parcel, typenames); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 684 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 685 | out.Dedent(); |
| 686 | out << "}\n"; |
| 687 | out.Dedent(); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 688 | out << "}\n"; |
| 689 | } |
| 690 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 691 | template <typename ParcelableType> |
| 692 | bool GenerateRustParcel(const string& filename, const ParcelableType* parcel, |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 693 | const AidlTypenames& typenames, const IoDelegate& io_delegate) { |
| 694 | CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename); |
| 695 | |
Andrei Homescu | e61feb5 | 2020-08-18 15:44:24 -0700 | [diff] [blame] | 696 | // Debug is always derived because all Rust AIDL types implement it |
| 697 | // ParcelFileDescriptor doesn't support any of the others because |
| 698 | // it's a newtype over std::fs::File which only implements Debug |
| 699 | vector<string> derives{"Debug"}; |
| 700 | const AidlAnnotation* derive_annotation = parcel->RustDerive(); |
| 701 | if (derive_annotation != nullptr) { |
| 702 | for (const auto& name_and_param : derive_annotation->AnnotationParams(ConstantValueDecorator)) { |
| 703 | if (name_and_param.second == "true") { |
| 704 | derives.push_back(name_and_param.first); |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | *code_writer << "#[derive(" << Join(derives, ", ") << ")]\n"; |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 710 | GenerateParcelBody(*code_writer, parcel, typenames); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 711 | GenerateMangledAlias(*code_writer, parcel); |
| 712 | GenerateParcelDefault(*code_writer, parcel); |
| 713 | GenerateParcelSerialize(*code_writer, parcel, typenames); |
| 714 | GenerateParcelDeserialize(*code_writer, parcel, typenames); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 715 | return true; |
| 716 | } |
| 717 | |
| 718 | bool GenerateRustEnumDeclaration(const string& filename, const AidlEnumDeclaration* enum_decl, |
| 719 | const AidlTypenames& typenames, const IoDelegate& io_delegate) { |
| 720 | CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename); |
| 721 | |
| 722 | const auto& aidl_backing_type = enum_decl->GetBackingType(); |
| 723 | auto backing_type = RustNameOf(aidl_backing_type, typenames, StorageMode::VALUE); |
| 724 | |
| 725 | *code_writer << "#![allow(non_upper_case_globals)]\n"; |
Andrei Homescu | 0717c43 | 2020-09-04 17:41:00 -0700 | [diff] [blame] | 726 | *code_writer << "use binder::declare_binder_enum;\n"; |
| 727 | *code_writer << "declare_binder_enum! { " << enum_decl->GetName() << " : " << backing_type |
| 728 | << " {\n"; |
| 729 | code_writer->Indent(); |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 730 | for (const auto& enumerator : enum_decl->GetEnumerators()) { |
| 731 | auto value = enumerator->GetValue()->ValueString(aidl_backing_type, ConstantValueDecorator); |
Andrei Homescu | 0717c43 | 2020-09-04 17:41:00 -0700 | [diff] [blame] | 732 | *code_writer << enumerator->GetName() << " = " << value << ",\n"; |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 733 | } |
Andrei Homescu | 0717c43 | 2020-09-04 17:41:00 -0700 | [diff] [blame] | 734 | code_writer->Dedent(); |
| 735 | *code_writer << "} }\n"; |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 736 | |
| 737 | GenerateMangledAlias(*code_writer, enum_decl); |
| 738 | |
| 739 | return true; |
| 740 | } |
| 741 | |
| 742 | bool GenerateRust(const string& filename, const AidlDefinedType* defined_type, |
| 743 | const AidlTypenames& typenames, const IoDelegate& io_delegate, |
| 744 | const Options& options) { |
| 745 | if (const AidlStructuredParcelable* parcelable = defined_type->AsStructuredParcelable(); |
| 746 | parcelable != nullptr) { |
| 747 | return GenerateRustParcel(filename, parcelable, typenames, io_delegate); |
| 748 | } |
| 749 | |
Jooyung Han | f93b5bd | 2020-10-28 15:12:08 +0900 | [diff] [blame] | 750 | if (const AidlUnionDecl* parcelable = defined_type->AsUnionDeclaration(); parcelable != nullptr) { |
| 751 | return GenerateRustParcel(filename, parcelable, typenames, io_delegate); |
| 752 | } |
| 753 | |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 754 | if (const AidlEnumDeclaration* enum_decl = defined_type->AsEnumDeclaration(); |
| 755 | enum_decl != nullptr) { |
| 756 | return GenerateRustEnumDeclaration(filename, enum_decl, typenames, io_delegate); |
| 757 | } |
| 758 | |
| 759 | if (const AidlInterface* interface = defined_type->AsInterface(); interface != nullptr) { |
| 760 | return GenerateRustInterface(filename, interface, typenames, io_delegate, options); |
| 761 | } |
| 762 | |
Steven Moreland | 2178081 | 2020-09-11 01:29:45 +0000 | [diff] [blame] | 763 | AIDL_FATAL(filename) << "Unrecognized type sent for Rust generation."; |
Andrei Homescu | b62afd9 | 2020-05-11 19:24:59 -0700 | [diff] [blame] | 764 | return false; |
| 765 | } |
| 766 | |
| 767 | } // namespace rust |
| 768 | } // namespace aidl |
| 769 | } // namespace android |