uefi 0.37.0

This crate makes it easy to develop Rust software that leverages safe, convenient, and performant abstractions for UEFI functionality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Module for [`FileSystem`].

use crate::Status;
use crate::fs::*;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::fmt::{Debug, Formatter};
use uefi::boot::ScopedProtocol;

/// Return type for public [`FileSystem`] operations.
pub type FileSystemResult<T> = Result<T, Error>;

/// High-level file-system abstraction for UEFI volumes with an API that is
/// close to `std::fs`. It acts as convenient accessor around the
/// [`SimpleFileSystemProtocol`].
///
/// Please refer to the [module documentation] for more information.
///
/// [module documentation]: uefi::fs
pub struct FileSystem(ScopedProtocol<SimpleFileSystemProtocol>);

impl FileSystem {
    /// Constructor.
    #[must_use]
    pub fn new(proto: impl Into<Self>) -> Self {
        proto.into()
    }

    /// Returns `Ok(true)` if the path points at an existing file.
    ///
    /// If the file does not exist, `Ok(false)` is returned. If it cannot be
    /// determined whether the file exists or not, an error is returned.
    pub fn try_exists(&mut self, path: impl AsRef<Path>) -> FileSystemResult<bool> {
        match self.open(path.as_ref(), UefiFileMode::Read, false) {
            Ok(_) => Ok(true),
            Err(Error::Io(err)) => {
                if err.uefi_error.status() == Status::NOT_FOUND {
                    Ok(false)
                } else {
                    Err(Error::Io(err))
                }
            }
            Err(err) => Err(err),
        }
    }

    /// Copies the contents of one file to another. Creates the destination file
    /// if it doesn't exist and overwrites any content, if it exists.
    pub fn copy(
        &mut self,
        src_path: impl AsRef<Path>,
        dest_path: impl AsRef<Path>,
    ) -> FileSystemResult<()> {
        let src_path = src_path.as_ref();
        let dest_path = dest_path.as_ref();

        // Open the source file for reading.
        let mut src = self
            .open(src_path, UefiFileMode::Read, false)?
            .into_regular_file()
            .ok_or_else(|| {
                Error::Io(IoError {
                    path: src_path.to_path_buf(),
                    context: IoErrorContext::NotAFile,
                    uefi_error: Status::INVALID_PARAMETER.into(),
                })
            })?;

        // Get the source file's size in bytes.
        let src_size = {
            let src_info = src.get_boxed_info::<UefiFileInfo>().map_err(|err| {
                Error::Io(IoError {
                    path: src_path.to_path_buf(),
                    context: IoErrorContext::Metadata,
                    uefi_error: err,
                })
            })?;
            src_info.file_size()
        };

        // Try to delete the destination file in case it already exists. Allow
        // this to fail, since it might not exist. Or it might exist, but be a
        // directory, in which case the error will be caught when trying to
        // create the file.
        let _ = self.remove_file(dest_path);

        // Create and open the destination file.
        let mut dest = self
            .open(dest_path, UefiFileMode::CreateReadWrite, false)?
            .into_regular_file()
            .ok_or_else(|| {
                Error::Io(IoError {
                    path: dest_path.to_path_buf(),
                    context: IoErrorContext::OpenError,
                    uefi_error: Status::INVALID_PARAMETER.into(),
                })
            })?;

        // 1 MiB copy buffer.
        let mut chunk = vec![0; 1024 * 1024];

        // Read chunks from the source file and write to the destination file.
        let mut remaining_size = src_size;
        while remaining_size > 0 {
            // Read one chunk.
            let num_bytes_read = src.read(&mut chunk).map_err(|err| {
                Error::Io(IoError {
                    path: src_path.to_path_buf(),
                    context: IoErrorContext::ReadFailure,
                    uefi_error: err.to_err_without_payload(),
                })
            })?;

            // If the read returned no bytes, but `remaining_size > 0`, return
            // an error.
            if num_bytes_read == 0 {
                return Err(Error::Io(IoError {
                    path: src_path.to_path_buf(),
                    context: IoErrorContext::ReadFailure,
                    uefi_error: Status::ABORTED.into(),
                }));
            }

            // Copy the bytes read out to the destination file.
            dest.write(&chunk[..num_bytes_read]).map_err(|err| {
                Error::Io(IoError {
                    path: dest_path.to_path_buf(),
                    context: IoErrorContext::WriteFailure,
                    uefi_error: err.to_err_without_payload(),
                })
            })?;

            remaining_size -= u64::try_from(num_bytes_read).unwrap();
        }

        dest.flush().map_err(|err| {
            Error::Io(IoError {
                path: dest_path.to_path_buf(),
                context: IoErrorContext::FlushFailure,
                uefi_error: err,
            })
        })?;

        Ok(())
    }

    /// Creates a new, empty directory at the provided path
    pub fn create_dir(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> {
        let path = path.as_ref();
        self.open(path, UefiFileMode::CreateReadWrite, true)
            .map(|_| ())
    }

    /// Recursively create a directory and all of its parent components if they
    /// are missing.
    pub fn create_dir_all(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> {
        let path = path.as_ref();

        // Collect all relevant sub paths in a vector.
        let mut dirs_to_create = vec![path.to_path_buf()];
        while let Some(parent) = dirs_to_create.last().unwrap().parent() {
            dirs_to_create.push(parent)
        }
        // Now reverse, so that we have something like this:
        // - a
        // - a\\b
        // - a\\b\\c
        dirs_to_create.reverse();

        for parent in dirs_to_create {
            if !self.try_exists(&parent)? {
                self.create_dir(parent)?;
            }
        }

        Ok(())
    }

    /// Given a path, query the file system to get information about a file,
    /// directory, etc. Returns [`UefiFileInfo`].
    pub fn metadata(&mut self, path: impl AsRef<Path>) -> FileSystemResult<Box<UefiFileInfo>> {
        let path = path.as_ref();
        let mut file = self.open(path, UefiFileMode::Read, false)?;
        file.get_boxed_info().map_err(|err| {
            Error::Io(IoError {
                path: path.to_path_buf(),
                context: IoErrorContext::Metadata,
                uefi_error: err,
            })
        })
    }

    /// Read the entire contents of a file into a bytes vector.
    pub fn read(&mut self, path: impl AsRef<Path>) -> FileSystemResult<Vec<u8>> {
        let path = path.as_ref();

        let mut file = self
            .open(path, UefiFileMode::Read, false)?
            .into_regular_file()
            .ok_or_else(|| {
                Error::Io(IoError {
                    path: path.to_path_buf(),
                    context: IoErrorContext::NotAFile,
                    // We do not have a real UEFI error here as we have a logical
                    // problem.
                    uefi_error: Status::INVALID_PARAMETER.into(),
                })
            })?;

        let info = file.get_boxed_info::<UefiFileInfo>().map_err(|err| {
            Error::Io(IoError {
                path: path.to_path_buf(),
                context: IoErrorContext::Metadata,
                uefi_error: err,
            })
        })?;

        let mut vec = vec![0; info.file_size() as usize];
        let read_bytes = file.read(vec.as_mut_slice()).map_err(|err| {
            Error::Io(IoError {
                path: path.to_path_buf(),
                context: IoErrorContext::ReadFailure,
                uefi_error: err.to_err_without_payload(),
            })
        })?;

        // we read the whole file at once!
        if read_bytes != info.file_size() as usize {
            log::error!("Did only read {}/{} bytes", info.file_size(), read_bytes);
        }

        Ok(vec)
    }

    /// Returns an iterator over the entries within a directory.
    pub fn read_dir(&mut self, path: impl AsRef<Path>) -> FileSystemResult<UefiDirectoryIter> {
        let path = path.as_ref();
        let dir = self
            .open(path, UefiFileMode::Read, false)?
            .into_directory()
            .ok_or_else(|| {
                Error::Io(IoError {
                    path: path.to_path_buf(),
                    context: IoErrorContext::NotADirectory,
                    // We do not have a real UEFI error here as we have a logical
                    // problem.
                    uefi_error: Status::INVALID_PARAMETER.into(),
                })
            })?;
        Ok(UefiDirectoryIter::new(dir))
    }

    /// Read the entire contents of a file into a Rust string.
    pub fn read_to_string(&mut self, path: impl AsRef<Path>) -> FileSystemResult<String> {
        String::from_utf8(self.read(path)?).map_err(Error::Utf8Encoding)
    }

    /// Removes an empty directory.
    pub fn remove_dir(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> {
        let path = path.as_ref();

        let file = self
            .open(path, UefiFileMode::ReadWrite, false)?
            .into_type()
            .unwrap();

        match file {
            UefiFileType::Dir(dir) => dir.delete().map_err(|err| {
                Error::Io(IoError {
                    path: path.to_path_buf(),
                    context: IoErrorContext::CantDeleteDirectory,
                    uefi_error: err,
                })
            }),
            UefiFileType::Regular(_) => {
                Err(Error::Io(IoError {
                    path: path.to_path_buf(),
                    context: IoErrorContext::NotADirectory,
                    // We do not have a real UEFI error here as we have a logical
                    // problem.
                    uefi_error: Status::INVALID_PARAMETER.into(),
                }))
            }
        }
    }

    /// Removes a directory at this path, after removing all its contents. Use
    /// carefully!
    pub fn remove_dir_all(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> {
        let path = path.as_ref();
        for file_info in self
            .read_dir(path)?
            .filter_map(|file_info_result| file_info_result.ok())
        {
            if COMMON_SKIP_DIRS.contains(&file_info.file_name()) {
                continue;
            }

            let mut abs_entry_path = PathBuf::new();
            abs_entry_path.push(path);
            abs_entry_path.push(file_info.file_name());
            if file_info.is_directory() {
                // delete all inner files
                // This recursion is fine as there are no links in UEFI/FAT file
                // systems. No cycles possible.
                self.remove_dir_all(&abs_entry_path)?;
            } else {
                self.remove_file(abs_entry_path)?;
            }
        }
        // Now that the dir is empty, we delete it as final step.
        self.remove_dir(path)?;
        Ok(())
    }

    /// Removes a file from the filesystem.
    pub fn remove_file(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> {
        let path = path.as_ref();

        let file = self
            .open(path, UefiFileMode::ReadWrite, false)?
            .into_type()
            .unwrap();

        match file {
            UefiFileType::Regular(file) => file.delete().map_err(|err| {
                Error::Io(IoError {
                    path: path.to_path_buf(),
                    context: IoErrorContext::CantDeleteFile,
                    uefi_error: err,
                })
            }),
            UefiFileType::Dir(_) => Err(Error::Io(IoError {
                path: path.to_path_buf(),
                context: IoErrorContext::NotAFile,
                // We do not have a real UEFI error here as we have a logical
                // problem.
                uefi_error: Status::INVALID_PARAMETER.into(),
            })),
        }
    }

    /// Rename a file or directory to a new name, replacing the original file if
    /// it already exists.
    pub fn rename(
        &mut self,
        src_path: impl AsRef<Path>,
        dest_path: impl AsRef<Path>,
    ) -> FileSystemResult<()> {
        self.copy(&src_path, dest_path)?;
        self.remove_file(src_path)
    }

    /// Write a slice as the entire contents of a file. This function will
    /// create a file if it does not exist, and will entirely replace its
    /// contents if it does.
    pub fn write(
        &mut self,
        path: impl AsRef<Path>,
        content: impl AsRef<[u8]>,
    ) -> FileSystemResult<()> {
        let path = path.as_ref();

        // since there is no .truncate() in UEFI, we delete the file first it it
        // exists.
        if self.try_exists(path)? {
            self.remove_file(path)?;
        }

        let mut handle = self
            .open(path, UefiFileMode::CreateReadWrite, false)?
            .into_regular_file()
            .unwrap();

        handle.write(content.as_ref()).map_err(|err| {
            Error::Io(IoError {
                path: path.to_path_buf(),
                context: IoErrorContext::WriteFailure,
                uefi_error: err.to_err_without_payload(),
            })
        })?;
        handle.flush().map_err(|err| {
            Error::Io(IoError {
                path: path.to_path_buf(),
                context: IoErrorContext::FlushFailure,
                uefi_error: err,
            })
        })?;
        Ok(())
    }

    /// Opens a fresh handle to the root directory of the volume.
    fn open_root(&mut self) -> FileSystemResult<UefiDirectoryHandle> {
        self.0.open_volume().map_err(|err| {
            Error::Io(IoError {
                path: {
                    let mut path = PathBuf::new();
                    path.push(SEPARATOR_STR);
                    path
                },
                context: IoErrorContext::CantOpenVolume,
                uefi_error: err,
            })
        })
    }

    /// Wrapper around [`Self::open_root`] that opens the provided path as
    /// absolute path.
    ///
    /// May create a file if [`UefiFileMode::CreateReadWrite`] is set. May
    /// create a directory if [`UefiFileMode::CreateReadWrite`] and `create_dir`
    /// is set. The parameter `create_dir` is ignored otherwise.
    fn open(
        &mut self,
        path: &Path,
        mode: UefiFileMode,
        create_dir: bool,
    ) -> FileSystemResult<UefiFileHandle> {
        validate_path(path)?;

        let attr = if mode == UefiFileMode::CreateReadWrite && create_dir {
            UefiFileAttribute::DIRECTORY
        } else {
            UefiFileAttribute::empty()
        };

        self.open_root()?
            .open(path.to_cstr16(), mode, attr)
            .map_err(|err| {
                Error::Io(IoError {
                    path: path.to_path_buf(),
                    context: IoErrorContext::OpenError,
                    uefi_error: err,
                })
            })
    }
}

impl Debug for FileSystem {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let ptr: *const _ = &self.0;
        f.debug_tuple("FileSystem").field(&ptr).finish()
    }
}

impl From<uefi::boot::ScopedProtocol<SimpleFileSystemProtocol>> for FileSystem {
    fn from(proto: uefi::boot::ScopedProtocol<SimpleFileSystemProtocol>) -> Self {
        Self(proto)
    }
}