Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ default = []
## ELF parsing, for deriving NRO and NSO segments from a linked binary
elf-parsing = ["filesystem-support", "dep:object"]
## Filesystem-backed write layer: the format builders and their output paths
filesystem-support = ["dep:fs-err", "dep:sha2", "serde/std"]
filesystem-support = ["dep:fs-err", "dep:serde", "dep:sha2", "serde/std"]
## LZ4 compression and decompression of NSO segments
lz4-compression = ["filesystem-support", "dep:lz4_flex"]

Expand All @@ -29,7 +29,7 @@ bitflags = "2.9"
fs-err = { version = "3.1", optional = true }
lz4_flex = { version = "0.11", optional = true, default-features = false }
object = { version = "0.38", optional = true, default-features = false, features = ["read", "elf"] }
serde = { version = "1.0", default-features = false, features = ["derive"] }
serde = { version = "1.0", optional = true, default-features = false, features = ["derive"] }
sha2 = { version = "0.10", optional = true, default-features = false }
static_assertions = "1.1"
thiserror = { version = "2.0", default-features = false }
Expand Down
109 changes: 101 additions & 8 deletions src/raw/romfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ use zerocopy::{
little_endian::{U32, U64},
};

/// The offset standing for "nothing here", which every chain in the tree ends with.
///
/// An entry is addressed by its byte offset into a metadata table, and zero is a valid one: it is
/// the root directory. So the format cannot spell absence as `0`, and reserves the largest offset
/// instead, which no table ever reaches. It terminates the sibling, child and hash chains alike,
/// and fills a hash bucket holding no entry.
pub const NO_ENTRY: u32 = 0xFFFF_FFFF;

/// Locates the four tables the tree is stored in, and the region the file contents sit in.
///
/// Every offset is from the start of the image. The hash tables turn a name lookup into a bucket
Expand Down Expand Up @@ -57,7 +65,7 @@ const_assert_eq!(align_of::<RomFsHeader>(), 0x1);
///
/// The tree is threaded rather than nested: a directory names its first child and its next sibling,
/// and walking a directory means following `child_offset` once and then `sibling_offset` until the
/// chain ends. Every offset is a byte offset into the directory metadata table, and `U32::MAX`
/// chain ends. Every offset is a byte offset into the directory metadata table, and [`NO_ENTRY`]
/// terminates a chain.
///
/// The `0x18` bytes asserted below are the fixed prefix only; the entry's name follows it inline.
Expand All @@ -66,15 +74,15 @@ const_assert_eq!(align_of::<RomFsHeader>(), 0x1);
#[derive(Debug, Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
pub struct RomFsDirEntry {
/// The directory this one sits in, or `U32::MAX` for the root, which is its own parent.
/// The directory this one sits in, or [`NO_ENTRY`] for the root, which is its own parent.
pub parent_offset: U32,
/// The next directory sharing this parent, or `U32::MAX` at the end of the chain.
/// The next directory sharing this parent, or [`NO_ENTRY`] at the end of the chain.
pub sibling_offset: U32,
/// The first subdirectory, or `U32::MAX` when there are none.
/// The first subdirectory, or [`NO_ENTRY`] when there are none.
pub child_offset: U32,
/// The first file in this directory, or `U32::MAX` when there are none.
/// The first file in this directory, or [`NO_ENTRY`] when there are none.
pub file_offset: U32,
/// The next entry in the same hash bucket, or `U32::MAX` at the end of the chain.
/// The next entry in the same hash bucket, or [`NO_ENTRY`] at the end of the chain.
pub hash_sibling_offset: U32,
/// Length of the name following this entry, in bytes.
pub name_len: U32,
Expand All @@ -99,13 +107,13 @@ const_assert_eq!(align_of::<RomFsDirEntry>(), 0x1);
pub struct RomFsFileEntry {
/// The directory this file sits in, as an offset into the directory metadata table.
pub parent_offset: U32,
/// The next file sharing this parent, or `U32::MAX` at the end of the chain.
/// The next file sharing this parent, or [`NO_ENTRY`] at the end of the chain.
pub sibling_offset: U32,
/// Offset of the file's first byte, from [`RomFsHeader::file_data_offset`].
pub data_offset: U64,
/// Length of the file in bytes.
pub data_size: U64,
/// The next entry in the same hash bucket, or `U32::MAX` at the end of the chain.
/// The next entry in the same hash bucket, or [`NO_ENTRY`] at the end of the chain.
pub hash_sibling_offset: U32,
/// Length of the name following this entry, in bytes.
pub name_len: U32,
Expand All @@ -115,3 +123,88 @@ pub struct RomFsFileEntry {
// Verify struct size - https://switchbrew.org/wiki/RomFS#File_Entry
const_assert_eq!(size_of::<RomFsFileEntry>(), 0x20);
const_assert_eq!(align_of::<RomFsFileEntry>(), 0x1);

/// Hashes one path component to the bucket its entry is chained from.
///
/// An entry's bucket is this value modulo the number of buckets in the table, which the header
/// gives as a byte length rather than as a count. A reader hashes the name it is looking for and
/// walks that bucket's chain; a writer hashes each name it places and threads the chain the reader
/// will walk. The two have to agree exactly, which is why the arithmetic lives here rather than
/// once on each side.
///
/// `parent_offset` is the offset of the containing directory's entry, so the same name under two
/// parents lands in two different buckets. The name is taken as bytes because that is how it is
/// stored: the format calls it UTF-8, but hashing never decodes it, and a reader matching against
/// an image should not have to either.
///
/// This is not a general-purpose hash and has no property worth relying on beyond agreeing with
/// the format.
pub fn path_hash(parent_offset: u32, name: &[u8]) -> u32 {
let mut hash = parent_offset ^ 123_456_789;
for byte in name {
hash = hash.rotate_right(5) ^ u32::from(*byte);
}
hash
}

#[cfg(test)]
mod tests {
use super::path_hash;

/// Offset of the root directory's entry, which is the first in its table.
const ROOT: u32 = 0;

#[test]
fn path_hash_with_an_empty_name_returns_the_seeded_parent() {
//* Given
// A name with no bytes to fold in, so the seed is the whole result.
let name = b"";

//* When
let hash = path_hash(ROOT, name);

//* Then
assert_eq!(
hash, 123_456_789,
"an empty name should hash to the parent offset seeded and otherwise untouched"
);
}

#[test]
fn path_hash_with_a_different_parent_returns_a_different_hash() {
//* Given
// One name, hashed under the root, against the directory whose entry
// follows the root's one entry in.
let name = b"data";
let sibling_dir = 0x18;
let under_root = path_hash(ROOT, name);

//* When
let under_sibling_dir = path_hash(sibling_dir, name);

//* Then
assert_ne!(
under_sibling_dir, under_root,
"the parent offset should reach the hash, so one name under two parents lands in two buckets"
);
}

#[test]
fn path_hash_with_a_multi_byte_name_hashes_every_byte() {
//* Given
// Four characters stored as twelve UTF-8 bytes.
let name = "ファイル".as_bytes();

//* When
let hash = path_hash(ROOT, name);

//* Then
// Twelve rounds rather than four: hashing walks the stored bytes and never
// decodes them into characters. The constant pins the rotation direction and
// the order of the rotate and the XOR along with it.
assert_eq!(
hash, 0xF3B5_84EB,
"a non-ASCII name should fold in one round per UTF-8 byte"
);
}
}
10 changes: 5 additions & 5 deletions src/read/romfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

use zerocopy::FromBytes;

use crate::raw::romfs::{RomFsDirEntry, RomFsFileEntry, RomFsHeader};
use crate::raw::romfs::{NO_ENTRY, RomFsDirEntry, RomFsFileEntry, RomFsHeader};

/// A borrowed view of a RomFS image, with its four tables proven to lie inside the buffer.
///
Expand Down Expand Up @@ -331,7 +331,7 @@ impl<'a> RomFsDir<'a> {
let mut child_offset = self.entry.child_offset.get();
let table_base = self.romfs.header.dir_meta_table_offset.get() as usize;

while child_offset != u32::MAX {
while child_offset != NO_ENTRY {
let child = RomFsDir::from_offset(self.romfs, child_offset, table_base)?;
if child.name() == name {
return Ok(child);
Expand All @@ -347,7 +347,7 @@ impl<'a> RomFsDir<'a> {
let mut file_offset = self.entry.file_offset.get();
let table_base = self.romfs.header.file_meta_table_offset.get() as usize;

while file_offset != u32::MAX {
while file_offset != NO_ENTRY {
let file = RomFsFile::from_offset(self.romfs, file_offset, table_base)?;
if file.name() == name {
return Ok(file);
Expand Down Expand Up @@ -512,7 +512,7 @@ impl<'a> Iterator for DirIterator<'a> {

fn next(&mut self) -> Option<Self::Item> {
// First iterate through directories
if self.next_dir_offset != u32::MAX
if self.next_dir_offset != NO_ENTRY
&& let Ok(dir) =
RomFsDir::from_offset(self.romfs, self.next_dir_offset, self.dir_table_base)
{
Expand All @@ -521,7 +521,7 @@ impl<'a> Iterator for DirIterator<'a> {
}

// Then iterate through files
if self.next_file_offset != u32::MAX
if self.next_file_offset != NO_ENTRY
&& let Ok(file) =
RomFsFile::from_offset(self.romfs, self.next_file_offset, self.file_table_base)
{
Expand Down
32 changes: 11 additions & 21 deletions src/write/romfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

use std::{path::PathBuf, string::String, vec::Vec};

use crate::raw::romfs::{RomFsDirEntry, RomFsFileEntry};
use crate::raw::romfs::{NO_ENTRY, RomFsDirEntry, RomFsFileEntry, path_hash};

const ROMFS_FILEPARTITION_OFS: u64 = 0x200;
const ROMFS_ENTRY_EMPTY: u32 = 0xFFFFFFFF;

/// Internal directory entry for building RomFS.
struct DirEntry {
Expand Down Expand Up @@ -271,8 +270,8 @@ impl RomFsBuilder {
self.calculate_offsets();

// Initialize hash sibling tracking
self.dir_hash_siblings = vec![ROMFS_ENTRY_EMPTY; self.dirs.len()];
self.file_hash_siblings = vec![ROMFS_ENTRY_EMPTY; self.files.len()];
self.dir_hash_siblings = vec![NO_ENTRY; self.dirs.len()];
self.file_hash_siblings = vec![NO_ENTRY; self.files.len()];

// Generate hash tables
let dir_hash_table = self.generate_dir_hash_table();
Expand Down Expand Up @@ -413,11 +412,11 @@ impl RomFsBuilder {

fn generate_dir_hash_table(&mut self) -> Vec<u32> {
let table_size = romfs_get_hash_table_count(self.dirs.len());
let mut table = vec![ROMFS_ENTRY_EMPTY; table_size];
let mut table = vec![NO_ENTRY; table_size];

for (dir_idx, dir) in self.dirs.iter().enumerate() {
let parent_offset = self.dirs[dir.parent].entry_offset;
let hash = calc_path_hash(parent_offset, &dir.name);
let hash = path_hash(parent_offset, dir.name.as_bytes());
let bucket = (hash as usize) % table_size;

// Chain collision: new entry becomes head, points to old head
Expand All @@ -431,11 +430,11 @@ impl RomFsBuilder {

fn generate_file_hash_table(&mut self) -> Vec<u32> {
let table_size = romfs_get_hash_table_count(self.files.len());
let mut table = vec![ROMFS_ENTRY_EMPTY; table_size];
let mut table = vec![NO_ENTRY; table_size];

for (file_idx, file) in self.files.iter().enumerate() {
let parent_offset = self.dirs[file.parent].entry_offset;
let hash = calc_path_hash(parent_offset, &file.name);
let hash = path_hash(parent_offset, file.name.as_bytes());
let bucket = (hash as usize) % table_size;

// Chain collision: new entry becomes head, points to old head
Expand All @@ -457,12 +456,12 @@ impl RomFsBuilder {
.children
.first()
.map(|&idx| self.dirs[idx].entry_offset)
.unwrap_or(ROMFS_ENTRY_EMPTY);
.unwrap_or(NO_ENTRY);
let first_file = dir
.files
.first()
.map(|&idx| self.files[idx].entry_offset)
.unwrap_or(ROMFS_ENTRY_EMPTY);
.unwrap_or(NO_ENTRY);

let hash_sibling = self.dir_hash_siblings[dir_idx];

Expand Down Expand Up @@ -520,7 +519,7 @@ impl RomFsBuilder {
.windows(2)
.find(|window| self.dirs[window[0]].entry_offset == dir.entry_offset)
.map(|window| self.dirs[window[1]].entry_offset)
.unwrap_or(ROMFS_ENTRY_EMPTY)
.unwrap_or(NO_ENTRY)
}

fn find_sibling_file(&self, file: &FileEntry) -> u32 {
Expand All @@ -530,7 +529,7 @@ impl RomFsBuilder {
.windows(2)
.find(|window| self.files[window[0]].entry_offset == file.entry_offset)
.map(|window| self.files[window[1]].entry_offset)
.unwrap_or(ROMFS_ENTRY_EMPTY)
.unwrap_or(NO_ENTRY)
}

fn write_header(
Expand Down Expand Up @@ -665,15 +664,6 @@ fn romfs_get_hash_table_count(num_entries: usize) -> usize {
}
}

/// Calculate path hash for hash table lookup.
fn calc_path_hash(parent_offset: u32, name: &str) -> u32 {
let mut hash = parent_offset ^ 123_456_789;
for c in name.bytes() {
hash = hash.rotate_right(5) ^ u32::from(c);
}
hash
}

/// Align value to specified alignment.
fn align32(value: u32, alignment: u32) -> u32 {
let mask = alignment - 1;
Expand Down