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 <android-base/stringprintf.h>
20 #include <android-base/strings.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include <map>
26 #include <memory>
27 #include <sstream>
28
29 #include "aidl_to_common.h"
30 #include "aidl_to_cpp_common.h"
31 #include "aidl_to_rust.h"
32 #include "code_writer.h"
33 #include "comments.h"
34 #include "logging.h"
35
36 using android::base::Join;
37 using android::base::Split;
38 using std::ostringstream;
39 using std::shared_ptr;
40 using std::string;
41 using std::unique_ptr;
42 using std::vector;
43
44 namespace android {
45 namespace aidl {
46 namespace rust {
47
48 static constexpr const char kArgumentPrefix[] = "_arg_";
49 static constexpr const char kGetInterfaceVersion[] = "getInterfaceVersion";
50 static constexpr const char kGetInterfaceHash[] = "getInterfaceHash";
51
52 struct MangledAliasVisitor : AidlVisitor {
53 CodeWriter& out;
MangledAliasVisitorandroid::aidl::rust::MangledAliasVisitor54 MangledAliasVisitor(CodeWriter& out) : out(out) {}
Visitandroid::aidl::rust::MangledAliasVisitor55 void Visit(const AidlStructuredParcelable& type) override { VisitType(type); }
Visitandroid::aidl::rust::MangledAliasVisitor56 void Visit(const AidlInterface& type) override { VisitType(type); }
Visitandroid::aidl::rust::MangledAliasVisitor57 void Visit(const AidlEnumDeclaration& type) override { VisitType(type); }
Visitandroid::aidl::rust::MangledAliasVisitor58 void Visit(const AidlUnionDecl& type) override { VisitType(type); }
59 template <typename T>
VisitTypeandroid::aidl::rust::MangledAliasVisitor60 void VisitType(const T& type) {
61 out << " pub use " << Qname(type) << " as " << Mangled(type) << ";\n";
62 }
63 // Return a mangled name for a type (including AIDL package)
64 template <typename T>
Mangledandroid::aidl::rust::MangledAliasVisitor65 string Mangled(const T& type) const {
66 ostringstream alias;
67 for (const auto& component : Split(type.GetCanonicalName(), ".")) {
68 alias << "_" << component.size() << "_" << component;
69 }
70 return alias.str();
71 }
72 template <typename T>
Typenameandroid::aidl::rust::MangledAliasVisitor73 string Typename(const T& type) const {
74 if constexpr (std::is_same_v<T, AidlInterface>) {
75 return ClassName(type, cpp::ClassNames::INTERFACE);
76 } else {
77 return type.GetName();
78 }
79 }
80 // Return a fully qualified name for a type in the current file (excluding AIDL package)
81 template <typename T>
Qnameandroid::aidl::rust::MangledAliasVisitor82 string Qname(const T& type) const {
83 return Module(type) + "::r#" + Typename(type);
84 }
85 // Return a module name for a type (relative to the file)
86 template <typename T>
Moduleandroid::aidl::rust::MangledAliasVisitor87 string Module(const T& type) const {
88 if (type.GetParentType()) {
89 return Module(*type.GetParentType()) + "::r#" + type.GetName();
90 } else {
91 return "super";
92 }
93 }
94 };
95
GenerateMangledAliases(CodeWriter & out,const AidlDefinedType & type)96 void GenerateMangledAliases(CodeWriter& out, const AidlDefinedType& type) {
97 MangledAliasVisitor v(out);
98 out << "pub(crate) mod mangled {\n";
99 VisitTopDown(v, type);
100 out << "}\n";
101 }
102
BuildArg(const AidlArgument & arg,const AidlTypenames & typenames,Lifetime lifetime,bool is_vintf_stability,vector<string> & lifetimes)103 string BuildArg(const AidlArgument& arg, const AidlTypenames& typenames, Lifetime lifetime,
104 bool is_vintf_stability, vector<string>& lifetimes) {
105 // We pass in parameters that are not primitives by const reference.
106 // Arrays get passed in as slices, which is handled in RustNameOf.
107 auto arg_mode = ArgumentStorageMode(arg, typenames);
108 auto arg_type =
109 RustNameOf(arg.GetType(), typenames, arg_mode, lifetime, is_vintf_stability, lifetimes);
110 return kArgumentPrefix + arg.GetName() + ": " + arg_type;
111 }
112
113 enum class MethodKind {
114 // This is a normal non-async method.
115 NORMAL,
116 // This is an async method. Identical to NORMAL except that async is added
117 // in front of `fn`.
118 ASYNC,
119 // This is an async function, but using a boxed future instead of the async
120 // keyword.
121 BOXED_FUTURE,
122 // This could have been a non-async method, but it returns a Future so that
123 // it would not be breaking to make the function do async stuff in the future.
124 READY_FUTURE,
125 };
126
BuildMethod(const AidlMethod & method,const AidlTypenames & typenames,bool is_vintf_stability,const MethodKind kind=MethodKind::NORMAL)127 string BuildMethod(const AidlMethod& method, const AidlTypenames& typenames,
128 bool is_vintf_stability, const MethodKind kind = MethodKind::NORMAL) {
129 // We need to mark the arguments with the same lifetime when returning a future that actually
130 // captures the arguments, or a fresh lifetime otherwise to make automock work.
131 Lifetime arg_lifetime;
132 switch (kind) {
133 case MethodKind::NORMAL:
134 case MethodKind::ASYNC:
135 case MethodKind::READY_FUTURE:
136 arg_lifetime = Lifetime::FRESH;
137 break;
138 case MethodKind::BOXED_FUTURE:
139 arg_lifetime = Lifetime::A;
140 break;
141 }
142
143 // Collect the lifetimes used in all types we generate for this method.
144 vector<string> lifetimes;
145
146 // Always use lifetime `'a` for the `self` parameter, so we can use the same lifetime in the
147 // return value (if any) to match Rust's lifetime elision rules.
148 auto method_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE, Lifetime::A,
149 is_vintf_stability, lifetimes);
150 auto return_type = string{"binder::Result<"} + method_type + ">";
151 auto fn_prefix = string{""};
152
153 switch (kind) {
154 case MethodKind::NORMAL:
155 // Don't wrap the return type in anything.
156 break;
157 case MethodKind::ASYNC:
158 fn_prefix = "async ";
159 break;
160 case MethodKind::BOXED_FUTURE:
161 return_type = "binder::BoxFuture<'a, " + return_type + ">";
162 break;
163 case MethodKind::READY_FUTURE:
164 return_type = "std::future::Ready<" + return_type + ">";
165 break;
166 }
167
168 string parameters = "&" + RustLifetimeName(Lifetime::A, lifetimes) + "self";
169 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
170 parameters += ", ";
171 parameters += BuildArg(*arg, typenames, arg_lifetime, is_vintf_stability, lifetimes);
172 }
173
174 string lifetimes_str = "<";
175 for (const string& lifetime : lifetimes) {
176 lifetimes_str += "'" + lifetime + ", ";
177 }
178 lifetimes_str += ">";
179
180 return fn_prefix + "fn r#" + method.GetName() + lifetimes_str + "(" + parameters + ") -> " +
181 return_type;
182 }
183
GenerateClientMethodHelpers(CodeWriter & out,const AidlInterface & iface,const AidlMethod & method,const AidlTypenames & typenames,const Options & options,const std::string & default_trait_name,bool is_vintf_stability)184 void GenerateClientMethodHelpers(CodeWriter& out, const AidlInterface& iface,
185 const AidlMethod& method, const AidlTypenames& typenames,
186 const Options& options, const std::string& default_trait_name,
187 bool is_vintf_stability) {
188 string parameters = "&self";
189 vector<string> lifetimes;
190 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
191 parameters += ", ";
192 parameters += BuildArg(*arg, typenames, Lifetime::NONE, is_vintf_stability, lifetimes);
193 }
194
195 // Generate build_parcel helper.
196 out << "fn build_parcel_" + method.GetName() + "(" + parameters +
197 ") -> binder::Result<binder::binder_impl::Parcel> {\n";
198 out.Indent();
199
200 out << "let mut aidl_data = self.binder.prepare_transact()?;\n";
201
202 if (iface.IsSensitiveData()) {
203 out << "aidl_data.mark_sensitive();\n";
204 }
205
206 // Arguments
207 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
208 auto arg_name = kArgumentPrefix + arg->GetName();
209 if (arg->IsIn()) {
210 // If the argument is already a reference, don't reference it again
211 // (unless we turned it into an Option<&T>)
212 auto ref_mode = ArgumentReferenceMode(*arg, typenames);
213 if (IsReference(ref_mode)) {
214 out << "aidl_data.write(" << arg_name << ")?;\n";
215 } else {
216 out << "aidl_data.write(&" << arg_name << ")?;\n";
217 }
218 } else if (arg->GetType().IsDynamicArray()) {
219 // For out-only arrays, send the array size
220 if (arg->GetType().IsNullable()) {
221 out << "aidl_data.write_slice_size(" << arg_name << ".as_deref())?;\n";
222 } else {
223 out << "aidl_data.write_slice_size(Some(" << arg_name << "))?;\n";
224 }
225 }
226 }
227
228 out << "Ok(aidl_data)\n";
229 out.Dedent();
230 out << "}\n";
231
232 // Generate read_response helper.
233 auto return_type =
234 RustNameOf(method.GetType(), typenames, StorageMode::VALUE, is_vintf_stability);
235 out << "fn read_response_" + method.GetName() + "(" + parameters +
236 ", _aidl_reply: std::result::Result<binder::binder_impl::Parcel, "
237 "binder::StatusCode>) -> binder::Result<" +
238 return_type + "> {\n";
239 out.Indent();
240
241 // Check for UNKNOWN_TRANSACTION and call the default impl
242 if (method.IsUserDefined()) {
243 string default_args;
244 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
245 if (!default_args.empty()) {
246 default_args += ", ";
247 }
248 default_args += kArgumentPrefix;
249 default_args += arg->GetName();
250 }
251 out << "if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {\n";
252 out << " if let Some(_aidl_default_impl) = <Self as " << default_trait_name
253 << ">::getDefaultImpl() {\n";
254 out << " return _aidl_default_impl.r#" << method.GetName() << "(" << default_args << ");\n";
255 out << " }\n";
256 out << "}\n";
257 }
258
259 // Return all other errors
260 out << "let _aidl_reply = _aidl_reply?;\n";
261
262 string return_val = "()";
263 if (!method.IsOneway()) {
264 // Check for errors
265 out << "let _aidl_status: binder::Status = _aidl_reply.read()?;\n";
266 out << "if !_aidl_status.is_ok() { return Err(_aidl_status); }\n";
267
268 // Return reply value
269 if (method.GetType().GetName() != "void") {
270 auto return_type =
271 RustNameOf(method.GetType(), typenames, StorageMode::VALUE, is_vintf_stability);
272 out << "let _aidl_return: " << return_type << " = _aidl_reply.read()?;\n";
273 return_val = "_aidl_return";
274
275 if (!method.IsUserDefined()) {
276 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
277 out << "self.cached_version.store(_aidl_return, std::sync::atomic::Ordering::Relaxed);\n";
278 }
279 if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
280 out << "*self.cached_hash.lock().unwrap() = Some(_aidl_return.clone());\n";
281 }
282 }
283 }
284
285 for (const AidlArgument* arg : method.GetOutArguments()) {
286 out << "_aidl_reply.read_onto(" << kArgumentPrefix << arg->GetName() << ")?;\n";
287 }
288 }
289
290 // Return the result
291 out << "Ok(" << return_val << ")\n";
292
293 out.Dedent();
294 out << "}\n";
295 }
296
GenerateClientMethod(CodeWriter & out,const AidlInterface & iface,const AidlMethod & method,const AidlTypenames & typenames,const Options & options,const MethodKind kind)297 void GenerateClientMethod(CodeWriter& out, const AidlInterface& iface, const AidlMethod& method,
298 const AidlTypenames& typenames, const Options& options,
299 const MethodKind kind) {
300 // Generate the method
301 out << BuildMethod(method, typenames, iface.IsVintfStability(), kind) << " {\n";
302 out.Indent();
303
304 if (!method.IsUserDefined()) {
305 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
306 // Check if the version is in the cache
307 out << "let _aidl_version = "
308 "self.cached_version.load(std::sync::atomic::Ordering::Relaxed);\n";
309 switch (kind) {
310 case MethodKind::NORMAL:
311 case MethodKind::ASYNC:
312 out << "if _aidl_version != -1 { return Ok(_aidl_version); }\n";
313 break;
314 case MethodKind::BOXED_FUTURE:
315 out << "if _aidl_version != -1 { return Box::pin(std::future::ready(Ok(_aidl_version))); "
316 "}\n";
317 break;
318 case MethodKind::READY_FUTURE:
319 out << "if _aidl_version != -1 { return std::future::ready(Ok(_aidl_version)); }\n";
320 break;
321 }
322 }
323
324 if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
325 out << "{\n";
326 out << " let _aidl_hash_lock = self.cached_hash.lock().unwrap();\n";
327 out << " if let Some(ref _aidl_hash) = *_aidl_hash_lock {\n";
328 switch (kind) {
329 case MethodKind::NORMAL:
330 case MethodKind::ASYNC:
331 out << " return Ok(_aidl_hash.clone());\n";
332 break;
333 case MethodKind::BOXED_FUTURE:
334 out << " return Box::pin(std::future::ready(Ok(_aidl_hash.clone())));\n";
335 break;
336 case MethodKind::READY_FUTURE:
337 out << " return std::future::ready(Ok(_aidl_hash.clone()));\n";
338 break;
339 }
340 out << " }\n";
341 out << "}\n";
342 }
343 }
344
345 string build_parcel_args;
346 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
347 if (!build_parcel_args.empty()) {
348 build_parcel_args += ", ";
349 }
350 build_parcel_args += kArgumentPrefix;
351 build_parcel_args += arg->GetName();
352 }
353
354 string read_response_args =
355 build_parcel_args.empty() ? "_aidl_reply" : build_parcel_args + ", _aidl_reply";
356
357 vector<string> flags;
358 if (method.IsOneway()) flags.push_back("binder::binder_impl::FLAG_ONEWAY");
359 if (iface.IsSensitiveData()) flags.push_back("binder::binder_impl::FLAG_CLEAR_BUF");
360 flags.push_back("FLAG_PRIVATE_LOCAL");
361 string transact_flags = flags.empty() ? "0" : Join(flags, " | ");
362
363 switch (kind) {
364 case MethodKind::NORMAL:
365 case MethodKind::ASYNC:
366 if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
367 method.IsUserDefined()) {
368 out << "if (true) {\n";
369 out << " return Err(binder::Status::from(binder::StatusCode::UNKNOWN_TRANSACTION));\n";
370 out << "} else {\n";
371 out.Indent();
372 }
373 // Prepare transaction.
374 out << "let _aidl_data = self.build_parcel_" + method.GetName() + "(" + build_parcel_args +
375 ")?;\n";
376 // Submit transaction.
377 out << "let _aidl_reply = self.binder.submit_transact(transactions::r#" << method.GetName()
378 << ", _aidl_data, " << transact_flags << ");\n";
379 // Deserialize response.
380 out << "self.read_response_" + method.GetName() + "(" + read_response_args + ")\n";
381 break;
382 case MethodKind::READY_FUTURE:
383 if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
384 method.IsUserDefined()) {
385 out << "if (true) {\n";
386 out << " return "
387 "std::future::ready(Err(binder::Status::from(binder::StatusCode::UNKNOWN_"
388 "TRANSACTION)));\n";
389 out << "} else {\n";
390 out.Indent();
391 }
392 // Prepare transaction.
393 out << "let _aidl_data = match self.build_parcel_" + method.GetName() + "(" +
394 build_parcel_args + ") {\n";
395 out.Indent();
396 out << "Ok(_aidl_data) => _aidl_data,\n";
397 out << "Err(err) => return std::future::ready(Err(err)),\n";
398 out.Dedent();
399 out << "};\n";
400 // Submit transaction.
401 out << "let _aidl_reply = self.binder.submit_transact(transactions::r#" << method.GetName()
402 << ", _aidl_data, " << transact_flags << ");\n";
403 // Deserialize response.
404 out << "std::future::ready(self.read_response_" + method.GetName() + "(" +
405 read_response_args + "))\n";
406 break;
407 case MethodKind::BOXED_FUTURE:
408 if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
409 method.IsUserDefined()) {
410 out << "if (true) {\n";
411 out << " return "
412 "Box::pin(std::future::ready(Err(binder::Status::from(binder::StatusCode::UNKNOWN_"
413 "TRANSACTION))));\n";
414 out << "} else {\n";
415 out.Indent();
416 }
417 // Prepare transaction.
418 out << "let _aidl_data = match self.build_parcel_" + method.GetName() + "(" +
419 build_parcel_args + ") {\n";
420 out.Indent();
421 out << "Ok(_aidl_data) => _aidl_data,\n";
422 out << "Err(err) => return Box::pin(std::future::ready(Err(err))),\n";
423 out.Dedent();
424 out << "};\n";
425 // Submit transaction.
426 out << "let binder = self.binder.clone();\n";
427 out << "P::spawn(\n";
428 out.Indent();
429 out << "move || binder.submit_transact(transactions::r#" << method.GetName()
430 << ", _aidl_data, " << transact_flags << "),\n";
431 out << "move |_aidl_reply| async move {\n";
432 out.Indent();
433 // Deserialize response.
434 out << "self.read_response_" + method.GetName() + "(" + read_response_args + ")\n";
435 out.Dedent();
436 out << "}\n";
437 out.Dedent();
438 out << ")\n";
439 break;
440 }
441
442 if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
443 method.IsUserDefined()) {
444 out.Dedent();
445 out << "}\n";
446 }
447 out.Dedent();
448 out << "}\n";
449 }
450
GenerateServerTransaction(CodeWriter & out,const AidlInterface & interface,const AidlMethod & method,const AidlTypenames & typenames)451 void GenerateServerTransaction(CodeWriter& out, const AidlInterface& interface,
452 const AidlMethod& method, const AidlTypenames& typenames) {
453 out << "transactions::r#" << method.GetName() << " => {\n";
454 out.Indent();
455 if (method.IsUserDefined() && method.IsNew() &&
456 ShouldForceDowngradeFor(CommunicationSide::READ)) {
457 out << "if (true) {\n";
458 out << " Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n";
459 out << "} else {\n";
460 out.Indent();
461 }
462
463 if (interface.EnforceExpression() || method.GetType().EnforceExpression()) {
464 out << "compile_error!(\"Permission checks not support for the Rust backend\");\n";
465 }
466
467 string args;
468 for (const auto& arg : method.GetArguments()) {
469 string arg_name = kArgumentPrefix + arg->GetName();
470 StorageMode arg_mode;
471 if (arg->IsIn()) {
472 arg_mode = StorageMode::VALUE;
473 } else {
474 // We need a value we can call Default::default() on
475 arg_mode = StorageMode::DEFAULT_VALUE;
476 }
477 auto arg_type = RustNameOf(arg->GetType(), typenames, arg_mode, interface.IsVintfStability());
478
479 string arg_mut = arg->IsOut() ? "mut " : "";
480 string arg_init = arg->IsIn() ? "_aidl_data.read()?" : "Default::default()";
481 out << "let " << arg_mut << arg_name << ": " << arg_type << " = " << arg_init << ";\n";
482 if (!arg->IsIn() && arg->GetType().IsDynamicArray()) {
483 // _aidl_data.resize_[nullable_]out_vec(&mut _arg_foo)?;
484 auto resize_name = arg->GetType().IsNullable() ? "resize_nullable_out_vec" : "resize_out_vec";
485 out << "_aidl_data." << resize_name << "(&mut " << arg_name << ")?;\n";
486 }
487
488 auto ref_mode = ArgumentReferenceMode(*arg, typenames);
489 if (!args.empty()) {
490 args += ", ";
491 }
492 args += TakeReference(ref_mode, arg_name);
493 }
494 out << "let _aidl_return = _aidl_service.r#" << method.GetName() << "(" << args << ");\n";
495
496 if (!method.IsOneway()) {
497 out << "match &_aidl_return {\n";
498 out.Indent();
499 out << "Ok(_aidl_return) => {\n";
500 out.Indent();
501 out << "_aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;\n";
502 if (method.GetType().GetName() != "void") {
503 out << "_aidl_reply.write(_aidl_return)?;\n";
504 }
505
506 // Serialize out arguments
507 for (const AidlArgument* arg : method.GetOutArguments()) {
508 string arg_name = kArgumentPrefix + arg->GetName();
509
510 auto& arg_type = arg->GetType();
511 if (!arg->IsIn() && arg_type.IsArray() && arg_type.GetName() == "ParcelFileDescriptor") {
512 // We represent arrays of ParcelFileDescriptor as
513 // Vec<Option<ParcelFileDescriptor>> when they're out-arguments,
514 // but we need all of them to be initialized to Some; if there's
515 // any None, return UNEXPECTED_NULL (this is what libbinder_ndk does)
516 out << "if " << arg_name << ".iter().any(Option::is_none) { "
517 << "return Err(binder::StatusCode::UNEXPECTED_NULL); }\n";
518 } else if (!arg->IsIn() && TypeNeedsOption(arg_type, typenames)) {
519 // Unwrap out-only arguments that we wrapped in Option<T>
520 out << "let " << arg_name << " = " << arg_name
521 << ".ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
522 }
523
524 out << "_aidl_reply.write(&" << arg_name << ")?;\n";
525 }
526 out.Dedent();
527 out << "}\n";
528 out << "Err(_aidl_status) => _aidl_reply.write(_aidl_status)?\n";
529 out.Dedent();
530 out << "}\n";
531 }
532 out << "Ok(())\n";
533 if (method.IsUserDefined() && method.IsNew() &&
534 ShouldForceDowngradeFor(CommunicationSide::READ)) {
535 out.Dedent();
536 out << "}\n";
537 }
538 out.Dedent();
539 out << "}\n";
540 }
541
GenerateServerItems(CodeWriter & out,const AidlInterface * iface,const AidlTypenames & typenames)542 void GenerateServerItems(CodeWriter& out, const AidlInterface* iface,
543 const AidlTypenames& typenames) {
544 auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
545 auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
546
547 // Forward all IFoo functions from Binder to the inner object
548 out << "impl " << trait_name << " for binder::binder_impl::Binder<" << server_name << "> {\n";
549 out.Indent();
550 for (const auto& method : iface->GetMethods()) {
551 string args;
552 for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
553 if (!args.empty()) {
554 args += ", ";
555 }
556 args += kArgumentPrefix;
557 args += arg->GetName();
558 }
559 out << BuildMethod(*method, typenames, iface->IsVintfStability()) << " { " << "self.0.r#"
560 << method->GetName() << "(" << args << ") }\n";
561 }
562 out.Dedent();
563 out << "}\n";
564
565 out << "fn on_transact("
566 "_aidl_service: &dyn "
567 << trait_name
568 << ", "
569 "_aidl_code: binder::binder_impl::TransactionCode, "
570 "_aidl_data: &binder::binder_impl::BorrowedParcel<'_>, "
571 "_aidl_reply: &mut binder::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), "
572 "binder::StatusCode> "
573 "{\n";
574 out.Indent();
575 out << "match _aidl_code {\n";
576 out.Indent();
577 for (const auto& method : iface->GetMethods()) {
578 GenerateServerTransaction(out, *iface, *method, typenames);
579 }
580 out << "_ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n";
581 out.Dedent();
582 out << "}\n";
583 out.Dedent();
584 out << "}\n";
585 }
586
GenerateDeprecated(CodeWriter & out,const AidlCommentable & type)587 void GenerateDeprecated(CodeWriter& out, const AidlCommentable& type) {
588 if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
589 if (deprecated->note.empty()) {
590 out << "#[deprecated]\n";
591 } else {
592 out << "#[deprecated = " << QuotedEscape(deprecated->note) << "]\n";
593 }
594 }
595 }
596
597 template <typename TypeWithConstants>
GenerateConstantDeclarations(CodeWriter & out,const TypeWithConstants & type,const AidlTypenames & typenames)598 void GenerateConstantDeclarations(CodeWriter& out, const TypeWithConstants& type,
599 const AidlTypenames& typenames) {
600 for (const auto& constant : type.GetConstantDeclarations()) {
601 const AidlTypeSpecifier& type = constant->GetType();
602 const AidlConstantValue& value = constant->GetValue();
603
604 string const_type;
605 if (type.Signature() == "String") {
606 const_type = "&str";
607 } else if (type.Signature() == "byte" || type.Signature() == "int" ||
608 type.Signature() == "long" || type.Signature() == "float" ||
609 type.Signature() == "double") {
610 const_type = RustNameOf(type, typenames, StorageMode::VALUE,
611 /*is_vintf_stability=*/false);
612 } else {
613 AIDL_FATAL(value) << "Unrecognized constant type: " << type.Signature();
614 }
615
616 GenerateDeprecated(out, *constant);
617 out << "pub const r#" << constant->GetName() << ": " << const_type << " = "
618 << constant->ValueString(ConstantValueDecoratorRef) << ";\n";
619 }
620 }
621
GenerateRustInterface(CodeWriter * code_writer,const AidlInterface * iface,const AidlTypenames & typenames,const Options & options)622 void GenerateRustInterface(CodeWriter* code_writer, const AidlInterface* iface,
623 const AidlTypenames& typenames, const Options& options) {
624 *code_writer << "#![allow(non_upper_case_globals)]\n";
625 *code_writer << "#![allow(non_snake_case)]\n";
626 // Import IBinderInternal for transact()
627 *code_writer << "#[allow(unused_imports)] use binder::binder_impl::IBinderInternal;\n";
628 *code_writer << "#[cfg(any(android_vndk, not(android_ndk)))]\n";
629 *code_writer << "const FLAG_PRIVATE_LOCAL: binder::binder_impl::TransactionFlags = "
630 "binder::binder_impl::FLAG_PRIVATE_LOCAL;\n";
631 *code_writer << "#[cfg(not(any(android_vndk, not(android_ndk))))]\n";
632 *code_writer << "const FLAG_PRIVATE_LOCAL: binder::binder_impl::TransactionFlags = 0;\n";
633
634 auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
635 auto trait_name_async = trait_name + "Async";
636 auto trait_name_async_server = trait_name + "AsyncServer";
637 auto client_name = ClassName(*iface, cpp::ClassNames::CLIENT);
638 auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
639 *code_writer << "use binder::declare_binder_interface;\n";
640 *code_writer << "declare_binder_interface! {\n";
641 code_writer->Indent();
642 *code_writer << trait_name << "[\"" << iface->GetDescriptor() << "\"] {\n";
643 code_writer->Indent();
644 *code_writer << "native: " << server_name << "(on_transact),\n";
645 *code_writer << "proxy: " << client_name << " {\n";
646 code_writer->Indent();
647 if (options.Version() > 0) {
648 string comma = options.Hash().empty() ? "" : ",";
649 *code_writer << "cached_version: "
650 "std::sync::atomic::AtomicI32 = "
651 "std::sync::atomic::AtomicI32::new(-1)"
652 << comma << "\n";
653 }
654 if (!options.Hash().empty()) {
655 *code_writer << "cached_hash: "
656 "std::sync::Mutex<Option<String>> = "
657 "std::sync::Mutex::new(None)\n";
658 }
659 code_writer->Dedent();
660 *code_writer << "},\n";
661 *code_writer << "async: " << trait_name_async << "(try_into_local_async),\n";
662 if (iface->IsVintfStability()) {
663 *code_writer << "stability: binder::binder_impl::Stability::Vintf,\n";
664 }
665 code_writer->Dedent();
666 *code_writer << "}\n";
667 code_writer->Dedent();
668 *code_writer << "}\n";
669
670 // Emit the trait.
671 GenerateDeprecated(*code_writer, *iface);
672 if (options.GenMockall()) {
673 *code_writer << "#[mockall::automock]\n";
674 }
675 *code_writer << "pub trait " << trait_name << ": binder::Interface + Send {\n";
676 code_writer->Indent();
677 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
678 << iface->GetDescriptor() << "\" }\n";
679
680 for (const auto& method : iface->GetMethods()) {
681 // Generate the method
682 GenerateDeprecated(*code_writer, *method);
683 if (method->IsUserDefined()) {
684 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << ";\n";
685 } else {
686 // Generate default implementations for meta methods
687 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << " {\n";
688 code_writer->Indent();
689 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
690 *code_writer << "Ok(VERSION)\n";
691 } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
692 *code_writer << "Ok(HASH.into())\n";
693 }
694 code_writer->Dedent();
695 *code_writer << "}\n";
696 }
697 }
698
699 // Emit the default implementation code inside the trait
700 auto default_trait_name = ClassName(*iface, cpp::ClassNames::DEFAULT_IMPL);
701 auto default_ref_name = default_trait_name + "Ref";
702 *code_writer << "fn getDefaultImpl()"
703 << " -> " << default_ref_name << " where Self: Sized {\n";
704 *code_writer << " DEFAULT_IMPL.lock().unwrap().clone()\n";
705 *code_writer << "}\n";
706 *code_writer << "fn setDefaultImpl(d: " << default_ref_name << ")"
707 << " -> " << default_ref_name << " where Self: Sized {\n";
708 *code_writer << " std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)\n";
709 *code_writer << "}\n";
710 *code_writer << "fn try_as_async_server<'a>(&'a self) -> Option<&'a (dyn "
711 << trait_name_async_server << " + Send + Sync)> {\n";
712 *code_writer << " None\n";
713 *code_writer << "}\n";
714 code_writer->Dedent();
715 *code_writer << "}\n";
716
717 // Emit the Interface implementation for the mock, if needed.
718 if (options.GenMockall()) {
719 *code_writer << "impl binder::Interface for Mock" << trait_name << " {}\n";
720 }
721
722 // Emit the async trait.
723 GenerateDeprecated(*code_writer, *iface);
724 *code_writer << "pub trait " << trait_name_async << "<P>: binder::Interface + Send {\n";
725 code_writer->Indent();
726 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
727 << iface->GetDescriptor() << "\" }\n";
728
729 for (const auto& method : iface->GetMethods()) {
730 // Generate the method
731 GenerateDeprecated(*code_writer, *method);
732
733 if (method->IsUserDefined()) {
734 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(),
735 MethodKind::BOXED_FUTURE)
736 << ";\n";
737 } else {
738 // Generate default implementations for meta methods
739 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(),
740 MethodKind::BOXED_FUTURE)
741 << " {\n";
742 code_writer->Indent();
743 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
744 *code_writer << "Box::pin(async move { Ok(VERSION) })\n";
745 } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
746 *code_writer << "Box::pin(async move { Ok(HASH.into()) })\n";
747 }
748 code_writer->Dedent();
749 *code_writer << "}\n";
750 }
751 }
752 code_writer->Dedent();
753 *code_writer << "}\n";
754
755 // Emit the async server trait.
756 GenerateDeprecated(*code_writer, *iface);
757 *code_writer << "#[::async_trait::async_trait]\n";
758 *code_writer << "pub trait " << trait_name_async_server << ": binder::Interface + Send {\n";
759 code_writer->Indent();
760 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
761 << iface->GetDescriptor() << "\" }\n";
762
763 for (const auto& method : iface->GetMethods()) {
764 // Generate the method
765 if (method->IsUserDefined()) {
766 GenerateDeprecated(*code_writer, *method);
767 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(), MethodKind::ASYNC)
768 << ";\n";
769 }
770 }
771 code_writer->Dedent();
772 *code_writer << "}\n";
773
774 // Emit a new_async_binder method for binding an async server.
775 *code_writer << "impl " << server_name << " {\n";
776 code_writer->Indent();
777 *code_writer << "/// Create a new async binder service.\n";
778 *code_writer << "pub fn new_async_binder<T, R>(inner: T, rt: R, features: "
779 "binder::BinderFeatures) -> binder::Strong<dyn "
780 << trait_name << ">\n";
781 *code_writer << "where\n";
782 code_writer->Indent();
783 *code_writer << "T: " << trait_name_async_server
784 << " + binder::Interface + Send + Sync + 'static,\n";
785 *code_writer << "R: binder::binder_impl::BinderAsyncRuntime + Send + Sync + 'static,\n";
786 code_writer->Dedent();
787 *code_writer << "{\n";
788 code_writer->Indent();
789 // Define a wrapper struct that implements the non-async trait by calling block_on.
790 *code_writer << "struct Wrapper<T, R> {\n";
791 code_writer->Indent();
792 *code_writer << "_inner: T,\n";
793 *code_writer << "_rt: R,\n";
794 code_writer->Dedent();
795 *code_writer << "}\n";
796 *code_writer << "impl<T, R> binder::Interface for Wrapper<T, R> where T: binder::Interface, R: "
797 "Send + Sync + 'static {\n";
798 code_writer->Indent();
799 *code_writer << "fn as_binder(&self) -> binder::SpIBinder { self._inner.as_binder() }\n";
800 *code_writer
801 << "fn dump(&self, _writer: &mut dyn std::io::Write, _args: "
802 "&[&std::ffi::CStr]) -> "
803 "std::result::Result<(), binder::StatusCode> { self._inner.dump(_writer, _args) }\n";
804 code_writer->Dedent();
805 *code_writer << "}\n";
806 *code_writer << "impl<T, R> " << trait_name << " for Wrapper<T, R>\n";
807 *code_writer << "where\n";
808 code_writer->Indent();
809 *code_writer << "T: " << trait_name_async_server << " + Send + Sync + 'static,\n";
810 *code_writer << "R: binder::binder_impl::BinderAsyncRuntime + Send + Sync + 'static,\n";
811 code_writer->Dedent();
812 *code_writer << "{\n";
813 code_writer->Indent();
814 for (const auto& method : iface->GetMethods()) {
815 // Generate the method
816 if (method->IsUserDefined()) {
817 string args = "";
818 for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
819 if (!args.empty()) {
820 args += ", ";
821 }
822 args += kArgumentPrefix;
823 args += arg->GetName();
824 }
825
826 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << " {\n";
827 code_writer->Indent();
828 *code_writer << "self._rt.block_on(self._inner.r#" << method->GetName() << "(" << args
829 << "))\n";
830 code_writer->Dedent();
831 *code_writer << "}\n";
832 }
833 }
834 *code_writer << "fn try_as_async_server(&self) -> Option<&(dyn " << trait_name_async_server
835 << " + Send + Sync)> {\n";
836 code_writer->Indent();
837 *code_writer << "Some(&self._inner)\n";
838 code_writer->Dedent();
839 *code_writer << "}\n";
840 code_writer->Dedent();
841 *code_writer << "}\n";
842
843 *code_writer << "let wrapped = Wrapper { _inner: inner, _rt: rt };\n";
844 *code_writer << "Self::new_binder(wrapped, features)\n";
845
846 code_writer->Dedent();
847 *code_writer << "}\n";
848
849 // Emit a method for accessing the underlying async implementation of a local server.
850 *code_writer << "pub fn try_into_local_async<P: binder::BinderAsyncPool + 'static>(_native: "
851 "binder::binder_impl::Binder<Self>) -> Option<binder::Strong<dyn "
852 << trait_name_async << "<P>>> {\n";
853 code_writer->Indent();
854
855 *code_writer << "struct Wrapper {\n";
856 code_writer->Indent();
857 *code_writer << "_native: binder::binder_impl::Binder<" << server_name << ">\n";
858 code_writer->Dedent();
859 *code_writer << "}\n";
860 *code_writer << "impl binder::Interface for Wrapper {}\n";
861 *code_writer << "impl<P: binder::BinderAsyncPool> " << trait_name_async << "<P> for Wrapper {\n";
862 code_writer->Indent();
863 for (const auto& method : iface->GetMethods()) {
864 // Generate the method
865 if (method->IsUserDefined()) {
866 string args = "";
867 for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
868 if (!args.empty()) {
869 args += ", ";
870 }
871 args += kArgumentPrefix;
872 args += arg->GetName();
873 }
874
875 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(),
876 MethodKind::BOXED_FUTURE)
877 << " {\n";
878 code_writer->Indent();
879 *code_writer << "Box::pin(self._native.try_as_async_server().unwrap().r#" << method->GetName()
880 << "(" << args << "))\n";
881 code_writer->Dedent();
882 *code_writer << "}\n";
883 }
884 }
885 code_writer->Dedent();
886 *code_writer << "}\n";
887 *code_writer << "if _native.try_as_async_server().is_some() {\n";
888 *code_writer << " Some(binder::Strong::new(Box::new(Wrapper { _native }) as Box<dyn "
889 << trait_name_async << "<P>>))\n";
890 *code_writer << "} else {\n";
891 *code_writer << " None\n";
892 *code_writer << "}\n";
893
894 code_writer->Dedent();
895 *code_writer << "}\n";
896
897 code_writer->Dedent();
898 *code_writer << "}\n";
899
900 // Emit the default trait
901 *code_writer << "pub trait " << default_trait_name << ": Send + Sync {\n";
902 code_writer->Indent();
903 for (const auto& method : iface->GetMethods()) {
904 if (!method->IsUserDefined()) {
905 continue;
906 }
907
908 // Generate the default method
909 *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << " {\n";
910 code_writer->Indent();
911 *code_writer << "Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())\n";
912 code_writer->Dedent();
913 *code_writer << "}\n";
914 }
915 code_writer->Dedent();
916 *code_writer << "}\n";
917
918 // Generate the transaction code constants
919 // The constants get their own sub-module to avoid conflicts
920 *code_writer << "pub mod transactions {\n";
921 code_writer->Indent();
922 for (const auto& method : iface->GetMethods()) {
923 // Generate the transaction code constant
924 *code_writer << "pub const r#" << method->GetName()
925 << ": binder::binder_impl::TransactionCode = "
926 "binder::binder_impl::FIRST_CALL_TRANSACTION + " +
927 std::to_string(method->GetId()) + ";\n";
928 }
929 code_writer->Dedent();
930 *code_writer << "}\n";
931
932 // Emit the default implementation code outside the trait
933 *code_writer << "pub type " << default_ref_name << " = Option<std::sync::Arc<dyn "
934 << default_trait_name << ">>;\n";
935 *code_writer << "static DEFAULT_IMPL: std::sync::Mutex<" << default_ref_name
936 << "> = std::sync::Mutex::new(None);\n";
937
938 // Emit the interface constants
939 GenerateConstantDeclarations(*code_writer, *iface, typenames);
940
941 // Emit VERSION and HASH
942 // These need to be top-level item constants instead of associated consts
943 // because the latter are incompatible with trait objects, see
944 // https://doc.rust-lang.org/reference/items/traits.html#object-safety
945 if (options.Version() > 0) {
946 if (options.IsLatestUnfrozenVersion()) {
947 *code_writer << kDowngradeComment;
948 *code_writer << "pub const VERSION: i32 = if true {"
949 << std::to_string(options.PreviousVersion()) << "} else {"
950 << std::to_string(options.Version()) << "};\n";
951 } else {
952 *code_writer << "pub const VERSION: i32 = " << std::to_string(options.Version()) << ";\n";
953 }
954 }
955 if (!options.Hash().empty() || options.IsLatestUnfrozenVersion()) {
956 if (options.IsLatestUnfrozenVersion()) {
957 *code_writer << "pub const HASH: &str = if true {\"" << options.PreviousHash()
958 << "\"} else {\"" << options.Hash() << "\"};\n";
959 } else {
960 *code_writer << "pub const HASH: &str = \"" << options.Hash() << "\";\n";
961 }
962 }
963
964 // Generate the client-side method helpers
965 //
966 // The methods in this block are not marked pub, so they are not accessible from outside the
967 // AIDL generated code.
968 *code_writer << "impl " << client_name << " {\n";
969 code_writer->Indent();
970 for (const auto& method : iface->GetMethods()) {
971 GenerateClientMethodHelpers(*code_writer, *iface, *method, typenames, options, trait_name,
972 iface->IsVintfStability());
973 }
974 code_writer->Dedent();
975 *code_writer << "}\n";
976
977 // Generate the client-side methods
978 *code_writer << "impl " << trait_name << " for " << client_name << " {\n";
979 code_writer->Indent();
980 for (const auto& method : iface->GetMethods()) {
981 GenerateClientMethod(*code_writer, *iface, *method, typenames, options, MethodKind::NORMAL);
982 }
983 code_writer->Dedent();
984 *code_writer << "}\n";
985
986 // Generate the async client-side methods
987 *code_writer << "impl<P: binder::BinderAsyncPool> " << trait_name_async << "<P> for "
988 << client_name << " {\n";
989 code_writer->Indent();
990 for (const auto& method : iface->GetMethods()) {
991 GenerateClientMethod(*code_writer, *iface, *method, typenames, options,
992 MethodKind::BOXED_FUTURE);
993 }
994 code_writer->Dedent();
995 *code_writer << "}\n";
996
997 // Generate the server-side methods
998 GenerateServerItems(*code_writer, iface, typenames);
999 }
1000
RemoveUsed(std::set<std::string> * params,const AidlTypeSpecifier & type)1001 void RemoveUsed(std::set<std::string>* params, const AidlTypeSpecifier& type) {
1002 if (!type.IsResolved()) {
1003 params->erase(type.GetName());
1004 }
1005 if (type.IsGeneric()) {
1006 for (const auto& param : type.GetTypeParameters()) {
1007 RemoveUsed(params, *param);
1008 }
1009 }
1010 }
1011
FreeParams(const AidlStructuredParcelable * parcel)1012 std::set<std::string> FreeParams(const AidlStructuredParcelable* parcel) {
1013 if (!parcel->IsGeneric()) {
1014 return std::set<std::string>();
1015 }
1016 auto typeParams = parcel->GetTypeParameters();
1017 std::set<std::string> unusedParams(typeParams.begin(), typeParams.end());
1018 for (const auto& variable : parcel->GetFields()) {
1019 RemoveUsed(&unusedParams, variable->GetType());
1020 }
1021 return unusedParams;
1022 }
1023
WriteParams(CodeWriter & out,const AidlParameterizable<std::string> * parcel,std::string extra)1024 void WriteParams(CodeWriter& out, const AidlParameterizable<std::string>* parcel,
1025 std::string extra) {
1026 if (parcel->IsGeneric()) {
1027 out << "<";
1028 for (const auto& param : parcel->GetTypeParameters()) {
1029 out << param << extra << ",";
1030 }
1031 out << ">";
1032 }
1033 }
1034
WriteParams(CodeWriter & out,const AidlParameterizable<std::string> * parcel)1035 void WriteParams(CodeWriter& out, const AidlParameterizable<std::string>* parcel) {
1036 WriteParams(out, parcel, "");
1037 }
1038
GeneratePaddingField(CodeWriter & out,const std::string & field_type,size_t struct_size,size_t & padding_index,const std::string & padding_element)1039 static void GeneratePaddingField(CodeWriter& out, const std::string& field_type, size_t struct_size,
1040 size_t& padding_index, const std::string& padding_element) {
1041 // If current field is i64 or f64, generate padding for previous field. AIDL enums
1042 // backed by these types have structs with alignment attributes generated so we only need to
1043 // take primitive types that have variable alignment across archs into account here.
1044 if (field_type == "i64" || field_type == "f64") {
1045 // Align total struct size to 8 bytes since current field should have 8 byte alignment
1046 auto padding_size = cpp::AlignTo(struct_size, 8) - struct_size;
1047 if (padding_size != 0) {
1048 out << "_pad_" << std::to_string(padding_index) << ": [" << padding_element << "; "
1049 << std::to_string(padding_size) << "],\n";
1050 padding_index += 1;
1051 }
1052 }
1053 }
1054
GenerateParcelBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1055 void GenerateParcelBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
1056 const AidlTypenames& typenames) {
1057 GenerateDeprecated(out, *parcel);
1058 auto parcelable_alignment = cpp::AlignmentOfDefinedType(*parcel, typenames);
1059 if (parcelable_alignment || parcel->IsFixedSize()) {
1060 AIDL_FATAL_IF(!parcel->IsFixedSize(), parcel);
1061 AIDL_FATAL_IF(parcelable_alignment == std::nullopt, parcel);
1062 // i64/f64 are aligned to 4 bytes on x86 which may underalign the whole struct if it's the
1063 // largest field so we need to set the alignment manually as if these types were aligned to 8
1064 // bytes.
1065 out << "#[repr(C, align(" << std::to_string(*parcelable_alignment) << "))]\n";
1066 }
1067 out << "pub struct r#" << parcel->GetName();
1068 WriteParams(out, parcel);
1069 out << " {\n";
1070 out.Indent();
1071 const auto& fields = parcel->GetFields();
1072 // empty structs in C++ are 1 byte so generate an unused field in this case to make the layouts
1073 // match
1074 if (fields.size() == 0 && parcel->IsFixedSize()) {
1075 out << "_unused: u8,\n";
1076 } else {
1077 size_t padding_index = 0;
1078 size_t struct_size = 0;
1079 for (const auto& variable : fields) {
1080 GenerateDeprecated(out, *variable);
1081 const auto& var_type = variable->GetType();
1082 auto field_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1083 parcel->IsVintfStability());
1084 if (parcel->IsFixedSize()) {
1085 GeneratePaddingField(out, field_type, struct_size, padding_index, "u8");
1086
1087 auto alignment = cpp::AlignmentOf(var_type, typenames);
1088 AIDL_FATAL_IF(alignment == std::nullopt, var_type);
1089 struct_size = cpp::AlignTo(struct_size, *alignment);
1090 auto var_size = cpp::SizeOf(var_type, typenames);
1091 AIDL_FATAL_IF(var_size == std::nullopt, var_type);
1092 struct_size += *var_size;
1093 }
1094 out << "pub r#" << variable->GetName() << ": " << field_type << ",\n";
1095 }
1096 for (const auto& unused_param : FreeParams(parcel)) {
1097 out << "_phantom_" << unused_param << ": std::marker::PhantomData<" << unused_param << ">,\n";
1098 }
1099 }
1100 out.Dedent();
1101 out << "}\n";
1102 if (parcel->IsFixedSize()) {
1103 size_t variable_offset = 0;
1104 for (const auto& variable : fields) {
1105 const auto& var_type = variable->GetType();
1106 // Assert the offset of each field within the struct
1107 auto alignment = cpp::AlignmentOf(var_type, typenames);
1108 AIDL_FATAL_IF(alignment == std::nullopt, var_type);
1109 variable_offset = cpp::AlignTo(variable_offset, *alignment);
1110 out << "static_assertions::const_assert_eq!(std::mem::offset_of!(" << parcel->GetName()
1111 << ", r#" << variable->GetName() << "), " << std::to_string(variable_offset) << ");\n";
1112
1113 // Assert the size of each field
1114 auto variable_size = cpp::SizeOf(var_type, typenames);
1115 AIDL_FATAL_IF(variable_size == std::nullopt, var_type);
1116 std::string rust_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1117 parcel->IsVintfStability());
1118 out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << rust_type << ">(), "
1119 << std::to_string(*variable_size) << ");\n";
1120
1121 variable_offset += *variable_size;
1122 }
1123 // Assert the alignment of the struct
1124 auto parcelable_alignment = cpp::AlignmentOfDefinedType(*parcel, typenames);
1125 AIDL_FATAL_IF(parcelable_alignment == std::nullopt, *parcel);
1126 out << "static_assertions::const_assert_eq!(std::mem::align_of::<" << parcel->GetName()
1127 << ">(), " << std::to_string(*parcelable_alignment) << ");\n";
1128
1129 // Assert the size of the struct
1130 auto parcelable_size = cpp::SizeOfDefinedType(*parcel, typenames);
1131 AIDL_FATAL_IF(parcelable_size == std::nullopt, *parcel);
1132 out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << parcel->GetName()
1133 << ">(), " << std::to_string(*parcelable_size) << ");\n";
1134 }
1135 }
1136
GenerateParcelDefault(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1137 void GenerateParcelDefault(CodeWriter& out, const AidlStructuredParcelable* parcel,
1138 const AidlTypenames& typenames) {
1139 out << "impl";
1140 WriteParams(out, parcel, ": Default");
1141 out << " Default for r#" << parcel->GetName();
1142 WriteParams(out, parcel);
1143 out << " {\n";
1144 out.Indent();
1145 out << "fn default() -> Self {\n";
1146 out.Indent();
1147 out << "Self {\n";
1148 out.Indent();
1149 size_t padding_index = 0;
1150 size_t struct_size = 0;
1151 const auto& fields = parcel->GetFields();
1152 if (fields.size() == 0 && parcel->IsFixedSize()) {
1153 out << "_unused: 0,\n";
1154 } else {
1155 for (const auto& variable : fields) {
1156 const auto& var_type = variable->GetType();
1157 // Generate initializer for padding for previous field if current field is i64 or f64
1158 if (parcel->IsFixedSize()) {
1159 auto field_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1160 parcel->IsVintfStability());
1161 GeneratePaddingField(out, field_type, struct_size, padding_index, "0");
1162
1163 auto alignment = cpp::AlignmentOf(var_type, typenames);
1164 AIDL_FATAL_IF(alignment == std::nullopt, var_type);
1165 struct_size = cpp::AlignTo(struct_size, *alignment);
1166
1167 auto var_size = cpp::SizeOf(var_type, typenames);
1168 AIDL_FATAL_IF(var_size == std::nullopt, var_type);
1169 struct_size += *var_size;
1170 }
1171
1172 out << "r#" << variable->GetName() << ": ";
1173 if (variable->GetDefaultValue()) {
1174 out << variable->ValueString(ConstantValueDecorator);
1175 } else {
1176 // Some types don't implement "Default".
1177 // - Arrays
1178 if (variable->GetType().IsFixedSizeArray() && !variable->GetType().IsNullable()) {
1179 out << ArrayDefaultValue(variable->GetType());
1180 } else {
1181 out << "Default::default()";
1182 }
1183 }
1184 out << ",\n";
1185 }
1186 for (const auto& unused_param : FreeParams(parcel)) {
1187 out << "r#_phantom_" << unused_param << ": Default::default(),\n";
1188 }
1189 }
1190 out.Dedent();
1191 out << "}\n";
1192 out.Dedent();
1193 out << "}\n";
1194 out.Dedent();
1195 out << "}\n";
1196 }
1197
GenerateParcelSerializeBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1198 void GenerateParcelSerializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
1199 const AidlTypenames& typenames) {
1200 out << "parcel.sized_write(|subparcel| {\n";
1201 out.Indent();
1202 for (const auto& variable : parcel->GetFields()) {
1203 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1204 out << "if (false) {\n";
1205 out.Indent();
1206 }
1207 if (TypeNeedsOption(variable->GetType(), typenames)) {
1208 out << "let __field_ref = self.r#" << variable->GetName()
1209 << ".as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
1210 out << "subparcel.write(__field_ref)?;\n";
1211 } else {
1212 out << "subparcel.write(&self.r#" << variable->GetName() << ")?;\n";
1213 }
1214 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1215 out.Dedent();
1216 out << "}\n";
1217 }
1218 }
1219 out << "Ok(())\n";
1220 out.Dedent();
1221 out << "})\n";
1222 }
1223
GenerateParcelDeserializeBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1224 void GenerateParcelDeserializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
1225 const AidlTypenames& typenames) {
1226 out << "parcel.sized_read(|subparcel| {\n";
1227 out.Indent();
1228
1229 for (const auto& variable : parcel->GetFields()) {
1230 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1231 out << "if (false) {\n";
1232 out.Indent();
1233 }
1234 out << "if subparcel.has_more_data() {\n";
1235 out.Indent();
1236 if (TypeNeedsOption(variable->GetType(), typenames)) {
1237 out << "self.r#" << variable->GetName() << " = Some(subparcel.read()?);\n";
1238 } else {
1239 out << "self.r#" << variable->GetName() << " = subparcel.read()?;\n";
1240 }
1241 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1242 out.Dedent();
1243 out << "}\n";
1244 }
1245 out.Dedent();
1246 out << "}\n";
1247 }
1248 out << "Ok(())\n";
1249 out.Dedent();
1250 out << "})\n";
1251 }
1252
GenerateParcelBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1253 void GenerateParcelBody(CodeWriter& out, const AidlUnionDecl* parcel,
1254 const AidlTypenames& typenames) {
1255 GenerateDeprecated(out, *parcel);
1256 auto alignment = cpp::AlignmentOfDefinedType(*parcel, typenames);
1257 if (parcel->IsFixedSize()) {
1258 AIDL_FATAL_IF(alignment == std::nullopt, *parcel);
1259 auto tag = std::to_string(*alignment * 8);
1260 // This repr may use a tag larger than u8 to make sure the tag padding takes into account that
1261 // the overall alignment is computed as if i64/f64 were always 8-byte aligned
1262 out << "#[repr(C, u" << tag << ", align(" << std::to_string(*alignment) << "))]\n";
1263 }
1264 out << "pub enum r#" << parcel->GetName() << " {\n";
1265 out.Indent();
1266 for (const auto& variable : parcel->GetFields()) {
1267 GenerateDeprecated(out, *variable);
1268 auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD,
1269 parcel->IsVintfStability());
1270 out << variable->GetCapitalizedName() << "(" << field_type << "),\n";
1271 }
1272 out.Dedent();
1273 out << "}\n";
1274 if (parcel->IsFixedSize()) {
1275 for (const auto& variable : parcel->GetFields()) {
1276 const auto& var_type = variable->GetType();
1277 std::string rust_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1278 parcel->IsVintfStability());
1279 // Assert the size of each enum variant's payload
1280 auto variable_size = cpp::SizeOf(var_type, typenames);
1281 AIDL_FATAL_IF(variable_size == std::nullopt, var_type);
1282 out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << rust_type << ">(), "
1283 << std::to_string(*variable_size) << ");\n";
1284 }
1285 // Assert the alignment of the enum
1286 AIDL_FATAL_IF(alignment == std::nullopt, *parcel);
1287 out << "static_assertions::const_assert_eq!(std::mem::align_of::<" << parcel->GetName()
1288 << ">(), " << std::to_string(*alignment) << ");\n";
1289
1290 // Assert the size of the enum, taking into the tag and its padding into account
1291 auto union_size = cpp::SizeOfDefinedType(*parcel, typenames);
1292 AIDL_FATAL_IF(union_size == std::nullopt, *parcel);
1293 out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << parcel->GetName()
1294 << ">(), " << std::to_string(*union_size) << ");\n";
1295 }
1296 }
1297
GenerateParcelDefault(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1298 void GenerateParcelDefault(CodeWriter& out, const AidlUnionDecl* parcel,
1299 const AidlTypenames& typenames __attribute__((unused))) {
1300 out << "impl";
1301 WriteParams(out, parcel, ": Default");
1302 out << " Default for r#" << parcel->GetName();
1303 WriteParams(out, parcel);
1304 out << " {\n";
1305 out.Indent();
1306 out << "fn default() -> Self {\n";
1307 out.Indent();
1308
1309 AIDL_FATAL_IF(parcel->GetFields().empty(), *parcel)
1310 << "Union '" << parcel->GetName() << "' is empty.";
1311 const auto& first_field = parcel->GetFields()[0];
1312 const auto& first_value = first_field->ValueString(ConstantValueDecorator);
1313
1314 out << "Self::";
1315 if (first_field->GetDefaultValue()) {
1316 out << first_field->GetCapitalizedName() << "(" << first_value << ")\n";
1317 } else {
1318 out << first_field->GetCapitalizedName() << "(Default::default())\n";
1319 }
1320
1321 out.Dedent();
1322 out << "}\n";
1323 out.Dedent();
1324 out << "}\n";
1325 }
1326
GenerateParcelSerializeBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1327 void GenerateParcelSerializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
1328 const AidlTypenames& typenames) {
1329 out << "match self {\n";
1330 out.Indent();
1331 int tag = 0;
1332 for (const auto& variable : parcel->GetFields()) {
1333 out << "Self::" << variable->GetCapitalizedName() << "(v) => {\n";
1334 out.Indent();
1335 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1336 out << "if (true) {\n";
1337 out << " Err(binder::StatusCode::BAD_VALUE)\n";
1338 out << "} else {\n";
1339 out.Indent();
1340 }
1341 out << "parcel.write(&" << std::to_string(tag++) << "i32)?;\n";
1342 if (TypeNeedsOption(variable->GetType(), typenames)) {
1343 out << "let __field_ref = v.as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
1344 out << "parcel.write(__field_ref)\n";
1345 } else {
1346 out << "parcel.write(v)\n";
1347 }
1348 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1349 out.Dedent();
1350 out << "}\n";
1351 }
1352 out.Dedent();
1353 out << "}\n";
1354 }
1355 out.Dedent();
1356 out << "}\n";
1357 }
1358
GenerateParcelDeserializeBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1359 void GenerateParcelDeserializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
1360 const AidlTypenames& typenames) {
1361 out << "let tag: i32 = parcel.read()?;\n";
1362 out << "match tag {\n";
1363 out.Indent();
1364 int tag = 0;
1365 for (const auto& variable : parcel->GetFields()) {
1366 auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD,
1367 parcel->IsVintfStability());
1368
1369 out << std::to_string(tag++) << " => {\n";
1370 out.Indent();
1371 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1372 out << "if (true) {\n";
1373 out << " Err(binder::StatusCode::BAD_VALUE)\n";
1374 out << "} else {\n";
1375 out.Indent();
1376 }
1377 out << "let value: " << field_type << " = ";
1378 if (TypeNeedsOption(variable->GetType(), typenames)) {
1379 out << "Some(parcel.read()?);\n";
1380 } else {
1381 out << "parcel.read()?;\n";
1382 }
1383 out << "*self = Self::" << variable->GetCapitalizedName() << "(value);\n";
1384 out << "Ok(())\n";
1385 if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1386 out.Dedent();
1387 out << "}\n";
1388 }
1389 out.Dedent();
1390 out << "}\n";
1391 }
1392 out << "_ => {\n";
1393 out << " Err(binder::StatusCode::BAD_VALUE)\n";
1394 out << "}\n";
1395 out.Dedent();
1396 out << "}\n";
1397 }
1398
1399 template <typename ParcelableType>
GenerateParcelableTrait(CodeWriter & out,const ParcelableType * parcel,const AidlTypenames & typenames)1400 void GenerateParcelableTrait(CodeWriter& out, const ParcelableType* parcel,
1401 const AidlTypenames& typenames) {
1402 out << "impl";
1403 WriteParams(out, parcel);
1404 out << " binder::Parcelable for r#" << parcel->GetName();
1405 WriteParams(out, parcel);
1406 out << " {\n";
1407 out.Indent();
1408
1409 out << "fn write_to_parcel(&self, "
1410 "parcel: &mut binder::binder_impl::BorrowedParcel) -> std::result::Result<(), "
1411 "binder::StatusCode> "
1412 "{\n";
1413 out.Indent();
1414 GenerateParcelSerializeBody(out, parcel, typenames);
1415 out.Dedent();
1416 out << "}\n";
1417
1418 out << "fn read_from_parcel(&mut self, "
1419 "parcel: &binder::binder_impl::BorrowedParcel) -> std::result::Result<(), "
1420 "binder::StatusCode> {\n";
1421 out.Indent();
1422 GenerateParcelDeserializeBody(out, parcel, typenames);
1423 out.Dedent();
1424 out << "}\n";
1425
1426 out.Dedent();
1427 out << "}\n";
1428
1429 // Emit the outer (de)serialization traits
1430 out << "binder::impl_serialize_for_parcelable!(r#" << parcel->GetName();
1431 WriteParams(out, parcel);
1432 out << ");\n";
1433 out << "binder::impl_deserialize_for_parcelable!(r#" << parcel->GetName();
1434 WriteParams(out, parcel);
1435 out << ");\n";
1436 }
1437
1438 template <typename ParcelableType>
GenerateMetadataTrait(CodeWriter & out,const ParcelableType * parcel)1439 void GenerateMetadataTrait(CodeWriter& out, const ParcelableType* parcel) {
1440 out << "impl";
1441 WriteParams(out, parcel);
1442 out << " binder::binder_impl::ParcelableMetadata for r#" << parcel->GetName();
1443 WriteParams(out, parcel);
1444 out << " {\n";
1445 out.Indent();
1446
1447 out << "fn get_descriptor() -> &'static str { \"" << parcel->GetCanonicalName() << "\" }\n";
1448
1449 if (parcel->IsVintfStability()) {
1450 out << "fn get_stability(&self) -> binder::binder_impl::Stability { "
1451 "binder::binder_impl::Stability::Vintf }\n";
1452 }
1453
1454 out.Dedent();
1455 out << "}\n";
1456 }
1457
1458 template <typename ParcelableType>
GenerateRustParcel(CodeWriter * code_writer,const ParcelableType * parcel,const AidlTypenames & typenames)1459 void GenerateRustParcel(CodeWriter* code_writer, const ParcelableType* parcel,
1460 const AidlTypenames& typenames) {
1461 vector<string> derives = parcel->RustDerive();
1462
1463 // Debug is always derived because all Rust AIDL types implement it
1464 // ParcelFileDescriptor doesn't support any of the others because
1465 // it's a newtype over std::fs::File which only implements Debug
1466 derives.insert(derives.begin(), "Debug");
1467
1468 *code_writer << "#[derive(" << Join(derives, ", ") << ")]\n";
1469 GenerateParcelBody(*code_writer, parcel, typenames);
1470 GenerateConstantDeclarations(*code_writer, *parcel, typenames);
1471 GenerateParcelDefault(*code_writer, parcel, typenames);
1472 GenerateParcelableTrait(*code_writer, parcel, typenames);
1473 GenerateMetadataTrait(*code_writer, parcel);
1474 }
1475
GenerateRustEnumDeclaration(CodeWriter * code_writer,const AidlEnumDeclaration * enum_decl,const AidlTypenames & typenames)1476 void GenerateRustEnumDeclaration(CodeWriter* code_writer, const AidlEnumDeclaration* enum_decl,
1477 const AidlTypenames& typenames) {
1478 const auto& aidl_backing_type = enum_decl->GetBackingType();
1479 auto backing_type = RustNameOf(aidl_backing_type, typenames, StorageMode::VALUE,
1480 /*is_vintf_stability=*/false);
1481
1482 *code_writer << "#![allow(non_upper_case_globals)]\n";
1483 *code_writer << "use binder::declare_binder_enum;\n";
1484 *code_writer << "declare_binder_enum! {\n";
1485 code_writer->Indent();
1486
1487 GenerateDeprecated(*code_writer, *enum_decl);
1488 auto alignment = cpp::AlignmentOf(aidl_backing_type, typenames);
1489 AIDL_FATAL_IF(alignment == std::nullopt, *enum_decl);
1490 // u64 is aligned to 4 bytes on x86 which may underalign the whole struct if it's the backing type
1491 // so we need to set the alignment manually as if u64 were aligned to 8 bytes.
1492 *code_writer << "#[repr(C, align(" << std::to_string(*alignment) << "))]\n";
1493 *code_writer << "r#" << enum_decl->GetName() << " : [" << backing_type << "; "
1494 << std::to_string(enum_decl->GetEnumerators().size()) << "] {\n";
1495 code_writer->Indent();
1496 for (const auto& enumerator : enum_decl->GetEnumerators()) {
1497 auto value = enumerator->GetValue()->ValueString(aidl_backing_type, ConstantValueDecorator);
1498 GenerateDeprecated(*code_writer, *enumerator);
1499 *code_writer << "r#" << enumerator->GetName() << " = " << value << ",\n";
1500 }
1501 code_writer->Dedent();
1502 *code_writer << "}\n";
1503
1504 code_writer->Dedent();
1505 *code_writer << "}\n";
1506 }
1507
GenerateClass(CodeWriter * code_writer,const AidlDefinedType & defined_type,const AidlTypenames & types,const Options & options)1508 void GenerateClass(CodeWriter* code_writer, const AidlDefinedType& defined_type,
1509 const AidlTypenames& types, const Options& options) {
1510 if (const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
1511 parcelable != nullptr) {
1512 GenerateRustParcel(code_writer, parcelable, types);
1513 } else if (const AidlEnumDeclaration* enum_decl = defined_type.AsEnumDeclaration();
1514 enum_decl != nullptr) {
1515 GenerateRustEnumDeclaration(code_writer, enum_decl, types);
1516 } else if (const AidlInterface* interface = defined_type.AsInterface(); interface != nullptr) {
1517 GenerateRustInterface(code_writer, interface, types, options);
1518 } else if (const AidlUnionDecl* union_decl = defined_type.AsUnionDeclaration();
1519 union_decl != nullptr) {
1520 GenerateRustParcel(code_writer, union_decl, types);
1521 } else {
1522 AIDL_FATAL(defined_type) << "Unrecognized type sent for Rust generation.";
1523 }
1524
1525 for (const auto& nested : defined_type.GetNestedTypes()) {
1526 (*code_writer) << "pub mod r#" << nested->GetName() << " {\n";
1527 code_writer->Indent();
1528 GenerateClass(code_writer, *nested, types, options);
1529 code_writer->Dedent();
1530 (*code_writer) << "}\n";
1531 }
1532 }
1533
GenerateRust(const string & filename,const Options & options,const AidlTypenames & types,const AidlDefinedType & defined_type,const IoDelegate & io_delegate)1534 void GenerateRust(const string& filename, const Options& options, const AidlTypenames& types,
1535 const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
1536 CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
1537
1538 GenerateAutoGenHeader(*code_writer, options);
1539
1540 // Forbid the use of unsafe in auto-generated code.
1541 // Unsafe code should only be allowed in libbinder_rs.
1542 *code_writer << "#![forbid(unsafe_code)]\n";
1543 // Disable rustfmt on auto-generated files, including the golden outputs
1544 *code_writer << "#![cfg_attr(rustfmt, rustfmt_skip)]\n";
1545 GenerateClass(code_writer.get(), defined_type, types, options);
1546 GenerateMangledAliases(*code_writer, defined_type);
1547
1548 AIDL_FATAL_IF(!code_writer->Close(), defined_type) << "I/O Error!";
1549 }
1550
1551 } // namespace rust
1552 } // namespace aidl
1553 } // namespace android
1554