• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 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 use anyhow::anyhow;
18 use memmap2::MmapMut;
19 use std::fs::{self, OpenOptions};
20 
21 use aconfig_storage_file::AconfigStorageError::{self, FileReadFail, MapFileFail};
22 
23 /// Get the mutable memory mapping of a storage file
24 ///
25 /// # Safety
26 ///
27 /// The memory mapped file may have undefined behavior if there are writes to this
28 /// file not thru this memory mapped file or there are concurrent writes to this
29 /// memory mapped file. Ensure all writes to the underlying file are thru this memory
30 /// mapped file and there are no concurrent writes.
map_file(file_path: &str) -> Result<MmapMut, AconfigStorageError>31 pub(crate) unsafe fn map_file(file_path: &str) -> Result<MmapMut, AconfigStorageError> {
32     // make sure file has read write permission
33     let perms = fs::metadata(file_path).unwrap().permissions();
34     if perms.readonly() {
35         return Err(MapFileFail(anyhow!("fail to map non read write storage file {}", file_path)));
36     }
37 
38     let file =
39         OpenOptions::new().read(true).write(true).open(file_path).map_err(|errmsg| {
40             FileReadFail(anyhow!("Failed to open file {}: {}", file_path, errmsg))
41         })?;
42 
43     unsafe {
44         let mapped_file = MmapMut::map_mut(&file).map_err(|errmsg| {
45             MapFileFail(anyhow!("fail to map storage file {}: {}", file_path, errmsg))
46         })?;
47         Ok(mapped_file)
48     }
49 }
50 
51 #[cfg(test)]
52 mod tests {
53     use super::*;
54     use crate::test_utils::copy_to_temp_file;
55     use std::io::Read;
56 
57     #[test]
test_mapped_file_contents()58     fn test_mapped_file_contents() {
59         let mut rw_val_file = copy_to_temp_file("./tests/flag.val", false).unwrap();
60         let mut rw_info_file = copy_to_temp_file("./tests/flag.info", false).unwrap();
61         let flag_val = rw_val_file.path().display().to_string();
62         let flag_info = rw_info_file.path().display().to_string();
63 
64         let mut content = Vec::new();
65         rw_val_file.read_to_end(&mut content).unwrap();
66 
67         // SAFETY:
68         // The safety here is guaranteed here as no writes happens to this temp file
69         unsafe {
70             let mmaped_file = map_file(&flag_val).unwrap();
71             assert_eq!(mmaped_file[..], content[..]);
72         }
73 
74         let mut content = Vec::new();
75         rw_info_file.read_to_end(&mut content).unwrap();
76 
77         // SAFETY:
78         // The safety here is guaranteed here as no writes happens to this temp file
79         unsafe {
80             let mmaped_file = map_file(&flag_info).unwrap();
81             assert_eq!(mmaped_file[..], content[..]);
82         }
83     }
84 
85     #[test]
test_mapped_read_only_file()86     fn test_mapped_read_only_file() {
87         let ro_val_file = copy_to_temp_file("./tests/flag.val", true).unwrap();
88         let flag_val = ro_val_file.path().display().to_string();
89 
90         // SAFETY:
91         // The safety here is guaranteed here as no writes happens to this temp file
92         unsafe {
93             let error = map_file(&flag_val).unwrap_err();
94             assert_eq!(
95                 format!("{:?}", error),
96                 format!("MapFileFail(fail to map non read write storage file {})", flag_val)
97             );
98         }
99     }
100 }
101