Extracts param.sfo loader from pkg crate (#235)

This commit is contained in:
Putta Khunchalee 2023-06-26 02:33:29 +07:00 committed by GitHub
parent 9da8e5e279
commit 5faf88a3e0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 519 additions and 259 deletions

View File

@ -113,7 +113,7 @@ If all you want is to use the emulator, choose `[YOUR-PLATFORM]-release` for opt
cmake --build build
```
You can use `-j` to enable parallel building (e.g. `cmake --build build -j 2`). Each parallel build consumes a lot of memory so don't use the number of your CPU cores otherwise your system might crash due to out of memory.
You can use `-j` to enable parallel building (e.g. `cmake --build build -j 2`). Each parallel build on Linux consumes a lot of memory so don't use the number of your CPU cores otherwise your system might crash due to out of memory. On Windows it seems like it is safe to use the number of your CPU cores.
## Development
@ -164,6 +164,6 @@ We use icons from https://materialdesignicons.com for UI (e.g. on the menu and t
## License
- `src/ansi_escape.hpp`, `src/ansi_escape.cpp`, `src/log_formatter.hpp` and `src/log_formatter.cpp` are licensed under GPL-3.0 only.
- `src/pfs` and `src/pkg` are licensed under LGPL-3.0 license.
- `src/param`, `src/pfs` and `src/pkg` are licensed under LGPL-3.0 license.
- All other source code is licensed under MIT license.
- All release binaries are under GPL-3.0 license.

View File

@ -6,25 +6,19 @@ find_package(Qt6 COMPONENTS Widgets REQUIRED)
find_package(Threads REQUIRED)
# Setup LLVM target.
set(LLVM_OPTS -DCMAKE_INSTALL_PREFIX:STRING=<INSTALL_DIR>)
set(LLVM_OPTS -DCMAKE_INSTALL_PREFIX:STRING=<INSTALL_DIR> -DLLVM_ENABLE_ZSTD:BOOL=OFF -DLLVM_APPEND_VC_REV:BOOL=OFF)
if(WIN32)
if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "AMD64")
list(APPEND LLVM_OPTS -DLLVM_TARGETS_TO_BUILD:STRING=X86)
# turn off zstd due to potential shared libray issue
list(APPEND LLVM_OPTS -DLLVM_ENABLE_ZSTD:BOOL=OFF)
else()
message(FATAL_ERROR "Target CPU is not supported")
endif()
else()
if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
list(APPEND LLVM_OPTS -DLLVM_TARGETS_TO_BUILD:STRING=X86)
list(APPEND LLVM_OPTS -DLLVM_ENABLE_ZSTD:BOOL=OFF)
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm64")
list(APPEND LLVM_OPTS -DLLVM_TARGETS_TO_BUILD:STRING=AArch64)
list(APPEND LLVM_OPTS -DLLVM_ENABLE_ZSTD:BOOL=OFF)
else()
message(FATAL_ERROR "Target CPU is not supported")
endif()

View File

@ -7,6 +7,7 @@ members = [
"ftp",
"kernel",
"kernel-macros",
"param",
"pfs",
"pkg",
"system",
@ -14,3 +15,9 @@ members = [
]
default-members = ["core", "kernel"]
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"

View File

@ -8,5 +8,6 @@ crate-type = ["staticlib"]
[dependencies]
error = { path = "../error" }
param = { path = "../param" }
pkg = { path = "../pkg" }
system = { path = "../system" }

View File

@ -2,5 +2,6 @@
// to add other crates that expose API to the GUI as a dependency of this crate then re-export all
// of those APIs here.
pub use error::*;
pub use param::*;
pub use pkg::*;
pub use system::*;

View File

@ -3,12 +3,6 @@ name = "kernel"
version = "0.1.0"
edition = "2021"
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"
[[bin]]
name = "obkrnl"
path = "src/main.rs"

View File

@ -1,3 +1,6 @@
// This file contains error codes used in a PS4 system. The value of each error must be the same as the PS4.
pub const E2BIG: i32 = 7;
pub const ENOMEM: i32 = 12;
pub const EFAULT: i32 = 14;
pub const EINVAL: i32 = 22;
pub const ENAMETOOLONG: i32 = 63;

View File

@ -11,9 +11,13 @@ impl Syscalls {
#[cpu_abi]
pub fn exec(&self, i: &Input, o: &mut Output) -> i64 {
// Reset output.
o.rax = 0;
o.rdx = 0;
// Execute the handler. See
// https://github.com/freebsd/freebsd-src/blob/release/9.1.0/sys/kern/init_sysent.c#L36 for
// standard FreeBSD syscalls.
match i.id {
_ => panic!(
"Syscall {} is not implemented at {:#018x} on {}.",

View File

@ -43,9 +43,9 @@ MainWindow::MainWindow() :
restoreGeometry();
// Determine current theme.
QString svgPath;
if (QApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark) {
if (QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark) {
svgPath = ":/resources/darkmode/";
} else {
svgPath = ":/resources/lightmode/";
@ -224,7 +224,7 @@ void MainWindow::installPkg()
// Get game ID.
char *error;
auto param = pkg_get_param(pkg, &error);
Param param(pkg_get_param(pkg, &error));
if (!param) {
QMessageBox::critical(&progress, "Error", QString("Failed to get param.sfo from %1: %2").arg(pkgPath.c_str()).arg(error));
@ -232,27 +232,22 @@ void MainWindow::installPkg()
return;
}
auto gameId = fromMalloc(pkg_param_title_id(param));
auto gameTitle = fromMalloc(pkg_param_title(param));
pkg_param_close(param);
// Create game directory.
auto gamesDirectory = readGamesDirectorySetting();
if (!QDir(gamesDirectory).mkdir(gameId)) {
QString msg("Cannot create directory %1 inside %2.");
if (!QDir(gamesDirectory).mkdir(param.titleId())) {
QString msg(
"Cannot create directory %1 inside %2. "
"If you have a failed installation from a previous attempt, you will need to remove this directory before trying again.");
msg += " If you have a failed installation from a previous attempt, you will need to remove this directory before trying again.";
QMessageBox::critical(&progress, "Error", msg.arg(gameId).arg(gamesDirectory));
QMessageBox::critical(&progress, "Error", msg.arg(param.titleId()).arg(gamesDirectory));
return;
}
auto directory = joinPath(gamesDirectory, gameId);
auto directory = joinPath(gamesDirectory, param.titleId());
// Extract items.
progress.setWindowTitle(gameTitle);
progress.setWindowTitle(param.title());
newError = pkg_extract(pkg, directory.c_str(), [](const char *name, std::uint64_t total, std::uint64_t written, void *ud) {
auto toProgress = [total](std::uint64_t v) -> int {
@ -294,7 +289,7 @@ void MainWindow::installPkg()
}
// Add to game list.
auto success = loadGame(gameId);
auto success = loadGame(param.titleId());
if (success) {
QMessageBox::information(this, "Success", "Package installed successfully.");
@ -486,23 +481,16 @@ bool MainWindow::loadGame(const QString &gameId)
// Read game title from param.sfo.
auto paramDir = joinPath(gamePath.c_str(), "sce_sys");
auto paramPath = joinPath(paramDir.c_str(), "param.sfo");
pkg_param *param;
char *error;
param = pkg_param_open(paramPath.c_str(), &error);
Error error;
Param param(param_open(paramPath.c_str(), &error));
if (!param) {
QMessageBox::critical(this, "Error", QString("Cannot open %1: %2").arg(paramPath.c_str()).arg(error));
std::free(error);
QMessageBox::critical(this, "Error", QString("Cannot open %1: %2").arg(paramPath.c_str()).arg(error.message()));
return false;
}
auto name = fromMalloc(pkg_param_title(param));
pkg_param_close(param);
// Add to list.
gameList->add(new Game(name, gamePath.c_str()));
gameList->add(new Game(param.title(), gamePath.c_str()));
return true;
}

50
src/param.hpp Normal file
View File

@ -0,0 +1,50 @@
#pragma once
#include "error.hpp"
struct param;
extern "C" {
param *param_open(const char *file, error **error);
void param_close(param *param);
const char *param_title(const param *param);
const char *param_title_id(const param *param);
}
class Param final {
public:
Param() : m_obj(nullptr) {}
explicit Param(param *obj) : m_obj(obj) {}
Param(const Param &) = delete;
~Param() { close(); }
public:
Param &operator=(const Param &) = delete;
Param &operator=(param *obj)
{
if (m_obj) {
param_close(m_obj);
}
m_obj = obj;
return *this;
}
operator param *() const { return m_obj; }
public:
const char *title() const { return param_title(m_obj); }
const char *titleId() const { return param_title_id(m_obj); }
void close()
{
if (m_obj) {
param_close(m_obj);
m_obj = nullptr;
}
}
private:
param *m_obj;
};

165
src/param/COPYING Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

9
src/param/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "param"
version = "0.1.0"
edition = "2021"
[dependencies]
byteorder = "1.4"
error = { path = "../error" }
thiserror = "1.0"

256
src/param/src/lib.rs Normal file
View File

@ -0,0 +1,256 @@
use byteorder::{ByteOrder, BE, LE};
use error::Error;
use std::ffi::{c_char, CStr};
use std::fs::File;
use std::io::{ErrorKind, Read, Seek, SeekFrom};
use std::ptr::null_mut;
use thiserror::Error;
#[no_mangle]
pub unsafe extern "C" fn param_open(file: *const c_char, error: *mut *mut Error) -> *mut Param {
// Open file.
let file = match File::open(CStr::from_ptr(file).to_str().unwrap()) {
Ok(v) => v,
Err(e) => {
*error = Error::new(&e);
return null_mut();
}
};
// Parse.
let param = match Param::read(file) {
Ok(v) => Box::new(v),
Err(e) => {
*error = Error::new(&e);
return null_mut();
}
};
Box::into_raw(param)
}
#[no_mangle]
pub unsafe extern "C" fn param_close(param: *mut Param) {
drop(Box::from_raw(param));
}
#[no_mangle]
pub unsafe extern "C" fn param_title(param: &Param) -> *const c_char {
param.title.as_ptr() as _
}
#[no_mangle]
pub unsafe extern "C" fn param_title_id(param: &Param) -> *const c_char {
param.title_id.as_ptr() as _
}
/// A loaded param.sfo.
///
/// See https://www.psdevwiki.com/ps4/Param.sfo#Internal_Structure for more information.
pub struct Param {
title: Vec<u8>,
title_id: Vec<u8>,
}
impl Param {
pub fn read<R: Read + Seek>(mut raw: R) -> Result<Self, ReadError> {
// Seek to the beginning.
if let Err(e) = raw.seek(SeekFrom::Start(0)) {
return Err(ReadError::SeekFailed(0, e));
}
// Read the header.
let mut hdr = [0u8; 0x14];
if let Err(e) = raw.read_exact(&mut hdr) {
return Err(ReadError::ReadHeaderFailed(e));
}
// Check magic.
let magic = BE::read_u32(&hdr[0x00..]);
if magic != 0x00505346 {
return Err(ReadError::InvalidMagic);
}
// Load the header.
let key_table = LE::read_u32(&hdr[0x08..]) as u64;
let data_table = LE::read_u32(&hdr[0x0C..]) as u64;
let entries = LE::read_u32(&hdr[0x10..]) as u64;
// Seek to key table.
match raw.seek(SeekFrom::Start(key_table)) {
Ok(v) => {
if v != key_table {
return Err(ReadError::InvalidHeader);
}
}
Err(e) => return Err(ReadError::SeekFailed(key_table, e)),
}
// Read key table.
let mut keys = vec![0u8; 0xFFFF];
let mut i = 0;
while i != keys.len() {
let r = match raw.read(&mut keys[i..]) {
Ok(v) => v,
Err(e) => {
if e.kind() == ErrorKind::Interrupted {
continue;
}
return Err(ReadError::ReadKeyTableFailed(e));
}
};
if r == 0 {
break;
}
i += r;
}
keys.drain(i..);
// Read entries.
let mut title: Option<Vec<u8>> = None;
let mut title_id: Option<Vec<u8>> = None;
for i in 0..entries {
// Seek to the entry.
let offset = 0x14 + i * 0x10;
match raw.seek(SeekFrom::Start(offset)) {
Ok(v) => {
if v != offset {
return Err(ReadError::InvalidHeader);
}
}
Err(e) => return Err(ReadError::SeekFailed(offset, e)),
}
// Read the entry.
let mut hdr = [0u8; 0x10];
if let Err(e) = raw.read_exact(&mut hdr) {
return Err(ReadError::ReadEntryFailed(i.try_into().unwrap(), e));
}
let key_offset = LE::read_u16(&hdr[0x00..]) as usize;
let format = BE::read_u16(&hdr[0x02..]);
let len = LE::read_u32(&hdr[0x04..]) as usize;
let data_offset = data_table + LE::read_u32(&hdr[0x0C..]) as u64;
if len == 0 {
return Err(ReadError::InvalidEntry(i.try_into().unwrap()));
}
// Get key name.
let key = match keys.get(key_offset..) {
Some(v) => {
if let Some(i) = v.iter().position(|&b| b == 0) {
&v[..i]
} else {
return Err(ReadError::InvalidEntry(i.try_into().unwrap()));
}
}
None => return Err(ReadError::InvalidEntry(i.try_into().unwrap())),
};
// Seek to the value.
match raw.seek(SeekFrom::Start(data_offset)) {
Ok(v) => {
if v != data_offset {
return Err(ReadError::InvalidEntry(i.try_into().unwrap()));
}
}
Err(e) => return Err(ReadError::SeekFailed(data_offset, e)),
}
// Parse value.
match key {
b"TITLE" => title = Some(Self::read_utf8(&mut raw, i, format, len, 128)?),
b"TITLE_ID" => title_id = Some(Self::read_utf8(&mut raw, i, format, len, 12)?),
_ => continue,
}
}
Ok(Self {
title: title.ok_or(ReadError::MissingTitle)?,
title_id: title_id.ok_or(ReadError::MissingTitleId)?,
})
}
pub fn title(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.title[..(self.title.len() - 1)]) }
}
pub fn title_id(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.title_id[..(self.title_id.len() - 1)]) }
}
fn read_utf8<R: Read>(
raw: &mut R,
i: u64,
format: u16,
len: usize,
max: usize,
) -> Result<Vec<u8>, ReadError> {
// Check format and length.
if format != 0x0402 || len > max {
return Err(ReadError::InvalidEntry(i.try_into().unwrap()));
}
// Read the value.
let mut data = vec![0u8; len];
if let Err(e) = raw.read_exact(&mut data) {
return Err(ReadError::ReadValueFailed(i.try_into().unwrap(), e));
}
// Check the value.
if *data.last().unwrap() != 0 || std::str::from_utf8(&data).is_err() {
return Err(ReadError::InvalidValue(i.try_into().unwrap()));
}
Ok(data)
}
}
/// Errors for reading param.sfo.
#[derive(Debug, Error)]
pub enum ReadError {
#[error("cannot seek to {0:#018x}")]
SeekFailed(u64, #[source] std::io::Error),
#[error("cannot read the header")]
ReadHeaderFailed(#[source] std::io::Error),
#[error("invalid magic")]
InvalidMagic,
#[error("invalid header")]
InvalidHeader,
#[error("cannot read key table")]
ReadKeyTableFailed(#[source] std::io::Error),
#[error("cannot read entry #{0}")]
ReadEntryFailed(usize, #[source] std::io::Error),
#[error("entry #{0} is not valid")]
InvalidEntry(usize),
#[error("cannot read the value of entry #{0}")]
ReadValueFailed(usize, #[source] std::io::Error),
#[error("entry #{0} has invalid value")]
InvalidValue(usize),
#[error("TITLE is not found")]
MissingTitle,
#[error("TITLE_ID is not found")]
MissingTitleId,
}

View File

@ -1,12 +1,12 @@
#pragma once
#include "error.hpp"
#include "param.hpp"
#include <cinttypes>
#include <cstddef>
struct pkg;
struct pkg_param;
typedef void (*pkg_extract_status_t) (const char *name, std::uint64_t total, std::uint64_t written, void *ud);
@ -14,13 +14,8 @@ extern "C" {
pkg *pkg_open(const char *file, error **error);
void pkg_close(pkg *pkg);
pkg_param *pkg_get_param(const pkg *pkg, char **error);
param *pkg_get_param(const pkg *pkg, char **error);
error *pkg_extract(const pkg *pkg, const char *dir, pkg_extract_status_t status, void *ud);
pkg_param *pkg_param_open(const char *file, char **error);
char *pkg_param_title_id(const pkg_param *param);
char *pkg_param_title(const pkg_param *param);
void pkg_param_close(pkg_param *param);
}
class Pkg final {

View File

@ -10,6 +10,7 @@ cbc = "0.1"
error = { path = "../error" }
fs = { path = "../fs" }
memmap2 = "0.7"
param = { path = "../param" }
pfs = { path = "../pfs" }
rsa = "0.9"
sha2 = "0.10"

View File

@ -1,9 +1,9 @@
use self::entry::Entry;
use self::header::Header;
use self::keys::{fake_pfs_key, pkg_key3};
use self::param::Param;
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{BlockDecryptMut, KeyIvInit};
use param::Param;
use sha2::Digest;
use std::error::Error;
use std::ffi::{c_void, CString};
@ -18,7 +18,6 @@ use thiserror::Error;
pub mod entry;
pub mod header;
pub mod keys;
pub mod param;
#[no_mangle]
pub unsafe extern "C" fn pkg_open(file: *const c_char, error: *mut *mut error::Error) -> *mut Pkg {
@ -67,68 +66,6 @@ pub unsafe extern "C" fn pkg_extract(
}
}
#[no_mangle]
pub unsafe extern "C" fn pkg_param_open(
file: *const c_char,
error: *mut *mut c_char,
) -> *mut Param {
// Open file.
let mut file = match File::open(unsafe { util::str::from_c_unchecked(file) }) {
Ok(v) => v,
Err(e) => {
unsafe { util::str::set_c(error, &e.to_string()) };
return null_mut();
}
};
// param.sfo is quite small so we can read all of it content into memory.
let mut data: Vec<u8> = Vec::new();
match file.metadata() {
Ok(v) => {
if v.len() <= 4096 {
if let Err(e) = file.read_to_end(&mut data) {
unsafe { util::str::set_c(error, &e.to_string()) };
return null_mut();
}
} else {
unsafe { util::str::set_c(error, "file too large") };
return null_mut();
}
}
Err(e) => {
unsafe { util::str::set_c(error, &e.to_string()) };
return null_mut();
}
};
// Parse.
let param = match Param::read(&data) {
Ok(v) => Box::new(v),
Err(e) => {
unsafe { util::str::set_c(error, &e.to_string()) };
return null_mut();
}
};
Box::into_raw(param)
}
#[no_mangle]
pub unsafe extern "C" fn pkg_param_title_id(param: &Param) -> *mut c_char {
unsafe { util::str::to_c(param.title_id()) }
}
#[no_mangle]
pub unsafe extern "C" fn pkg_param_title(param: &Param) -> *mut c_char {
unsafe { util::str::to_c(param.title()) }
}
#[no_mangle]
pub unsafe extern "C" fn pkg_param_close(param: *mut Param) {
unsafe { Box::from_raw(param) };
}
// https://www.psdevwiki.com/ps4/Package_Files
pub struct Pkg {
raw: memmap2::Mmap,
@ -178,7 +115,7 @@ impl Pkg {
};
// Parse data.
let param = match Param::read(data) {
let param = match Param::read(Cursor::new(data)) {
Ok(v) => v,
Err(e) => return Err(GetParamError::ReadFailed(e)),
};

View File

@ -1,145 +0,0 @@
use byteorder::{ByteOrder, BE, LE};
use std::error::Error;
use std::fmt::{Display, Formatter};
macro_rules! utf8 {
($num:ident, $value:ident, $format:ident) => {{
if $format != 0x0402 {
return Err(ReadError::InvalidValueFormat($num));
} else if let Ok(v) = std::str::from_utf8(&$value[..($value.len() - 1)]) {
v.into()
} else {
return Err(ReadError::InvalidValue($num));
}
}};
}
// https://www.psdevwiki.com/ps4/Param.sfo#Internal_Structure
pub struct Param {
title: String,
title_id: String,
}
impl Param {
pub fn read(raw: &[u8]) -> Result<Self, ReadError> {
// Check minimum size.
if raw.len() < 20 {
return Err(ReadError::TooSmall);
}
// Check magic.
let magic = BE::read_u32(&raw[0x00..]);
if magic != 0x00505346 {
return Err(ReadError::InvalidMagic);
}
// Read header.
let key_table = LE::read_u32(&raw[0x08..]) as usize;
let data_table = LE::read_u32(&raw[0x0C..]) as usize;
let entries = LE::read_u32(&raw[0x10..]) as usize;
// Read entries.
let mut title: Option<String> = None;
let mut title_id: Option<String> = None;
for i in 0..entries {
// Entry header.
let offset = 20 + i * 16;
let entry = match raw.get(offset..(offset + 16)) {
Some(v) => v,
None => return Err(ReadError::TooSmall),
};
let key_offset = key_table + LE::read_u16(&entry[0x00..]) as usize;
let format = BE::read_u16(&entry[0x02..]);
let len = LE::read_u32(&entry[0x04..]) as usize;
let data_offset = data_table + LE::read_u32(&entry[0x0C..]) as usize;
if len == 0 {
return Err(ReadError::InvalidEntryHeader(i));
}
// Get key name.
let key = match raw.get(key_offset..) {
Some(v) => {
if let Some(i) = v.iter().position(|&b| b == 0) {
&v[..i]
} else {
return Err(ReadError::InvalidKeyOffset(i));
}
}
None => return Err(ReadError::InvalidKeyOffset(i)),
};
// Get value.
let value = match raw.get(data_offset..(data_offset + len)) {
Some(v) => v,
None => return Err(ReadError::InvalidValueOffset(i)),
};
// Parse value.
match key {
b"TITLE" => title = Some(utf8!(i, value, format)),
b"TITLE_ID" => title_id = Some(utf8!(i, value, format)),
_ => continue,
}
}
// Check required values.
let title = match title {
Some(v) => v,
None => return Err(ReadError::MissingTitle),
};
let title_id = match title_id {
Some(v) => v,
None => todo!(),
};
Ok(Self { title, title_id })
}
pub fn title_id(&self) -> &str {
self.title_id.as_ref()
}
pub fn title(&self) -> &str {
self.title.as_ref()
}
}
#[derive(Debug)]
pub enum ReadError {
TooSmall,
InvalidMagic,
InvalidEntryHeader(usize),
InvalidKeyOffset(usize),
InvalidValueOffset(usize),
InvalidValueFormat(usize),
InvalidValue(usize),
MissingAttribute,
MissingSystemVer,
MissingTitle,
MissingTitleId,
}
impl Error for ReadError {}
impl Display for ReadError {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
Self::TooSmall => f.write_str("data too small"),
Self::InvalidMagic => f.write_str("invalid magic"),
Self::InvalidEntryHeader(i) => write!(f, "entry #{} has invalid header", i),
Self::InvalidKeyOffset(i) => write!(f, "invalid key offset for entry #{}", i),
Self::InvalidValueOffset(i) => write!(f, "invalid value offset for entry #{}", i),
Self::InvalidValueFormat(i) => write!(f, "entry #{} has invalid value format", i),
Self::InvalidValue(i) => write!(f, "entry #{} has invalid value", i),
Self::MissingAttribute => f.write_str("ATTRIBUTE is not found"),
Self::MissingSystemVer => f.write_str("SYSTEM_VER is not found"),
Self::MissingTitle => f.write_str("TITLE is not found"),
Self::MissingTitleId => f.write_str("TITLE_ID is not found"),
}
}
}