blob: 415e99ba82c7498dba808457c351e35ad6d32f6c [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
2 * Copyright (C) 2021 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
17use anyhow::{bail, Result};
18use nix::sys::stat::FileStat;
19use std::fs;
20use std::fs::File;
21use std::os::unix::fs::FileTypeExt;
22use std::os::unix::io::AsRawFd;
23use std::path::Path;
24use std::thread;
25use std::time::{Duration, Instant};
26
27/// Returns when the file exists on the given `path` or timeout (1s) occurs.
28pub fn wait_for_path<P: AsRef<Path>>(path: P) -> Result<()> {
29 const TIMEOUT: Duration = Duration::from_secs(1);
30 const INTERVAL: Duration = Duration::from_millis(10);
31 let begin = Instant::now();
32 while !path.as_ref().exists() {
33 if begin.elapsed() > TIMEOUT {
34 bail!("{:?} not found. TIMEOUT.", path.as_ref());
35 }
36 thread::sleep(INTERVAL);
37 }
38 Ok(())
39}
40
41/// Returns hexadecimal reprentation of a given byte array.
42pub fn hexstring_from(s: &[u8]) -> String {
43 s.iter().map(|byte| format!("{:02x}", byte)).reduce(|i, j| i + &j).unwrap_or(String::new())
44}
45
46/// fstat that accepts a path rather than FD
47pub fn fstat(p: &Path) -> Result<FileStat> {
48 let f = File::open(p)?;
49 Ok(nix::sys::stat::fstat(f.as_raw_fd())?)
50}
51
52// From include/uapi/linux/fs.h
53const BLK: u8 = 0x12;
54const BLKGETSIZE64: u8 = 114;
55nix::ioctl_read!(_blkgetsize64, BLK, BLKGETSIZE64, libc::size_t);
56
57/// Gets the size of a block device
58pub fn blkgetsize64(p: &Path) -> Result<u64> {
59 let f = File::open(p)?;
60 if !f.metadata()?.file_type().is_block_device() {
61 bail!("{:?} is not a block device", p);
62 }
63 let mut size: usize = 0;
64 // SAFETY: kernel copies the return value out to `size`. The file is kept open until the end of
65 // this function.
66 unsafe { _blkgetsize64(f.as_raw_fd(), &mut size) }?;
67 Ok(size as u64)
68}