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("binder::binder_impl::FLAG_PRIVATE_LOCAL");
361 
362   string transact_flags = flags.empty() ? "0" : Join(flags, " | ");
363 
364   switch (kind) {
365     case MethodKind::NORMAL:
366     case MethodKind::ASYNC:
367       if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
368           method.IsUserDefined()) {
369         out << "if (true) {\n";
370         out << " return Err(binder::Status::from(binder::StatusCode::UNKNOWN_TRANSACTION));\n";
371         out << "} else {\n";
372         out.Indent();
373       }
374       // Prepare transaction.
375       out << "let _aidl_data = self.build_parcel_" + method.GetName() + "(" + build_parcel_args +
376                  ")?;\n";
377       // Submit transaction.
378       out << "let _aidl_reply = self.binder.submit_transact(transactions::r#" << method.GetName()
379           << ", _aidl_data, " << transact_flags << ");\n";
380       // Deserialize response.
381       out << "self.read_response_" + method.GetName() + "(" + read_response_args + ")\n";
382       break;
383     case MethodKind::READY_FUTURE:
384       if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
385           method.IsUserDefined()) {
386         out << "if (true) {\n";
387         out << " return "
388                "std::future::ready(Err(binder::Status::from(binder::StatusCode::UNKNOWN_"
389                "TRANSACTION)));\n";
390         out << "} else {\n";
391         out.Indent();
392       }
393       // Prepare transaction.
394       out << "let _aidl_data = match self.build_parcel_" + method.GetName() + "(" +
395                  build_parcel_args + ") {\n";
396       out.Indent();
397       out << "Ok(_aidl_data) => _aidl_data,\n";
398       out << "Err(err) => return std::future::ready(Err(err)),\n";
399       out.Dedent();
400       out << "};\n";
401       // Submit transaction.
402       out << "let _aidl_reply = self.binder.submit_transact(transactions::r#" << method.GetName()
403           << ", _aidl_data, " << transact_flags << ");\n";
404       // Deserialize response.
405       out << "std::future::ready(self.read_response_" + method.GetName() + "(" +
406                  read_response_args + "))\n";
407       break;
408     case MethodKind::BOXED_FUTURE:
409       if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
410           method.IsUserDefined()) {
411         out << "if (true) {\n";
412         out << " return "
413                "Box::pin(std::future::ready(Err(binder::Status::from(binder::StatusCode::UNKNOWN_"
414                "TRANSACTION))));\n";
415         out << "} else {\n";
416         out.Indent();
417       }
418       // Prepare transaction.
419       out << "let _aidl_data = match self.build_parcel_" + method.GetName() + "(" +
420                  build_parcel_args + ") {\n";
421       out.Indent();
422       out << "Ok(_aidl_data) => _aidl_data,\n";
423       out << "Err(err) => return Box::pin(std::future::ready(Err(err))),\n";
424       out.Dedent();
425       out << "};\n";
426       // Submit transaction.
427       out << "let binder = self.binder.clone();\n";
428       out << "P::spawn(\n";
429       out.Indent();
430       out << "move || binder.submit_transact(transactions::r#" << method.GetName()
431           << ", _aidl_data, " << transact_flags << "),\n";
432       out << "move |_aidl_reply| async move {\n";
433       out.Indent();
434       // Deserialize response.
435       out << "self.read_response_" + method.GetName() + "(" + read_response_args + ")\n";
436       out.Dedent();
437       out << "}\n";
438       out.Dedent();
439       out << ")\n";
440       break;
441   }
442 
443   if (method.IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE) &&
444       method.IsUserDefined()) {
445     out.Dedent();
446     out << "}\n";
447   }
448   out.Dedent();
449   out << "}\n";
450 }
451 
GenerateServerTransaction(CodeWriter & out,const AidlInterface & interface,const AidlMethod & method,const AidlTypenames & typenames)452 void GenerateServerTransaction(CodeWriter& out, const AidlInterface& interface,
453                                const AidlMethod& method, const AidlTypenames& typenames) {
454   out << "transactions::r#" << method.GetName() << " => {\n";
455   out.Indent();
456   if (method.IsUserDefined() && method.IsNew() &&
457       ShouldForceDowngradeFor(CommunicationSide::READ)) {
458     out << "if (true) {\n";
459     out << "  Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n";
460     out << "} else {\n";
461     out.Indent();
462   }
463 
464   if (interface.EnforceExpression() || method.GetType().EnforceExpression()) {
465     out << "compile_error!(\"Permission checks not support for the Rust backend\");\n";
466   }
467 
468   string args;
469   for (const auto& arg : method.GetArguments()) {
470     string arg_name = kArgumentPrefix + arg->GetName();
471     StorageMode arg_mode;
472     if (arg->IsIn()) {
473       arg_mode = StorageMode::VALUE;
474     } else {
475       // We need a value we can call Default::default() on
476       arg_mode = StorageMode::DEFAULT_VALUE;
477     }
478     auto arg_type = RustNameOf(arg->GetType(), typenames, arg_mode, interface.IsVintfStability());
479 
480     string arg_mut = arg->IsOut() ? "mut " : "";
481     string arg_init = arg->IsIn() ? "_aidl_data.read()?" : "Default::default()";
482     out << "let " << arg_mut << arg_name << ": " << arg_type << " = " << arg_init << ";\n";
483     if (!arg->IsIn() && arg->GetType().IsDynamicArray()) {
484       // _aidl_data.resize_[nullable_]out_vec(&mut _arg_foo)?;
485       auto resize_name = arg->GetType().IsNullable() ? "resize_nullable_out_vec" : "resize_out_vec";
486       out << "_aidl_data." << resize_name << "(&mut " << arg_name << ")?;\n";
487     }
488 
489     auto ref_mode = ArgumentReferenceMode(*arg, typenames);
490     if (!args.empty()) {
491       args += ", ";
492     }
493     args += TakeReference(ref_mode, arg_name);
494   }
495   out << "let _aidl_return = _aidl_service.r#" << method.GetName() << "(" << args << ");\n";
496 
497   if (!method.IsOneway()) {
498     out << "match &_aidl_return {\n";
499     out.Indent();
500     out << "Ok(_aidl_return) => {\n";
501     out.Indent();
502     out << "_aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;\n";
503     if (method.GetType().GetName() != "void") {
504       out << "_aidl_reply.write(_aidl_return)?;\n";
505     }
506 
507     // Serialize out arguments
508     for (const AidlArgument* arg : method.GetOutArguments()) {
509       string arg_name = kArgumentPrefix + arg->GetName();
510 
511       auto& arg_type = arg->GetType();
512       if (!arg->IsIn() && arg_type.IsArray() && arg_type.GetName() == "ParcelFileDescriptor") {
513         // We represent arrays of ParcelFileDescriptor as
514         // Vec<Option<ParcelFileDescriptor>> when they're out-arguments,
515         // but we need all of them to be initialized to Some; if there's
516         // any None, return UNEXPECTED_NULL (this is what libbinder_ndk does)
517         out << "if " << arg_name << ".iter().any(Option::is_none) { "
518             << "return Err(binder::StatusCode::UNEXPECTED_NULL); }\n";
519       } else if (!arg->IsIn() && TypeNeedsOption(arg_type, typenames)) {
520         // Unwrap out-only arguments that we wrapped in Option<T>
521         out << "let " << arg_name << " = " << arg_name
522             << ".ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
523       }
524 
525       out << "_aidl_reply.write(&" << arg_name << ")?;\n";
526     }
527     out.Dedent();
528     out << "}\n";
529     out << "Err(_aidl_status) => _aidl_reply.write(_aidl_status)?\n";
530     out.Dedent();
531     out << "}\n";
532   }
533   out << "Ok(())\n";
534   if (method.IsUserDefined() && method.IsNew() &&
535       ShouldForceDowngradeFor(CommunicationSide::READ)) {
536     out.Dedent();
537     out << "}\n";
538   }
539   out.Dedent();
540   out << "}\n";
541 }
542 
GenerateServerItems(CodeWriter & out,const AidlInterface * iface,const AidlTypenames & typenames)543 void GenerateServerItems(CodeWriter& out, const AidlInterface* iface,
544                          const AidlTypenames& typenames) {
545   auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
546   auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
547 
548   // Forward all IFoo functions from Binder to the inner object
549   out << "impl " << trait_name << " for binder::binder_impl::Binder<" << server_name << "> {\n";
550   out.Indent();
551   for (const auto& method : iface->GetMethods()) {
552     string args;
553     for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
554       if (!args.empty()) {
555         args += ", ";
556       }
557       args += kArgumentPrefix;
558       args += arg->GetName();
559     }
560     out << BuildMethod(*method, typenames, iface->IsVintfStability()) << " { " << "self.0.r#"
561         << method->GetName() << "(" << args << ") }\n";
562   }
563   out.Dedent();
564   out << "}\n";
565 
566   out << "fn on_transact("
567          "_aidl_service: &dyn "
568       << trait_name
569       << ", "
570          "_aidl_code: binder::binder_impl::TransactionCode, "
571          "_aidl_data: &binder::binder_impl::BorrowedParcel<'_>, "
572          "_aidl_reply: &mut binder::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), "
573          "binder::StatusCode> "
574          "{\n";
575   out.Indent();
576   out << "match _aidl_code {\n";
577   out.Indent();
578   for (const auto& method : iface->GetMethods()) {
579     GenerateServerTransaction(out, *iface, *method, typenames);
580   }
581   out << "_ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n";
582   out.Dedent();
583   out << "}\n";
584   out.Dedent();
585   out << "}\n";
586 }
587 
GenerateDeprecated(CodeWriter & out,const AidlCommentable & type)588 void GenerateDeprecated(CodeWriter& out, const AidlCommentable& type) {
589   if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
590     if (deprecated->note.empty()) {
591       out << "#[deprecated]\n";
592     } else {
593       out << "#[deprecated = " << QuotedEscape(deprecated->note) << "]\n";
594     }
595   }
596 }
597 
598 template <typename TypeWithConstants>
GenerateConstantDeclarations(CodeWriter & out,const TypeWithConstants & type,const AidlTypenames & typenames)599 void GenerateConstantDeclarations(CodeWriter& out, const TypeWithConstants& type,
600                                   const AidlTypenames& typenames) {
601   for (const auto& constant : type.GetConstantDeclarations()) {
602     const AidlTypeSpecifier& type = constant->GetType();
603     const AidlConstantValue& value = constant->GetValue();
604 
605     string const_type;
606     if (type.Signature() == "String") {
607       const_type = "&str";
608     } else if (type.Signature() == "byte" || type.Signature() == "int" ||
609                type.Signature() == "long" || type.Signature() == "float" ||
610                type.Signature() == "double") {
611       const_type = RustNameOf(type, typenames, StorageMode::VALUE,
612                               /*is_vintf_stability=*/false);
613     } else {
614       AIDL_FATAL(value) << "Unrecognized constant type: " << type.Signature();
615     }
616 
617     GenerateDeprecated(out, *constant);
618     out << "pub const r#" << constant->GetName() << ": " << const_type << " = "
619         << constant->ValueString(ConstantValueDecoratorRef) << ";\n";
620   }
621 }
622 
GenerateRustInterface(CodeWriter * code_writer,const AidlInterface * iface,const AidlTypenames & typenames,const Options & options)623 void GenerateRustInterface(CodeWriter* code_writer, const AidlInterface* iface,
624                            const AidlTypenames& typenames, const Options& options) {
625   *code_writer << "#![allow(non_upper_case_globals)]\n";
626   *code_writer << "#![allow(non_snake_case)]\n";
627   // Import IBinderInternal for transact()
628   *code_writer << "#[allow(unused_imports)] use binder::binder_impl::IBinderInternal;\n";
629 
630   auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
631   auto trait_name_async = trait_name + "Async";
632   auto trait_name_async_server = trait_name + "AsyncServer";
633   auto client_name = ClassName(*iface, cpp::ClassNames::CLIENT);
634   auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
635   *code_writer << "use binder::declare_binder_interface;\n";
636   *code_writer << "declare_binder_interface! {\n";
637   code_writer->Indent();
638   *code_writer << trait_name << "[\"" << iface->GetDescriptor() << "\"] {\n";
639   code_writer->Indent();
640   *code_writer << "native: " << server_name << "(on_transact),\n";
641   *code_writer << "proxy: " << client_name << " {\n";
642   code_writer->Indent();
643   if (options.Version() > 0) {
644     string comma = options.Hash().empty() ? "" : ",";
645     *code_writer << "cached_version: "
646                     "std::sync::atomic::AtomicI32 = "
647                     "std::sync::atomic::AtomicI32::new(-1)"
648                  << comma << "\n";
649   }
650   if (!options.Hash().empty()) {
651     *code_writer << "cached_hash: "
652                     "std::sync::Mutex<Option<String>> = "
653                     "std::sync::Mutex::new(None)\n";
654   }
655   code_writer->Dedent();
656   *code_writer << "},\n";
657   *code_writer << "async: " << trait_name_async << "(try_into_local_async),\n";
658   if (iface->IsVintfStability()) {
659     *code_writer << "stability: binder::binder_impl::Stability::Vintf,\n";
660   }
661   code_writer->Dedent();
662   *code_writer << "}\n";
663   code_writer->Dedent();
664   *code_writer << "}\n";
665 
666   // Emit the trait.
667   GenerateDeprecated(*code_writer, *iface);
668   if (options.GenMockall()) {
669     *code_writer << "#[mockall::automock]\n";
670   }
671   *code_writer << "pub trait " << trait_name << ": binder::Interface + Send {\n";
672   code_writer->Indent();
673   *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
674                << iface->GetDescriptor() << "\" }\n";
675 
676   for (const auto& method : iface->GetMethods()) {
677     // Generate the method
678     GenerateDeprecated(*code_writer, *method);
679     if (method->IsUserDefined()) {
680       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << ";\n";
681     } else {
682       // Generate default implementations for meta methods
683       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << " {\n";
684       code_writer->Indent();
685       if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
686         *code_writer << "Ok(VERSION)\n";
687       } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
688         *code_writer << "Ok(HASH.into())\n";
689       }
690       code_writer->Dedent();
691       *code_writer << "}\n";
692     }
693   }
694 
695   // Emit the default implementation code inside the trait
696   auto default_trait_name = ClassName(*iface, cpp::ClassNames::DEFAULT_IMPL);
697   auto default_ref_name = default_trait_name + "Ref";
698   *code_writer << "fn getDefaultImpl()"
699                << " -> " << default_ref_name << " where Self: Sized {\n";
700   *code_writer << "  DEFAULT_IMPL.lock().unwrap().clone()\n";
701   *code_writer << "}\n";
702   *code_writer << "fn setDefaultImpl(d: " << default_ref_name << ")"
703                << " -> " << default_ref_name << " where Self: Sized {\n";
704   *code_writer << "  std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)\n";
705   *code_writer << "}\n";
706   *code_writer << "fn try_as_async_server<'a>(&'a self) -> Option<&'a (dyn "
707                << trait_name_async_server << " + Send + Sync)> {\n";
708   *code_writer << "  None\n";
709   *code_writer << "}\n";
710   code_writer->Dedent();
711   *code_writer << "}\n";
712 
713   // Emit the Interface implementation for the mock, if needed.
714   if (options.GenMockall()) {
715     *code_writer << "impl binder::Interface for Mock" << trait_name << " {}\n";
716   }
717 
718   // Emit the async trait.
719   GenerateDeprecated(*code_writer, *iface);
720   *code_writer << "pub trait " << trait_name_async << "<P>: binder::Interface + Send {\n";
721   code_writer->Indent();
722   *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
723                << iface->GetDescriptor() << "\" }\n";
724 
725   for (const auto& method : iface->GetMethods()) {
726     // Generate the method
727     GenerateDeprecated(*code_writer, *method);
728 
729     if (method->IsUserDefined()) {
730       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(),
731                                   MethodKind::BOXED_FUTURE)
732                    << ";\n";
733     } else {
734       // Generate default implementations for meta methods
735       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(),
736                                   MethodKind::BOXED_FUTURE)
737                    << " {\n";
738       code_writer->Indent();
739       if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
740         *code_writer << "Box::pin(async move { Ok(VERSION) })\n";
741       } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
742         *code_writer << "Box::pin(async move { Ok(HASH.into()) })\n";
743       }
744       code_writer->Dedent();
745       *code_writer << "}\n";
746     }
747   }
748   code_writer->Dedent();
749   *code_writer << "}\n";
750 
751   // Emit the async server trait.
752   GenerateDeprecated(*code_writer, *iface);
753   *code_writer << "#[::async_trait::async_trait]\n";
754   *code_writer << "pub trait " << trait_name_async_server << ": binder::Interface + Send {\n";
755   code_writer->Indent();
756   *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
757                << iface->GetDescriptor() << "\" }\n";
758 
759   for (const auto& method : iface->GetMethods()) {
760     // Generate the method
761     if (method->IsUserDefined()) {
762       GenerateDeprecated(*code_writer, *method);
763       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(), MethodKind::ASYNC)
764                    << ";\n";
765     }
766   }
767   code_writer->Dedent();
768   *code_writer << "}\n";
769 
770   // Emit a new_async_binder method for binding an async server.
771   *code_writer << "impl " << server_name << " {\n";
772   code_writer->Indent();
773   *code_writer << "/// Create a new async binder service.\n";
774   *code_writer << "pub fn new_async_binder<T, R>(inner: T, rt: R, features: "
775                   "binder::BinderFeatures) -> binder::Strong<dyn "
776                << trait_name << ">\n";
777   *code_writer << "where\n";
778   code_writer->Indent();
779   *code_writer << "T: " << trait_name_async_server
780                << " + binder::Interface + Send + Sync + 'static,\n";
781   *code_writer << "R: binder::binder_impl::BinderAsyncRuntime + Send + Sync + 'static,\n";
782   code_writer->Dedent();
783   *code_writer << "{\n";
784   code_writer->Indent();
785   // Define a wrapper struct that implements the non-async trait by calling block_on.
786   *code_writer << "struct Wrapper<T, R> {\n";
787   code_writer->Indent();
788   *code_writer << "_inner: T,\n";
789   *code_writer << "_rt: R,\n";
790   code_writer->Dedent();
791   *code_writer << "}\n";
792   *code_writer << "impl<T, R> binder::Interface for Wrapper<T, R> where T: binder::Interface, R: "
793                   "Send + Sync + 'static {\n";
794   code_writer->Indent();
795   *code_writer << "fn as_binder(&self) -> binder::SpIBinder { self._inner.as_binder() }\n";
796   *code_writer
797       << "fn dump(&self, _writer: &mut dyn std::io::Write, _args: "
798          "&[&std::ffi::CStr]) -> "
799          "std::result::Result<(), binder::StatusCode> { self._inner.dump(_writer, _args) }\n";
800   code_writer->Dedent();
801   *code_writer << "}\n";
802   *code_writer << "impl<T, R> " << trait_name << " for Wrapper<T, R>\n";
803   *code_writer << "where\n";
804   code_writer->Indent();
805   *code_writer << "T: " << trait_name_async_server << " + Send + Sync + 'static,\n";
806   *code_writer << "R: binder::binder_impl::BinderAsyncRuntime + Send + Sync + 'static,\n";
807   code_writer->Dedent();
808   *code_writer << "{\n";
809   code_writer->Indent();
810   for (const auto& method : iface->GetMethods()) {
811     // Generate the method
812     if (method->IsUserDefined()) {
813       string args = "";
814       for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
815         if (!args.empty()) {
816           args += ", ";
817         }
818         args += kArgumentPrefix;
819         args += arg->GetName();
820       }
821 
822       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << " {\n";
823       code_writer->Indent();
824       *code_writer << "self._rt.block_on(self._inner.r#" << method->GetName() << "(" << args
825                    << "))\n";
826       code_writer->Dedent();
827       *code_writer << "}\n";
828     }
829   }
830   *code_writer << "fn try_as_async_server(&self) -> Option<&(dyn " << trait_name_async_server
831                << " + Send + Sync)> {\n";
832   code_writer->Indent();
833   *code_writer << "Some(&self._inner)\n";
834   code_writer->Dedent();
835   *code_writer << "}\n";
836   code_writer->Dedent();
837   *code_writer << "}\n";
838 
839   *code_writer << "let wrapped = Wrapper { _inner: inner, _rt: rt };\n";
840   *code_writer << "Self::new_binder(wrapped, features)\n";
841 
842   code_writer->Dedent();
843   *code_writer << "}\n";
844 
845   // Emit a method for accessing the underlying async implementation of a local server.
846   *code_writer << "pub fn try_into_local_async<P: binder::BinderAsyncPool + 'static>(_native: "
847                   "binder::binder_impl::Binder<Self>) -> Option<binder::Strong<dyn "
848                << trait_name_async << "<P>>> {\n";
849   code_writer->Indent();
850 
851   *code_writer << "struct Wrapper {\n";
852   code_writer->Indent();
853   *code_writer << "_native: binder::binder_impl::Binder<" << server_name << ">\n";
854   code_writer->Dedent();
855   *code_writer << "}\n";
856   *code_writer << "impl binder::Interface for Wrapper {}\n";
857   *code_writer << "impl<P: binder::BinderAsyncPool> " << trait_name_async << "<P> for Wrapper {\n";
858   code_writer->Indent();
859   for (const auto& method : iface->GetMethods()) {
860     // Generate the method
861     if (method->IsUserDefined()) {
862       string args = "";
863       for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
864         if (!args.empty()) {
865           args += ", ";
866         }
867         args += kArgumentPrefix;
868         args += arg->GetName();
869       }
870 
871       *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability(),
872                                   MethodKind::BOXED_FUTURE)
873                    << " {\n";
874       code_writer->Indent();
875       *code_writer << "Box::pin(self._native.try_as_async_server().unwrap().r#" << method->GetName()
876                    << "(" << args << "))\n";
877       code_writer->Dedent();
878       *code_writer << "}\n";
879     }
880   }
881   code_writer->Dedent();
882   *code_writer << "}\n";
883   *code_writer << "if _native.try_as_async_server().is_some() {\n";
884   *code_writer << "  Some(binder::Strong::new(Box::new(Wrapper { _native }) as Box<dyn "
885                << trait_name_async << "<P>>))\n";
886   *code_writer << "} else {\n";
887   *code_writer << "  None\n";
888   *code_writer << "}\n";
889 
890   code_writer->Dedent();
891   *code_writer << "}\n";
892 
893   code_writer->Dedent();
894   *code_writer << "}\n";
895 
896   // Emit the default trait
897   *code_writer << "pub trait " << default_trait_name << ": Send + Sync {\n";
898   code_writer->Indent();
899   for (const auto& method : iface->GetMethods()) {
900     if (!method->IsUserDefined()) {
901       continue;
902     }
903 
904     // Generate the default method
905     *code_writer << BuildMethod(*method, typenames, iface->IsVintfStability()) << " {\n";
906     code_writer->Indent();
907     *code_writer << "Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())\n";
908     code_writer->Dedent();
909     *code_writer << "}\n";
910   }
911   code_writer->Dedent();
912   *code_writer << "}\n";
913 
914   // Generate the transaction code constants
915   // The constants get their own sub-module to avoid conflicts
916   *code_writer << "pub mod transactions {\n";
917   code_writer->Indent();
918   for (const auto& method : iface->GetMethods()) {
919     // Generate the transaction code constant
920     *code_writer << "pub const r#" << method->GetName()
921                  << ": binder::binder_impl::TransactionCode = "
922                     "binder::binder_impl::FIRST_CALL_TRANSACTION + " +
923                         std::to_string(method->GetId()) + ";\n";
924   }
925   code_writer->Dedent();
926   *code_writer << "}\n";
927 
928   // Emit the default implementation code outside the trait
929   *code_writer << "pub type " << default_ref_name << " = Option<std::sync::Arc<dyn "
930                << default_trait_name << ">>;\n";
931   *code_writer << "static DEFAULT_IMPL: std::sync::Mutex<" << default_ref_name
932                << "> = std::sync::Mutex::new(None);\n";
933 
934   // Emit the interface constants
935   GenerateConstantDeclarations(*code_writer, *iface, typenames);
936 
937   // Emit VERSION and HASH
938   // These need to be top-level item constants instead of associated consts
939   // because the latter are incompatible with trait objects, see
940   // https://doc.rust-lang.org/reference/items/traits.html#object-safety
941   if (options.Version() > 0) {
942     if (options.IsLatestUnfrozenVersion()) {
943       *code_writer << "pub const VERSION: i32 = if true {"
944                    << std::to_string(options.PreviousVersion()) << "} else {"
945                    << std::to_string(options.Version()) << "};\n";
946     } else {
947       *code_writer << "pub const VERSION: i32 = " << std::to_string(options.Version()) << ";\n";
948     }
949   }
950   if (!options.Hash().empty() || options.IsLatestUnfrozenVersion()) {
951     if (options.IsLatestUnfrozenVersion()) {
952       *code_writer << "pub const HASH: &str = if true {\"" << options.PreviousHash()
953                    << "\"} else {\"" << options.Hash() << "\"};\n";
954     } else {
955       *code_writer << "pub const HASH: &str = \"" << options.Hash() << "\";\n";
956     }
957   }
958 
959   // Generate the client-side method helpers
960   //
961   // The methods in this block are not marked pub, so they are not accessible from outside the
962   // AIDL generated code.
963   *code_writer << "impl " << client_name << " {\n";
964   code_writer->Indent();
965   for (const auto& method : iface->GetMethods()) {
966     GenerateClientMethodHelpers(*code_writer, *iface, *method, typenames, options, trait_name,
967                                 iface->IsVintfStability());
968   }
969   code_writer->Dedent();
970   *code_writer << "}\n";
971 
972   // Generate the client-side methods
973   *code_writer << "impl " << trait_name << " for " << client_name << " {\n";
974   code_writer->Indent();
975   for (const auto& method : iface->GetMethods()) {
976     GenerateClientMethod(*code_writer, *iface, *method, typenames, options, MethodKind::NORMAL);
977   }
978   code_writer->Dedent();
979   *code_writer << "}\n";
980 
981   // Generate the async client-side methods
982   *code_writer << "impl<P: binder::BinderAsyncPool> " << trait_name_async << "<P> for "
983                << client_name << " {\n";
984   code_writer->Indent();
985   for (const auto& method : iface->GetMethods()) {
986     GenerateClientMethod(*code_writer, *iface, *method, typenames, options,
987                          MethodKind::BOXED_FUTURE);
988   }
989   code_writer->Dedent();
990   *code_writer << "}\n";
991 
992   // Generate the server-side methods
993   GenerateServerItems(*code_writer, iface, typenames);
994 }
995 
RemoveUsed(std::set<std::string> * params,const AidlTypeSpecifier & type)996 void RemoveUsed(std::set<std::string>* params, const AidlTypeSpecifier& type) {
997   if (!type.IsResolved()) {
998     params->erase(type.GetName());
999   }
1000   if (type.IsGeneric()) {
1001     for (const auto& param : type.GetTypeParameters()) {
1002       RemoveUsed(params, *param);
1003     }
1004   }
1005 }
1006 
FreeParams(const AidlStructuredParcelable * parcel)1007 std::set<std::string> FreeParams(const AidlStructuredParcelable* parcel) {
1008   if (!parcel->IsGeneric()) {
1009     return std::set<std::string>();
1010   }
1011   auto typeParams = parcel->GetTypeParameters();
1012   std::set<std::string> unusedParams(typeParams.begin(), typeParams.end());
1013   for (const auto& variable : parcel->GetFields()) {
1014     RemoveUsed(&unusedParams, variable->GetType());
1015   }
1016   return unusedParams;
1017 }
1018 
WriteParams(CodeWriter & out,const AidlParameterizable<std::string> * parcel,std::string extra)1019 void WriteParams(CodeWriter& out, const AidlParameterizable<std::string>* parcel,
1020                  std::string extra) {
1021   if (parcel->IsGeneric()) {
1022     out << "<";
1023     for (const auto& param : parcel->GetTypeParameters()) {
1024       out << param << extra << ",";
1025     }
1026     out << ">";
1027   }
1028 }
1029 
WriteParams(CodeWriter & out,const AidlParameterizable<std::string> * parcel)1030 void WriteParams(CodeWriter& out, const AidlParameterizable<std::string>* parcel) {
1031   WriteParams(out, parcel, "");
1032 }
1033 
GeneratePaddingField(CodeWriter & out,const std::string & field_type,size_t struct_size,size_t & padding_index,const std::string & padding_element)1034 static void GeneratePaddingField(CodeWriter& out, const std::string& field_type, size_t struct_size,
1035                                  size_t& padding_index, const std::string& padding_element) {
1036   // If current field is i64 or f64, generate padding for previous field. AIDL enums
1037   // backed by these types have structs with alignment attributes generated so we only need to
1038   // take primitive types that have variable alignment across archs into account here.
1039   if (field_type == "i64" || field_type == "f64") {
1040     // Align total struct size to 8 bytes since current field should have 8 byte alignment
1041     auto padding_size = cpp::AlignTo(struct_size, 8) - struct_size;
1042     if (padding_size != 0) {
1043       out << "_pad_" << std::to_string(padding_index) << ": [" << padding_element << "; "
1044           << std::to_string(padding_size) << "],\n";
1045       padding_index += 1;
1046     }
1047   }
1048 }
1049 
GenerateParcelBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1050 void GenerateParcelBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
1051                         const AidlTypenames& typenames) {
1052   GenerateDeprecated(out, *parcel);
1053   auto parcelable_alignment = cpp::AlignmentOfDefinedType(*parcel, typenames);
1054   if (parcelable_alignment || parcel->IsFixedSize()) {
1055     AIDL_FATAL_IF(!parcel->IsFixedSize(), parcel);
1056     AIDL_FATAL_IF(parcelable_alignment == std::nullopt, parcel);
1057     // i64/f64 are aligned to 4 bytes on x86 which may underalign the whole struct if it's the
1058     // largest field so we need to set the alignment manually as if these types were aligned to 8
1059     // bytes.
1060     out << "#[repr(C, align(" << std::to_string(*parcelable_alignment) << "))]\n";
1061   }
1062   out << "pub struct r#" << parcel->GetName();
1063   WriteParams(out, parcel);
1064   out << " {\n";
1065   out.Indent();
1066   const auto& fields = parcel->GetFields();
1067   // empty structs in C++ are 1 byte so generate an unused field in this case to make the layouts
1068   // match
1069   if (fields.size() == 0 && parcel->IsFixedSize()) {
1070     out << "_unused: u8,\n";
1071   } else {
1072     size_t padding_index = 0;
1073     size_t struct_size = 0;
1074     for (const auto& variable : fields) {
1075       GenerateDeprecated(out, *variable);
1076       const auto& var_type = variable->GetType();
1077       auto field_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1078                                    parcel->IsVintfStability());
1079       if (parcel->IsFixedSize()) {
1080         GeneratePaddingField(out, field_type, struct_size, padding_index, "u8");
1081 
1082         auto alignment = cpp::AlignmentOf(var_type, typenames);
1083         AIDL_FATAL_IF(alignment == std::nullopt, var_type);
1084         struct_size = cpp::AlignTo(struct_size, *alignment);
1085         auto var_size = cpp::SizeOf(var_type, typenames);
1086         AIDL_FATAL_IF(var_size == std::nullopt, var_type);
1087         struct_size += *var_size;
1088       }
1089       out << "pub r#" << variable->GetName() << ": " << field_type << ",\n";
1090     }
1091     for (const auto& unused_param : FreeParams(parcel)) {
1092       out << "_phantom_" << unused_param << ": std::marker::PhantomData<" << unused_param << ">,\n";
1093     }
1094   }
1095   out.Dedent();
1096   out << "}\n";
1097   if (parcel->IsFixedSize()) {
1098     size_t variable_offset = 0;
1099     for (const auto& variable : fields) {
1100       const auto& var_type = variable->GetType();
1101       // Assert the offset of each field within the struct
1102       auto alignment = cpp::AlignmentOf(var_type, typenames);
1103       AIDL_FATAL_IF(alignment == std::nullopt, var_type);
1104       variable_offset = cpp::AlignTo(variable_offset, *alignment);
1105       out << "static_assertions::const_assert_eq!(std::mem::offset_of!(" << parcel->GetName()
1106           << ", r#" << variable->GetName() << "), " << std::to_string(variable_offset) << ");\n";
1107 
1108       // Assert the size of each field
1109       auto variable_size = cpp::SizeOf(var_type, typenames);
1110       AIDL_FATAL_IF(variable_size == std::nullopt, var_type);
1111       std::string rust_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1112                                          parcel->IsVintfStability());
1113       out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << rust_type << ">(), "
1114           << std::to_string(*variable_size) << ");\n";
1115 
1116       variable_offset += *variable_size;
1117     }
1118     // Assert the alignment of the struct
1119     auto parcelable_alignment = cpp::AlignmentOfDefinedType(*parcel, typenames);
1120     AIDL_FATAL_IF(parcelable_alignment == std::nullopt, *parcel);
1121     out << "static_assertions::const_assert_eq!(std::mem::align_of::<" << parcel->GetName()
1122         << ">(), " << std::to_string(*parcelable_alignment) << ");\n";
1123 
1124     // Assert the size of the struct
1125     auto parcelable_size = cpp::SizeOfDefinedType(*parcel, typenames);
1126     AIDL_FATAL_IF(parcelable_size == std::nullopt, *parcel);
1127     out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << parcel->GetName()
1128         << ">(), " << std::to_string(*parcelable_size) << ");\n";
1129   }
1130 }
1131 
GenerateParcelDefault(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1132 void GenerateParcelDefault(CodeWriter& out, const AidlStructuredParcelable* parcel,
1133                            const AidlTypenames& typenames) {
1134   out << "impl";
1135   WriteParams(out, parcel, ": Default");
1136   out << " Default for r#" << parcel->GetName();
1137   WriteParams(out, parcel);
1138   out << " {\n";
1139   out.Indent();
1140   out << "fn default() -> Self {\n";
1141   out.Indent();
1142   out << "Self {\n";
1143   out.Indent();
1144   size_t padding_index = 0;
1145   size_t struct_size = 0;
1146   const auto& fields = parcel->GetFields();
1147   if (fields.size() == 0 && parcel->IsFixedSize()) {
1148     out << "_unused: 0,\n";
1149   } else {
1150     for (const auto& variable : fields) {
1151       const auto& var_type = variable->GetType();
1152       // Generate initializer for padding for previous field if current field is i64 or f64
1153       if (parcel->IsFixedSize()) {
1154         auto field_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1155                                      parcel->IsVintfStability());
1156         GeneratePaddingField(out, field_type, struct_size, padding_index, "0");
1157 
1158         auto alignment = cpp::AlignmentOf(var_type, typenames);
1159         AIDL_FATAL_IF(alignment == std::nullopt, var_type);
1160         struct_size = cpp::AlignTo(struct_size, *alignment);
1161 
1162         auto var_size = cpp::SizeOf(var_type, typenames);
1163         AIDL_FATAL_IF(var_size == std::nullopt, var_type);
1164         struct_size += *var_size;
1165       }
1166 
1167       out << "r#" << variable->GetName() << ": ";
1168       if (variable->GetDefaultValue()) {
1169         out << variable->ValueString(ConstantValueDecorator);
1170       } else {
1171         // Some types don't implement "Default".
1172         // - Arrays
1173         if (variable->GetType().IsFixedSizeArray() && !variable->GetType().IsNullable()) {
1174           out << ArrayDefaultValue(variable->GetType());
1175         } else {
1176           out << "Default::default()";
1177         }
1178       }
1179       out << ",\n";
1180     }
1181     for (const auto& unused_param : FreeParams(parcel)) {
1182       out << "r#_phantom_" << unused_param << ": Default::default(),\n";
1183     }
1184   }
1185   out.Dedent();
1186   out << "}\n";
1187   out.Dedent();
1188   out << "}\n";
1189   out.Dedent();
1190   out << "}\n";
1191 }
1192 
GenerateParcelSerializeBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1193 void GenerateParcelSerializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
1194                                  const AidlTypenames& typenames) {
1195   out << "parcel.sized_write(|subparcel| {\n";
1196   out.Indent();
1197   for (const auto& variable : parcel->GetFields()) {
1198     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1199       out << "if (false) {\n";
1200       out.Indent();
1201     }
1202     if (TypeNeedsOption(variable->GetType(), typenames)) {
1203       out << "let __field_ref = self.r#" << variable->GetName()
1204           << ".as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
1205       out << "subparcel.write(__field_ref)?;\n";
1206     } else {
1207       out << "subparcel.write(&self.r#" << variable->GetName() << ")?;\n";
1208     }
1209     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1210       out.Dedent();
1211       out << "}\n";
1212     }
1213   }
1214   out << "Ok(())\n";
1215   out.Dedent();
1216   out << "})\n";
1217 }
1218 
GenerateParcelDeserializeBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)1219 void GenerateParcelDeserializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
1220                                    const AidlTypenames& typenames) {
1221   out << "parcel.sized_read(|subparcel| {\n";
1222   out.Indent();
1223 
1224   for (const auto& variable : parcel->GetFields()) {
1225     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1226       out << "if (false) {\n";
1227       out.Indent();
1228     }
1229     out << "if subparcel.has_more_data() {\n";
1230     out.Indent();
1231     if (TypeNeedsOption(variable->GetType(), typenames)) {
1232       out << "self.r#" << variable->GetName() << " = Some(subparcel.read()?);\n";
1233     } else {
1234       out << "self.r#" << variable->GetName() << " = subparcel.read()?;\n";
1235     }
1236     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1237       out.Dedent();
1238       out << "}\n";
1239     }
1240     out.Dedent();
1241     out << "}\n";
1242   }
1243   out << "Ok(())\n";
1244   out.Dedent();
1245   out << "})\n";
1246 }
1247 
GenerateParcelBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1248 void GenerateParcelBody(CodeWriter& out, const AidlUnionDecl* parcel,
1249                         const AidlTypenames& typenames) {
1250   GenerateDeprecated(out, *parcel);
1251   auto alignment = cpp::AlignmentOfDefinedType(*parcel, typenames);
1252   if (parcel->IsFixedSize()) {
1253     AIDL_FATAL_IF(alignment == std::nullopt, *parcel);
1254     auto tag = std::to_string(*alignment * 8);
1255     // This repr may use a tag larger than u8 to make sure the tag padding takes into account that
1256     // the overall alignment is computed as if i64/f64 were always 8-byte aligned
1257     out << "#[repr(C, u" << tag << ", align(" << std::to_string(*alignment) << "))]\n";
1258   }
1259   out << "pub enum r#" << parcel->GetName() << " {\n";
1260   out.Indent();
1261   for (const auto& variable : parcel->GetFields()) {
1262     GenerateDeprecated(out, *variable);
1263     auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD,
1264                                  parcel->IsVintfStability());
1265     out << variable->GetCapitalizedName() << "(" << field_type << "),\n";
1266   }
1267   out.Dedent();
1268   out << "}\n";
1269   if (parcel->IsFixedSize()) {
1270     for (const auto& variable : parcel->GetFields()) {
1271       const auto& var_type = variable->GetType();
1272       std::string rust_type = RustNameOf(var_type, typenames, StorageMode::PARCELABLE_FIELD,
1273                                          parcel->IsVintfStability());
1274       // Assert the size of each enum variant's payload
1275       auto variable_size = cpp::SizeOf(var_type, typenames);
1276       AIDL_FATAL_IF(variable_size == std::nullopt, var_type);
1277       out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << rust_type << ">(), "
1278           << std::to_string(*variable_size) << ");\n";
1279     }
1280     // Assert the alignment of the enum
1281     AIDL_FATAL_IF(alignment == std::nullopt, *parcel);
1282     out << "static_assertions::const_assert_eq!(std::mem::align_of::<" << parcel->GetName()
1283         << ">(), " << std::to_string(*alignment) << ");\n";
1284 
1285     // Assert the size of the enum, taking into the tag and its padding into account
1286     auto union_size = cpp::SizeOfDefinedType(*parcel, typenames);
1287     AIDL_FATAL_IF(union_size == std::nullopt, *parcel);
1288     out << "static_assertions::const_assert_eq!(std::mem::size_of::<" << parcel->GetName()
1289         << ">(), " << std::to_string(*union_size) << ");\n";
1290   }
1291 }
1292 
GenerateParcelDefault(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1293 void GenerateParcelDefault(CodeWriter& out, const AidlUnionDecl* parcel,
1294                            const AidlTypenames& typenames __attribute__((unused))) {
1295   out << "impl";
1296   WriteParams(out, parcel, ": Default");
1297   out << " Default for r#" << parcel->GetName();
1298   WriteParams(out, parcel);
1299   out << " {\n";
1300   out.Indent();
1301   out << "fn default() -> Self {\n";
1302   out.Indent();
1303 
1304   AIDL_FATAL_IF(parcel->GetFields().empty(), *parcel)
1305       << "Union '" << parcel->GetName() << "' is empty.";
1306   const auto& first_field = parcel->GetFields()[0];
1307   const auto& first_value = first_field->ValueString(ConstantValueDecorator);
1308 
1309   out << "Self::";
1310   if (first_field->GetDefaultValue()) {
1311     out << first_field->GetCapitalizedName() << "(" << first_value << ")\n";
1312   } else {
1313     out << first_field->GetCapitalizedName() << "(Default::default())\n";
1314   }
1315 
1316   out.Dedent();
1317   out << "}\n";
1318   out.Dedent();
1319   out << "}\n";
1320 }
1321 
GenerateParcelSerializeBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1322 void GenerateParcelSerializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
1323                                  const AidlTypenames& typenames) {
1324   out << "match self {\n";
1325   out.Indent();
1326   int tag = 0;
1327   for (const auto& variable : parcel->GetFields()) {
1328     out << "Self::" << variable->GetCapitalizedName() << "(v) => {\n";
1329     out.Indent();
1330     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1331       out << "if (true) {\n";
1332       out << "  Err(binder::StatusCode::BAD_VALUE)\n";
1333       out << "} else {\n";
1334       out.Indent();
1335     }
1336     out << "parcel.write(&" << std::to_string(tag++) << "i32)?;\n";
1337     if (TypeNeedsOption(variable->GetType(), typenames)) {
1338       out << "let __field_ref = v.as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
1339       out << "parcel.write(__field_ref)\n";
1340     } else {
1341       out << "parcel.write(v)\n";
1342     }
1343     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::WRITE)) {
1344       out.Dedent();
1345       out << "}\n";
1346     }
1347     out.Dedent();
1348     out << "}\n";
1349   }
1350   out.Dedent();
1351   out << "}\n";
1352 }
1353 
GenerateParcelDeserializeBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1354 void GenerateParcelDeserializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
1355                                    const AidlTypenames& typenames) {
1356   out << "let tag: i32 = parcel.read()?;\n";
1357   out << "match tag {\n";
1358   out.Indent();
1359   int tag = 0;
1360   for (const auto& variable : parcel->GetFields()) {
1361     auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD,
1362                                  parcel->IsVintfStability());
1363 
1364     out << std::to_string(tag++) << " => {\n";
1365     out.Indent();
1366     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1367       out << "if (true) {\n";
1368       out << "  Err(binder::StatusCode::BAD_VALUE)\n";
1369       out << "} else {\n";
1370       out.Indent();
1371     }
1372     out << "let value: " << field_type << " = ";
1373     if (TypeNeedsOption(variable->GetType(), typenames)) {
1374       out << "Some(parcel.read()?);\n";
1375     } else {
1376       out << "parcel.read()?;\n";
1377     }
1378     out << "*self = Self::" << variable->GetCapitalizedName() << "(value);\n";
1379     out << "Ok(())\n";
1380     if (variable->IsNew() && ShouldForceDowngradeFor(CommunicationSide::READ)) {
1381       out.Dedent();
1382       out << "}\n";
1383     }
1384     out.Dedent();
1385     out << "}\n";
1386   }
1387   out << "_ => {\n";
1388   out << "  Err(binder::StatusCode::BAD_VALUE)\n";
1389   out << "}\n";
1390   out.Dedent();
1391   out << "}\n";
1392 }
1393 
1394 template <typename ParcelableType>
GenerateParcelableTrait(CodeWriter & out,const ParcelableType * parcel,const AidlTypenames & typenames)1395 void GenerateParcelableTrait(CodeWriter& out, const ParcelableType* parcel,
1396                              const AidlTypenames& typenames) {
1397   out << "impl";
1398   WriteParams(out, parcel);
1399   out << " binder::Parcelable for r#" << parcel->GetName();
1400   WriteParams(out, parcel);
1401   out << " {\n";
1402   out.Indent();
1403 
1404   out << "fn write_to_parcel(&self, "
1405          "parcel: &mut binder::binder_impl::BorrowedParcel) -> std::result::Result<(), "
1406          "binder::StatusCode> "
1407          "{\n";
1408   out.Indent();
1409   GenerateParcelSerializeBody(out, parcel, typenames);
1410   out.Dedent();
1411   out << "}\n";
1412 
1413   out << "fn read_from_parcel(&mut self, "
1414          "parcel: &binder::binder_impl::BorrowedParcel) -> std::result::Result<(), "
1415          "binder::StatusCode> {\n";
1416   out.Indent();
1417   GenerateParcelDeserializeBody(out, parcel, typenames);
1418   out.Dedent();
1419   out << "}\n";
1420 
1421   out.Dedent();
1422   out << "}\n";
1423 
1424   // Emit the outer (de)serialization traits
1425   out << "binder::impl_serialize_for_parcelable!(r#" << parcel->GetName();
1426   WriteParams(out, parcel);
1427   out << ");\n";
1428   out << "binder::impl_deserialize_for_parcelable!(r#" << parcel->GetName();
1429   WriteParams(out, parcel);
1430   out << ");\n";
1431 }
1432 
1433 template <typename ParcelableType>
GenerateMetadataTrait(CodeWriter & out,const ParcelableType * parcel)1434 void GenerateMetadataTrait(CodeWriter& out, const ParcelableType* parcel) {
1435   out << "impl";
1436   WriteParams(out, parcel);
1437   out << " binder::binder_impl::ParcelableMetadata for r#" << parcel->GetName();
1438   WriteParams(out, parcel);
1439   out << " {\n";
1440   out.Indent();
1441 
1442   out << "fn get_descriptor() -> &'static str { \"" << parcel->GetCanonicalName() << "\" }\n";
1443 
1444   if (parcel->IsVintfStability()) {
1445     out << "fn get_stability(&self) -> binder::binder_impl::Stability { "
1446            "binder::binder_impl::Stability::Vintf }\n";
1447   }
1448 
1449   out.Dedent();
1450   out << "}\n";
1451 }
1452 
1453 template <typename ParcelableType>
GenerateRustParcel(CodeWriter * code_writer,const ParcelableType * parcel,const AidlTypenames & typenames)1454 void GenerateRustParcel(CodeWriter* code_writer, const ParcelableType* parcel,
1455                         const AidlTypenames& typenames) {
1456   vector<string> derives = parcel->RustDerive();
1457 
1458   // Debug is always derived because all Rust AIDL types implement it
1459   // ParcelFileDescriptor doesn't support any of the others because
1460   // it's a newtype over std::fs::File which only implements Debug
1461   derives.insert(derives.begin(), "Debug");
1462 
1463   *code_writer << "#[derive(" << Join(derives, ", ") << ")]\n";
1464   GenerateParcelBody(*code_writer, parcel, typenames);
1465   GenerateConstantDeclarations(*code_writer, *parcel, typenames);
1466   GenerateParcelDefault(*code_writer, parcel, typenames);
1467   GenerateParcelableTrait(*code_writer, parcel, typenames);
1468   GenerateMetadataTrait(*code_writer, parcel);
1469 }
1470 
GenerateRustEnumDeclaration(CodeWriter * code_writer,const AidlEnumDeclaration * enum_decl,const AidlTypenames & typenames)1471 void GenerateRustEnumDeclaration(CodeWriter* code_writer, const AidlEnumDeclaration* enum_decl,
1472                                  const AidlTypenames& typenames) {
1473   const auto& aidl_backing_type = enum_decl->GetBackingType();
1474   auto backing_type = RustNameOf(aidl_backing_type, typenames, StorageMode::VALUE,
1475                                  /*is_vintf_stability=*/false);
1476 
1477   *code_writer << "#![allow(non_upper_case_globals)]\n";
1478   *code_writer << "use binder::declare_binder_enum;\n";
1479   *code_writer << "declare_binder_enum! {\n";
1480   code_writer->Indent();
1481 
1482   GenerateDeprecated(*code_writer, *enum_decl);
1483   auto alignment = cpp::AlignmentOf(aidl_backing_type, typenames);
1484   AIDL_FATAL_IF(alignment == std::nullopt, *enum_decl);
1485   // u64 is aligned to 4 bytes on x86 which may underalign the whole struct if it's the backing type
1486   // so we need to set the alignment manually as if u64 were aligned to 8 bytes.
1487   *code_writer << "#[repr(C, align(" << std::to_string(*alignment) << "))]\n";
1488   *code_writer << "r#" << enum_decl->GetName() << " : [" << backing_type << "; "
1489                << std::to_string(enum_decl->GetEnumerators().size()) << "] {\n";
1490   code_writer->Indent();
1491   for (const auto& enumerator : enum_decl->GetEnumerators()) {
1492     auto value = enumerator->GetValue()->ValueString(aidl_backing_type, ConstantValueDecorator);
1493     GenerateDeprecated(*code_writer, *enumerator);
1494     *code_writer << "r#" << enumerator->GetName() << " = " << value << ",\n";
1495   }
1496   code_writer->Dedent();
1497   *code_writer << "}\n";
1498 
1499   code_writer->Dedent();
1500   *code_writer << "}\n";
1501 }
1502 
GenerateClass(CodeWriter * code_writer,const AidlDefinedType & defined_type,const AidlTypenames & types,const Options & options)1503 void GenerateClass(CodeWriter* code_writer, const AidlDefinedType& defined_type,
1504                    const AidlTypenames& types, const Options& options) {
1505   if (const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
1506       parcelable != nullptr) {
1507     GenerateRustParcel(code_writer, parcelable, types);
1508   } else if (const AidlEnumDeclaration* enum_decl = defined_type.AsEnumDeclaration();
1509              enum_decl != nullptr) {
1510     GenerateRustEnumDeclaration(code_writer, enum_decl, types);
1511   } else if (const AidlInterface* interface = defined_type.AsInterface(); interface != nullptr) {
1512     GenerateRustInterface(code_writer, interface, types, options);
1513   } else if (const AidlUnionDecl* union_decl = defined_type.AsUnionDeclaration();
1514              union_decl != nullptr) {
1515     GenerateRustParcel(code_writer, union_decl, types);
1516   } else {
1517     AIDL_FATAL(defined_type) << "Unrecognized type sent for Rust generation.";
1518   }
1519 
1520   for (const auto& nested : defined_type.GetNestedTypes()) {
1521     (*code_writer) << "pub mod r#" << nested->GetName() << " {\n";
1522     code_writer->Indent();
1523     GenerateClass(code_writer, *nested, types, options);
1524     code_writer->Dedent();
1525     (*code_writer) << "}\n";
1526   }
1527 }
1528 
GenerateRust(const string & filename,const Options & options,const AidlTypenames & types,const AidlDefinedType & defined_type,const IoDelegate & io_delegate)1529 void GenerateRust(const string& filename, const Options& options, const AidlTypenames& types,
1530                   const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
1531   CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
1532 
1533   GenerateAutoGenHeader(*code_writer, options);
1534 
1535   // Forbid the use of unsafe in auto-generated code.
1536   // Unsafe code should only be allowed in libbinder_rs.
1537   *code_writer << "#![forbid(unsafe_code)]\n";
1538   // Disable rustfmt on auto-generated files, including the golden outputs
1539   *code_writer << "#![cfg_attr(rustfmt, rustfmt_skip)]\n";
1540   GenerateClass(code_writer.get(), defined_type, types, options);
1541   GenerateMangledAliases(*code_writer, defined_type);
1542 
1543   AIDL_FATAL_IF(!code_writer->Close(), defined_type) << "I/O Error!";
1544 }
1545 
1546 }  // namespace rust
1547 }  // namespace aidl
1548 }  // namespace android
1549