• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! This module handles the interaction with virtual machine payload service.
16 
17 use android_system_virtualization_payload::aidl::android::system::virtualization::payload:: IVmPayloadService::{
18     IVmPayloadService, ENCRYPTEDSTORE_MOUNTPOINT, VM_APK_CONTENTS_PATH,
19     VM_PAYLOAD_SERVICE_SOCKET_NAME, AttestationResult::AttestationResult,
20 };
21 use anyhow::{bail, ensure, Context, Result};
22 use binder::{
23     unstable_api::{new_spibinder, AIBinder},
24     Strong, ExceptionCode,
25 };
26 use lazy_static::lazy_static;
27 use log::{error, info, LevelFilter};
28 use rpcbinder::{RpcServer, RpcSession};
29 use openssl::{ec::EcKey, sha::sha256, ecdsa::EcdsaSig};
30 use std::convert::Infallible;
31 use std::ffi::{CString, CStr};
32 use std::fmt::Debug;
33 use std::os::raw::{c_char, c_void};
34 use std::path::Path;
35 use std::ptr::{self, NonNull};
36 use std::sync::{
37     atomic::{AtomicBool, Ordering},
38     Mutex,
39 };
40 use vm_payload_status_bindgen::AVmAttestationStatus;
41 
42 /// Maximum size of an ECDSA signature for EC P-256 key is 72 bytes.
43 const MAX_ECDSA_P256_SIGNATURE_SIZE: usize = 72;
44 
45 lazy_static! {
46     static ref VM_APK_CONTENTS_PATH_C: CString =
47         CString::new(VM_APK_CONTENTS_PATH).expect("CString::new failed");
48     static ref PAYLOAD_CONNECTION: Mutex<Option<Strong<dyn IVmPayloadService>>> = Mutex::default();
49     static ref VM_ENCRYPTED_STORAGE_PATH_C: CString =
50         CString::new(ENCRYPTEDSTORE_MOUNTPOINT).expect("CString::new failed");
51 }
52 
53 static ALREADY_NOTIFIED: AtomicBool = AtomicBool::new(false);
54 
55 /// Return a connection to the payload service in Microdroid Manager. Uses the existing connection
56 /// if there is one, otherwise attempts to create a new one.
get_vm_payload_service() -> Result<Strong<dyn IVmPayloadService>>57 fn get_vm_payload_service() -> Result<Strong<dyn IVmPayloadService>> {
58     let mut connection = PAYLOAD_CONNECTION.lock().unwrap();
59     if let Some(strong) = &*connection {
60         Ok(strong.clone())
61     } else {
62         let new_connection: Strong<dyn IVmPayloadService> = RpcSession::new()
63             .setup_unix_domain_client(VM_PAYLOAD_SERVICE_SOCKET_NAME)
64             .context(format!("Failed to connect to service: {}", VM_PAYLOAD_SERVICE_SOCKET_NAME))?;
65         *connection = Some(new_connection.clone());
66         Ok(new_connection)
67     }
68 }
69 
70 /// Make sure our logging goes to logcat. It is harmless to call this more than once.
initialize_logging()71 fn initialize_logging() {
72     android_logger::init_once(
73         android_logger::Config::default().with_tag("vm_payload").with_max_level(LevelFilter::Info),
74     );
75 }
76 
77 /// In many cases clients can't do anything useful if API calls fail, and the failure
78 /// generally indicates that the VM is exiting or otherwise doomed. So rather than
79 /// returning a non-actionable error indication we just log the problem and abort
80 /// the process.
unwrap_or_abort<T, E: Debug>(result: Result<T, E>) -> T81 fn unwrap_or_abort<T, E: Debug>(result: Result<T, E>) -> T {
82     result.unwrap_or_else(|e| {
83         let msg = format!("{:?}", e);
84         error!("{msg}");
85         panic!("{msg}")
86     })
87 }
88 
89 /// Notifies the host that the payload is ready.
90 /// Panics on failure.
91 #[no_mangle]
AVmPayload_notifyPayloadReady()92 pub extern "C" fn AVmPayload_notifyPayloadReady() {
93     initialize_logging();
94 
95     if !ALREADY_NOTIFIED.swap(true, Ordering::Relaxed) {
96         unwrap_or_abort(try_notify_payload_ready());
97 
98         info!("Notified host payload ready successfully");
99     }
100 }
101 
102 /// Notifies the host that the payload is ready.
103 /// Returns a `Result` containing error information if failed.
try_notify_payload_ready() -> Result<()>104 fn try_notify_payload_ready() -> Result<()> {
105     get_vm_payload_service()?.notifyPayloadReady().context("Cannot notify payload ready")
106 }
107 
108 /// Runs a binder RPC server, serving the supplied binder service implementation on the given vsock
109 /// port.
110 ///
111 /// If and when the server is ready for connections (it is listening on the port), `on_ready` is
112 /// called to allow appropriate action to be taken - e.g. to notify clients that they may now
113 /// attempt to connect.
114 ///
115 /// The current thread joins the binder thread pool to handle incoming messages.
116 /// This function never returns.
117 ///
118 /// Panics on error (including unexpected server exit).
119 ///
120 /// # Safety
121 ///
122 /// If present, the `on_ready` callback must be a valid function pointer, which will be called at
123 /// most once, while this function is executing, with the `param` parameter.
124 #[no_mangle]
AVmPayload_runVsockRpcServer( service: *mut AIBinder, port: u32, on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>, param: *mut c_void, ) -> Infallible125 pub unsafe extern "C" fn AVmPayload_runVsockRpcServer(
126     service: *mut AIBinder,
127     port: u32,
128     on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>,
129     param: *mut c_void,
130 ) -> Infallible {
131     initialize_logging();
132 
133     // SAFETY: try_run_vsock_server has the same requirements as this function
134     unwrap_or_abort(unsafe { try_run_vsock_server(service, port, on_ready, param) })
135 }
136 
137 /// # Safety: Same as `AVmPayload_runVsockRpcServer`.
try_run_vsock_server( service: *mut AIBinder, port: u32, on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>, param: *mut c_void, ) -> Result<Infallible>138 unsafe fn try_run_vsock_server(
139     service: *mut AIBinder,
140     port: u32,
141     on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>,
142     param: *mut c_void,
143 ) -> Result<Infallible> {
144     // SAFETY: AIBinder returned has correct reference count, and the ownership can
145     // safely be taken by new_spibinder.
146     let service = unsafe { new_spibinder(service) };
147     if let Some(service) = service {
148         match RpcServer::new_vsock(service, libc::VMADDR_CID_HOST, port) {
149             Ok(server) => {
150                 if let Some(on_ready) = on_ready {
151                     // SAFETY: We're calling the callback with the parameter specified within the
152                     // allowed lifetime.
153                     unsafe { on_ready(param) };
154                 }
155                 server.join();
156                 bail!("RpcServer unexpectedly terminated");
157             }
158             Err(err) => {
159                 bail!("Failed to start RpcServer: {:?}", err);
160             }
161         }
162     } else {
163         bail!("Failed to convert the given service from AIBinder to SpIBinder.");
164     }
165 }
166 
167 /// Get a secret that is uniquely bound to this VM instance.
168 /// Panics on failure.
169 ///
170 /// # Safety
171 ///
172 /// Behavior is undefined if any of the following conditions are violated:
173 ///
174 /// * `identifier` must be [valid] for reads of `identifier_size` bytes.
175 /// * `secret` must be [valid] for writes of `size` bytes.
176 ///
177 /// [valid]: ptr#safety
178 #[no_mangle]
AVmPayload_getVmInstanceSecret( identifier: *const u8, identifier_size: usize, secret: *mut u8, size: usize, )179 pub unsafe extern "C" fn AVmPayload_getVmInstanceSecret(
180     identifier: *const u8,
181     identifier_size: usize,
182     secret: *mut u8,
183     size: usize,
184 ) {
185     initialize_logging();
186 
187     // SAFETY: See the requirements on `identifier` above.
188     let identifier = unsafe { std::slice::from_raw_parts(identifier, identifier_size) };
189     let vm_secret = unwrap_or_abort(try_get_vm_instance_secret(identifier, size));
190 
191     // SAFETY: See the requirements on `secret` above; `vm_secret` is known to have length `size`,
192     // and cannot overlap `secret` because we just allocated it.
193     unsafe {
194         ptr::copy_nonoverlapping(vm_secret.as_ptr(), secret, size);
195     }
196 }
197 
try_get_vm_instance_secret(identifier: &[u8], size: usize) -> Result<Vec<u8>>198 fn try_get_vm_instance_secret(identifier: &[u8], size: usize) -> Result<Vec<u8>> {
199     let vm_secret = get_vm_payload_service()?
200         .getVmInstanceSecret(identifier, i32::try_from(size)?)
201         .context("Cannot get VM instance secret")?;
202     ensure!(
203         vm_secret.len() == size,
204         "Returned secret has {} bytes, expected {}",
205         vm_secret.len(),
206         size
207     );
208     Ok(vm_secret)
209 }
210 
211 /// Get the VM's attestation chain.
212 /// Panics on failure.
213 ///
214 /// # Safety
215 ///
216 /// Behavior is undefined if any of the following conditions are violated:
217 ///
218 /// * `data` must be [valid] for writes of `size` bytes, if size > 0.
219 ///
220 /// [valid]: ptr#safety
221 #[no_mangle]
AVmPayload_getDiceAttestationChain(data: *mut u8, size: usize) -> usize222 pub unsafe extern "C" fn AVmPayload_getDiceAttestationChain(data: *mut u8, size: usize) -> usize {
223     initialize_logging();
224 
225     let chain = unwrap_or_abort(try_get_dice_attestation_chain());
226     if size != 0 {
227         // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
228         // the length of either buffer, and `chain` cannot overlap `data` because we just allocated
229         // it. We allow data to be null, which is never valid, but only if size == 0 which is
230         // checked above.
231         unsafe { ptr::copy_nonoverlapping(chain.as_ptr(), data, std::cmp::min(chain.len(), size)) };
232     }
233     chain.len()
234 }
235 
try_get_dice_attestation_chain() -> Result<Vec<u8>>236 fn try_get_dice_attestation_chain() -> Result<Vec<u8>> {
237     get_vm_payload_service()?.getDiceAttestationChain().context("Cannot get attestation chain")
238 }
239 
240 /// Get the VM's attestation CDI.
241 /// Panics on failure.
242 ///
243 /// # Safety
244 ///
245 /// Behavior is undefined if any of the following conditions are violated:
246 ///
247 /// * `data` must be [valid] for writes of `size` bytes, if size > 0.
248 ///
249 /// [valid]: ptr#safety
250 #[no_mangle]
AVmPayload_getDiceAttestationCdi(data: *mut u8, size: usize) -> usize251 pub unsafe extern "C" fn AVmPayload_getDiceAttestationCdi(data: *mut u8, size: usize) -> usize {
252     initialize_logging();
253 
254     let cdi = unwrap_or_abort(try_get_dice_attestation_cdi());
255     if size != 0 {
256         // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
257         // the length of either buffer, and `cdi` cannot overlap `data` because we just allocated
258         // it. We allow data to be null, which is never valid, but only if size == 0 which is
259         // checked above.
260         unsafe { ptr::copy_nonoverlapping(cdi.as_ptr(), data, std::cmp::min(cdi.len(), size)) };
261     }
262     cdi.len()
263 }
264 
try_get_dice_attestation_cdi() -> Result<Vec<u8>>265 fn try_get_dice_attestation_cdi() -> Result<Vec<u8>> {
266     get_vm_payload_service()?.getDiceAttestationCdi().context("Cannot get attestation CDI")
267 }
268 
269 /// Requests the remote attestation of the client VM.
270 ///
271 /// The challenge will be included in the certificate chain in the attestation result,
272 /// serving as proof of the freshness of the result.
273 ///
274 /// # Safety
275 ///
276 /// Behavior is undefined if any of the following conditions are violated:
277 ///
278 /// * `challenge` must be [valid] for reads of `challenge_size` bytes.
279 ///
280 /// [valid]: ptr#safety
281 #[no_mangle]
AVmPayload_requestAttestation( challenge: *const u8, challenge_size: usize, res: &mut *mut AttestationResult, ) -> AVmAttestationStatus282 pub unsafe extern "C" fn AVmPayload_requestAttestation(
283     challenge: *const u8,
284     challenge_size: usize,
285     res: &mut *mut AttestationResult,
286 ) -> AVmAttestationStatus {
287     // SAFETY: The caller guarantees that `challenge` is valid for reads and `res` is valid
288     // for writes.
289     unsafe {
290         request_attestation(
291             challenge,
292             challenge_size,
293             false, // test_mode
294             res,
295         )
296     }
297 }
298 
299 /// Requests the remote attestation of the client VM for testing.
300 ///
301 /// # Safety
302 ///
303 /// Behavior is undefined if any of the following conditions are violated:
304 ///
305 /// * `challenge` must be [valid] for reads of `challenge_size` bytes.
306 ///
307 /// [valid]: ptr#safety
308 #[no_mangle]
AVmPayload_requestAttestationForTesting( challenge: *const u8, challenge_size: usize, res: &mut *mut AttestationResult, ) -> AVmAttestationStatus309 pub unsafe extern "C" fn AVmPayload_requestAttestationForTesting(
310     challenge: *const u8,
311     challenge_size: usize,
312     res: &mut *mut AttestationResult,
313 ) -> AVmAttestationStatus {
314     // SAFETY: The caller guarantees that `challenge` is valid for reads and `res` is valid
315     // for writes.
316     unsafe {
317         request_attestation(
318             challenge,
319             challenge_size,
320             true, // test_mode
321             res,
322         )
323     }
324 }
325 
326 /// Requests the remote attestation of the client VM.
327 ///
328 /// # Safety
329 ///
330 /// Behavior is undefined if any of the following conditions are violated:
331 ///
332 /// * `challenge` must be [valid] for reads of `challenge_size` bytes.
333 ///
334 /// [valid]: ptr#safety
request_attestation( challenge: *const u8, challenge_size: usize, test_mode: bool, res: &mut *mut AttestationResult, ) -> AVmAttestationStatus335 unsafe fn request_attestation(
336     challenge: *const u8,
337     challenge_size: usize,
338     test_mode: bool,
339     res: &mut *mut AttestationResult,
340 ) -> AVmAttestationStatus {
341     initialize_logging();
342     const MAX_CHALLENGE_SIZE: usize = 64;
343     if challenge_size > MAX_CHALLENGE_SIZE {
344         return AVmAttestationStatus::ATTESTATION_ERROR_INVALID_CHALLENGE;
345     }
346     let challenge = if challenge_size == 0 {
347         &[]
348     } else {
349         // SAFETY: The caller guarantees that `challenge` is valid for reads of
350         // `challenge_size` bytes and `challenge_size` is not zero.
351         unsafe { std::slice::from_raw_parts(challenge, challenge_size) }
352     };
353     let service = unwrap_or_abort(get_vm_payload_service());
354     match service.requestAttestation(challenge, test_mode) {
355         Ok(attestation_res) => {
356             *res = Box::into_raw(Box::new(attestation_res));
357             AVmAttestationStatus::ATTESTATION_OK
358         }
359         Err(e) => {
360             error!("Remote attestation failed: {e:?}");
361             binder_status_to_attestation_status(e)
362         }
363     }
364 }
365 
binder_status_to_attestation_status(status: binder::Status) -> AVmAttestationStatus366 fn binder_status_to_attestation_status(status: binder::Status) -> AVmAttestationStatus {
367     match status.exception_code() {
368         ExceptionCode::UNSUPPORTED_OPERATION => AVmAttestationStatus::ATTESTATION_ERROR_UNSUPPORTED,
369         _ => AVmAttestationStatus::ATTESTATION_ERROR_ATTESTATION_FAILED,
370     }
371 }
372 
373 /// Converts the return value from `AVmPayload_requestAttestation` to a text string
374 /// representing the error code.
375 #[no_mangle]
AVmAttestationStatus_toString(status: AVmAttestationStatus) -> *const c_char376 pub extern "C" fn AVmAttestationStatus_toString(status: AVmAttestationStatus) -> *const c_char {
377     let message = match status {
378         AVmAttestationStatus::ATTESTATION_OK => {
379             CStr::from_bytes_with_nul(b"The remote attestation completes successfully.\0").unwrap()
380         }
381         AVmAttestationStatus::ATTESTATION_ERROR_INVALID_CHALLENGE => {
382             CStr::from_bytes_with_nul(b"The challenge size is not between 0 and 64.\0").unwrap()
383         }
384         AVmAttestationStatus::ATTESTATION_ERROR_ATTESTATION_FAILED => {
385             CStr::from_bytes_with_nul(b"Failed to attest the VM. Please retry at a later time.\0")
386                 .unwrap()
387         }
388         AVmAttestationStatus::ATTESTATION_ERROR_UNSUPPORTED => CStr::from_bytes_with_nul(
389             b"Remote attestation is not supported in the current environment.\0",
390         )
391         .unwrap(),
392     };
393     message.as_ptr()
394 }
395 
396 /// Reads the DER-encoded ECPrivateKey structure specified in [RFC 5915 s3] for the
397 /// EC P-256 private key from the provided attestation result.
398 ///
399 /// # Safety
400 ///
401 /// Behavior is undefined if any of the following conditions are violated:
402 ///
403 /// * `data` must be [valid] for writes of `size` bytes, if size > 0.
404 /// * The region of memory beginning at `data` with `size` bytes must not overlap with the
405 ///  region of memory `res` points to.
406 ///
407 /// [valid]: ptr#safety
408 /// [RFC 5915 s3]: https://datatracker.ietf.org/doc/html/rfc5915#section-3
409 #[no_mangle]
AVmAttestationResult_getPrivateKey( res: &AttestationResult, data: *mut u8, size: usize, ) -> usize410 pub unsafe extern "C" fn AVmAttestationResult_getPrivateKey(
411     res: &AttestationResult,
412     data: *mut u8,
413     size: usize,
414 ) -> usize {
415     let private_key = &res.privateKey;
416     if size != 0 {
417         let data = NonNull::new(data).expect("data must not be null when size > 0");
418         // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
419         // the length of either buffer, and the caller ensures that `private_key` cannot overlap
420         // `data`. We allow data to be null, which is never valid, but only if size == 0
421         // which is checked above.
422         unsafe {
423             ptr::copy_nonoverlapping(
424                 private_key.as_ptr(),
425                 data.as_ptr(),
426                 std::cmp::min(private_key.len(), size),
427             )
428         };
429     }
430     private_key.len()
431 }
432 
433 /// Signs the given message using ECDSA P-256, the message is first hashed with SHA-256 and
434 /// then it is signed with the attested EC P-256 private key in the attestation result.
435 ///
436 /// # Safety
437 ///
438 /// Behavior is undefined if any of the following conditions are violated:
439 ///
440 /// * `message` must be [valid] for reads of `message_size` bytes.
441 /// * `data` must be [valid] for writes of `size` bytes, if size > 0.
442 /// * The region of memory beginning at `data` with `size` bytes must not overlap with the
443 ///  region of memory `res` or `message` point to.
444 ///
445 ///
446 /// [valid]: ptr#safety
447 #[no_mangle]
AVmAttestationResult_sign( res: &AttestationResult, message: *const u8, message_size: usize, data: *mut u8, size: usize, ) -> usize448 pub unsafe extern "C" fn AVmAttestationResult_sign(
449     res: &AttestationResult,
450     message: *const u8,
451     message_size: usize,
452     data: *mut u8,
453     size: usize,
454 ) -> usize {
455     // A DER-encoded ECDSA signature can have varying sizes even with the same EC Key and message,
456     // due to the encoding of the random values r and s that are part of the signature.
457     if size == 0 {
458         return MAX_ECDSA_P256_SIGNATURE_SIZE;
459     }
460     if message_size == 0 {
461         panic!("Message to be signed must not be empty.")
462     }
463     // SAFETY: See the requirements on `message` above.
464     let message = unsafe { std::slice::from_raw_parts(message, message_size) };
465     let signature = unwrap_or_abort(try_ecdsa_sign(message, &res.privateKey));
466     let data = NonNull::new(data).expect("data must not be null when size > 0");
467     // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
468     // the length of either buffer, and the caller ensures that `signature` cannot overlap
469     // `data`. We allow data to be null, which is never valid, but only if size == 0
470     // which is checked above.
471     unsafe {
472         ptr::copy_nonoverlapping(
473             signature.as_ptr(),
474             data.as_ptr(),
475             usize::min(signature.len(), size),
476         )
477     };
478     if size < signature.len() {
479         // If the buffer is too small, return the maximum size of the signature to allow the caller
480         // to allocate a buffer large enough to call this function again.
481         MAX_ECDSA_P256_SIGNATURE_SIZE
482     } else {
483         signature.len()
484     }
485 }
486 
try_ecdsa_sign(message: &[u8], der_encoded_ec_private_key: &[u8]) -> Result<Vec<u8>>487 fn try_ecdsa_sign(message: &[u8], der_encoded_ec_private_key: &[u8]) -> Result<Vec<u8>> {
488     let private_key = EcKey::private_key_from_der(der_encoded_ec_private_key)?;
489     let digest = sha256(message);
490     let sig = EcdsaSig::sign(&digest, &private_key)?;
491     Ok(sig.to_der()?)
492 }
493 
494 /// Gets the number of certificates in the certificate chain.
495 #[no_mangle]
AVmAttestationResult_getCertificateCount(res: &AttestationResult) -> usize496 pub extern "C" fn AVmAttestationResult_getCertificateCount(res: &AttestationResult) -> usize {
497     res.certificateChain.len()
498 }
499 
500 /// Retrieves the certificate at the given `index` from the certificate chain in the provided
501 /// attestation result.
502 ///
503 /// # Safety
504 ///
505 /// Behavior is undefined if any of the following conditions are violated:
506 ///
507 /// * `data` must be [valid] for writes of `size` bytes, if size > 0.
508 /// * `index` must be within the range of [0, number of certificates). The number of certificates
509 ///   can be obtained with `AVmAttestationResult_getCertificateCount`.
510 /// * The region of memory beginning at `data` with `size` bytes must not overlap with the
511 ///  region of memory `res` points to.
512 ///
513 /// [valid]: ptr#safety
514 #[no_mangle]
AVmAttestationResult_getCertificateAt( res: &AttestationResult, index: usize, data: *mut u8, size: usize, ) -> usize515 pub unsafe extern "C" fn AVmAttestationResult_getCertificateAt(
516     res: &AttestationResult,
517     index: usize,
518     data: *mut u8,
519     size: usize,
520 ) -> usize {
521     let certificate =
522         &res.certificateChain.get(index).expect("The index is out of bounds.").encodedCertificate;
523     if size != 0 {
524         let data = NonNull::new(data).expect("data must not be null when size > 0");
525         // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
526         // the length of either buffer, and the caller ensures that `certificate` cannot overlap
527         // `data`. We allow data to be null, which is never valid, but only if size == 0
528         // which is checked above.
529         unsafe {
530             ptr::copy_nonoverlapping(
531                 certificate.as_ptr(),
532                 data.as_ptr(),
533                 std::cmp::min(certificate.len(), size),
534             )
535         };
536     }
537     certificate.len()
538 }
539 
540 /// Frees all the data owned by given attestation result and result itself.
541 ///
542 /// # Safety
543 ///
544 /// Behavior is undefined if any of the following conditions are violated:
545 ///
546 /// * `res` must point to a valid `AttestationResult` and has not been freed before.
547 #[no_mangle]
AVmAttestationResult_free(res: *mut AttestationResult)548 pub unsafe extern "C" fn AVmAttestationResult_free(res: *mut AttestationResult) {
549     if !res.is_null() {
550         // SAFETY: The result is only freed once is ensured by the caller.
551         let res = unsafe { Box::from_raw(res) };
552         drop(res)
553     }
554 }
555 
556 /// Gets the path to the APK contents.
557 #[no_mangle]
AVmPayload_getApkContentsPath() -> *const c_char558 pub extern "C" fn AVmPayload_getApkContentsPath() -> *const c_char {
559     VM_APK_CONTENTS_PATH_C.as_ptr()
560 }
561 
562 /// Gets the path to the VM's encrypted storage.
563 #[no_mangle]
AVmPayload_getEncryptedStoragePath() -> *const c_char564 pub extern "C" fn AVmPayload_getEncryptedStoragePath() -> *const c_char {
565     if Path::new(ENCRYPTEDSTORE_MOUNTPOINT).exists() {
566         VM_ENCRYPTED_STORAGE_PATH_C.as_ptr()
567     } else {
568         ptr::null()
569     }
570 }
571