init. Начало процесса выноса всего что касается фс в библиотеку

This commit is contained in:
Roman Serov 2025-06-13 00:40:49 +03:00
commit b4b4bfd82a
27 changed files with 3026 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
build/
.vscode/

90
CMakeLists.txt Normal file
View file

@ -0,0 +1,90 @@
cmake_minimum_required(VERSION 3.5)
project(ffshit VERSION 0.0.1 DESCRIPTION "Siemens filesystem library" LANGUAGES CXX)
option(BUILD_SHARED_LIBS "Build using shared library" ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(fmt REQUIRED)
find_package(Iconv REQUIRED)
find_package(spdlog REQUIRED)
include_directories(
${PROJECT_SOURCE_DIR}/inc
${Iconv_INCLUDE_DIRS}
)
set(SOURCES_LIST
src/system.cpp
src/rawdata.cpp
src/blocks.cpp
src/filesystem/extract.cpp
src/filesystem/file.cpp
src/filesystem/directory.cpp
src/filesystem/sgold.cpp
src/filesystem/newsgold.cpp
src/filesystem/newsgold_x85.cpp)
set(PUBLIC_HEADERS_LIST
inc/ffshit/rawdata.h
inc/ffshit/help.h
inc/ffshit/filesystem/file.h
inc/ffshit/filesystem/directory.h
inc/ffshit/filesystem/base.h
inc/ffshit/filesystem/newsgold.h
inc/ffshit/filesystem/sgold.h
inc/ffshit/filesystem/newsgold_x85.h
inc/ffshit/filesystem/extract.h
inc/ffshit/filesystem/ex.h
inc/ffshit/blocks.h
inc/ffshit/ex.h
inc/ffshit/system.h
)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
endif()
set(CMAKE_CXX_FLAGS_DEBUG "-g")
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
add_library(${PROJECT_NAME} ${SOURCES_LIST} ${PUBLIC_HEADERS_LIST})
set_target_properties(${PROJECT_NAME} PROPERTIES FRAMEWORK TRUE)
set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION})
set_target_properties(${PROJECT_NAME} PROPERTIES SOVERSION ${PROJECT_VERSION_MAJOR})
target_include_directories(${PROJECT_NAME} PRIVATE inc)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
install(TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(DIRECTORY ${PROJECT_SOURCE_DIR}/inc/
DESTINATION include)
install(EXPORT ${PROJECT_NAME}Targets
FILE ${PROJECT_NAME}Targets.cmake
DESTINATION lib/cmake/${PROJECT_NAME})
configure_package_config_file(
${CMAKE_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in
${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake
INSTALL_DESTINATION lib/cmake/${PROJECT_NAME})
install(FILES ${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake
DESTINATION lib/cmake/${PROJECT_NAME})
write_basic_package_version_file(
${CMAKE_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
VERSION ${PROJECT_VERSION}
COMPATIBILITY AnyNewerVersion)
install(
FILES ${CMAKE_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
DESTINATION lib/cmake/${PROJECT_NAME})

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Siemens Mobile Hackers, Roman Serov <roman@serov.co>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

11
README.md Normal file
View file

@ -0,0 +1,11 @@
# Siemens filesystem library
#### Щито это
Библиотека для работы с файловой системой в FULLFLASH. Поддерживается только чтение, записи в обозримых планах нет.
##### Поддерживаемые платформы:
- X65
- X75
##### В разработке/планах на 2035:
- X85
- X55

3
ffshitConfig.cmake.in Normal file
View file

@ -0,0 +1,3 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/ffshitTargets.cmake")

92
inc/ffshit/blocks.h Normal file
View file

@ -0,0 +1,92 @@
#ifndef BLOCKS_H
#define BLOCKS_H
#define FMT_HEADER_ONLY
#include <fmt/format.h>
#include <fmt/printf.h>
#include <cstdint>
#include <memory>
#include <vector>
#include <map>
#include <unordered_map>
#include "rawdata.h"
namespace FULLFLASH {
enum class Platform {
UNK,
X65,
X75,
X85
};
const std::unordered_map<Platform, std::string> PlatformToString = {
{ Platform::X65, "X65" },
{ Platform::X75, "X75" },
{ Platform::X85, "X85" },
};
const std::unordered_map<std::string, Platform> StringToPlatform = {
{ "X65", Platform::X65 },
{ "X75", Platform::X75 },
{ "X85", Platform::X85 },
};
class Blocks {
public:
typedef struct {
char name[8];
uint16_t unknown_1;
uint16_t unknown_2;
uint32_t unknown_3;
} BlockHeader;
typedef struct {
BlockHeader header;
size_t offset;
size_t count;
RawData data;
std::string name;
} Block;
using Map = std::map<std::string, std::vector<Block>>;
using Ptr = std::unique_ptr<Blocks>;
template<typename ...Args>
static Ptr build(Args ...args) {
return std::make_unique<Blocks>(args...);
}
Blocks(std::string fullflash_path);
Blocks(std::string fullflash_path, Platform platform);
const Platform get_platform() const;
const std::string & get_imei() const;
const std::string & get_model() const;
Map & get_blocks();
RawData & get_data();
void print();
uint32_t block_size;
// static const uint32_t block_size = 0x10000;
private:
void detect_platform();
void search_blocks();
void search_blocks_x85();
RawData data;
Map blocks_map;
Platform platform;
std::string imei;
std::string model;
};
};
#endif

31
inc/ffshit/ex.h Normal file
View file

@ -0,0 +1,31 @@
#ifndef FULLFLASH_EXCEPTION_H
#define FULLFLASH_EXCEPTION_H
#include <string>
#include <fmt/format.h>
namespace FULLFLASH {
class Exception {
public:
template<typename Format, typename ...Args>
Exception(Format format, const Args& ...args) {
this->msg = fmt::format(format, args...);
}
const std::string &what() const {
return msg;
}
const char *what_c() const {
return msg.c_str();
}
private:
std::string msg;
};
};
#endif

View file

@ -0,0 +1,24 @@
#ifndef FULLFLASH_FILESYSTEM_BASE_H
#define FULLFLASH_FILESYSTEM_BASE_H
#include <memory>
namespace FULLFLASH {
namespace Filesystem {
class Base {
public:
using Ptr = std::shared_ptr<Base>;
Base() { }
virtual void load() = 0;
virtual void extract(std::string path, bool overwrite) = 0;
private:
};
};
};
#endif

View file

@ -0,0 +1,38 @@
#ifndef FULLFLASH_FILESYSTEM_DIRECTORY_H
#define FULLFLASH_FILESYSTEM_DIRECTORY_H
#include <memory>
#include <string>
#include <vector>
#include "ffshit/rawdata.h"
#include "ffshit/filesystem/file.h"
namespace FULLFLASH {
namespace Filesystem {
class Directory {
public:
using Ptr = std::shared_ptr<Directory>;
using Directories = std::vector<Ptr>;
Directory(std::string name);
static Ptr build(std::string name);
void add_subdir(Ptr dir);
void add_file(File::Ptr file);
const std::string get_name() const;
const Directories & get_subdirs() const;
const File::Files & get_files() const;
private:
std::string name;
Directories subdirs;
File::Files files;
};
};
};
#endif

View file

@ -0,0 +1,32 @@
#ifndef FULLFLASH_FILESYSTEM_EXCEPTION_H
#define FULLFLASH_FILESYSTEM_EXCEPTION_H
#include <fmt/format.h>
#include <string>
namespace FULLFLASH {
namespace Filesystem {
class Exception {
public:
template<typename Format, typename ...Args>
Exception(Format format, const Args& ...args) {
this->msg = fmt::format(format, args...);
}
const std::string &what() const {
return msg;
}
const char *what_c() const {
return msg.c_str();
}
private:
std::string msg;
};
};
};
#endif

View file

@ -0,0 +1,15 @@
#ifndef FULLFLASH_FILESYSTEM_EXTRACT_H
#define FULLFLASH_FILESYSTEM_EXTRACT_H
#include <string>
#include <functional>
namespace FULLFLASH {
namespace Filesystem {
void extract(const std::string &path, bool overwrite, std::function<void(std::string)> extractor);
};
};
#endif

View file

@ -0,0 +1,34 @@
#ifndef FULLFLASH_FILESYSTEM_FILE_H
#define FULLFLASH_FILESYSTEM_FILE_H
#include <memory>
#include <string>
#include <vector>
#include "ffshit/rawdata.h"
namespace FULLFLASH {
namespace Filesystem {
class File {
public:
using Ptr = std::shared_ptr<File>;
using Files = std::vector<Ptr>;
File(const std::string name, const RawData &data);
static Ptr build(const std::string name, const RawData &data);
const std::string get_name() const;
RawData get_data() const;
const size_t get_size() const;
private:
std::string name;
RawData data;
};
};
};
#endif

View file

@ -0,0 +1,83 @@
#ifndef FULLFLASH_FILESYSTEM_NEWSGOLD_H
#define FULLFLASH_FILESYSTEM_NEWSGOLD_H
#include "ffshit/blocks.h"
#include "ffshit/filesystem/base.h"
#include "ffshit/filesystem/file.h"
#include "ffshit/filesystem/directory.h"
namespace FULLFLASH {
namespace Filesystem {
class NewSGOLD : public Base {
public:
NewSGOLD(Blocks &blocks);
static Base::Ptr build(Blocks &blocks) {
return std::make_shared<NewSGOLD>(blocks);
}
void load() override final;
void extract(std::string path, bool overwrite) override final;
private:
typedef struct {
uint32_t flags;
uint32_t id;
uint32_t size;
uint32_t offset;
} FITHeader;
typedef struct {
FITHeader header;
RawData data;
} FFSBlock;
typedef struct {
uint32_t id;
uint32_t unknown1;
uint32_t next_part;
uint32_t parent_id;
uint16_t unknown2;
uint16_t unknown3;
uint16_t unknown4;
uint16_t unknown5;
uint16_t unknown6;
uint16_t unknown7;
std::string name;
} FileHeader;
typedef struct {
uint32_t id;
uint32_t parent_id;
uint32_t next_part;
} FilePart;
using FSBlocksMap = std::map<uint16_t, FFSBlock>;
using FSMap = std::map<std::string, Directory::Ptr>;
Blocks & blocks;
FSMap fs_map;
static void print_fit_header(const NewSGOLD::FITHeader &header);
void parse_FIT();
static void print_file_header(const FileHeader &header);
static void print_file_part(const FilePart &part);
static FileHeader read_file_header(const RawData &data);
static FilePart read_file_part(const RawData &data);
void read_recurse(FSBlocksMap &ffs_map, RawData &data, uint16_t next_id);
RawData read_full_data(FSBlocksMap &ffs_map, const FileHeader &header);
void scan(const std::string &block_name, FSBlocksMap &ffs_map, Directory::Ptr dir, const FileHeader &header, std::string path = "/");
void unpack(Directory::Ptr dir, std::string path = "/");
};
};
};
#endif

View file

@ -0,0 +1,112 @@
#ifndef FULLFLASH_FILESYSTEM_NEWSGOLD_X85_H
#define FULLFLASH_FILESYSTEM_NEWSGOLD_X85_H
#include "ffshit/blocks.h"
#include "ffshit/filesystem/base.h"
#include "ffshit/filesystem/file.h"
#include "ffshit/filesystem/directory.h"
namespace FULLFLASH {
namespace Filesystem {
class NewSGOLD_X85 : public Base {
public:
NewSGOLD_X85(Blocks &blocks);
static Base::Ptr build(Blocks &blocks) {
return std::make_shared<NewSGOLD_X85>(blocks);
}
void load() override final;
void extract(std::string path, bool overwrite) override final;
private:
typedef struct {
uint32_t flags;
uint32_t id;
uint32_t size;
uint32_t offset;
uint32_t unk1;
uint32_t unk2;
uint32_t unk3;
uint32_t unk4;
} FITHeader;
typedef struct {
FITHeader header;
RawData data;
RawData data_header;
RawData data_from_header;
const Blocks::Block * block_ptr;
uint32_t ff_boffset;
uint32_t ff_offset;
uint16_t fit_size;
} FFSBlock;
typedef struct {
uint32_t id;
uint32_t unknown1;
uint32_t next_part;
uint32_t parent_id;
uint32_t unknown2;
uint16_t unknown4;
uint16_t unknown5;
uint16_t unknown6;
uint16_t unknown7;
std::string name;
} FileHeader;
typedef struct {
uint16_t id;
uint16_t unknown1;
uint16_t unknown2;
uint16_t unknown3;
} DirHeader;
using DirList = std::vector<DirHeader>;
typedef struct {
uint32_t id;
uint32_t parent_id;
uint32_t next_part;
} FilePart;
using FSBlocksMap = std::map<uint16_t, FFSBlock>;
using FSBlocksMapList = std::map<uint16_t, std::vector<FFSBlock>>;
using FSMap = std::map<std::string, Directory::Ptr>;
Blocks & blocks;
FSMap fs_map;
static void dump_data(const RawData &raw_data);
static void dump_block(const NewSGOLD_X85::FFSBlock &block, bool is_dump_data = true);
static void print_dir_header(const DirHeader &header);
static void print_file_header(const FileHeader &header);
static void print_file_part(const FilePart &part);
static RawData read_aligned(const FFSBlock &block);
static RawData read_aligned(char *data, size_t size);
static FileHeader read_file_header(const FFSBlock &block);
// static FileHeader read_file_header2(const FFSBlock &block);
static FilePart read_file_part(const FFSBlock &block);
uint32_t read_part(const FFSBlock &prev_part, const FileHeader &file_header, const FSBlocksMap &ffs_map_C0, const FSBlocksMapList &ffs_map_00, uint32_t next_part, uint32_t last_offset, RawData &data, size_t start_offset);
void read_file(const FSBlocksMap &ffs_map_C0, const FSBlocksMapList &ffs_map_00, const FFSBlock &file_block, RawData &data);
static void print_fit_header(const NewSGOLD_X85::FITHeader &header);
void parse_FIT();
DirList get_directory(FSBlocksMap &ffs_map_C0, FSBlocksMapList &ffs_map_00, const FFSBlock &block);
void scan(FSBlocksMap &ffs_map_C0, FSBlocksMapList &ffs_map_00, Directory::Ptr dir, const FFSBlock &block, std::string path = "/");
void unpack(Directory::Ptr dir, std::string path = "/");
};
};
};
#endif

View file

@ -0,0 +1,83 @@
#ifndef FULLFLASH_FILESYSTEM_SGOLD_H
#define FULLFLASH_FILESYSTEM_SGOLD_H
#include "ffshit/blocks.h"
#include "ffshit/rawdata.h"
#include "ffshit/filesystem/base.h"
#include "ffshit/filesystem/file.h"
#include "ffshit/filesystem/directory.h"
namespace FULLFLASH {
namespace Filesystem {
class SGOLD : public Base {
public:
SGOLD(Blocks &blocks);
static Base::Ptr build(Blocks &blocks) {
return std::make_shared<SGOLD>(blocks);
}
void load() override final;
void extract(std::string path, bool overwrite) override final;
private:
typedef struct {
uint32_t flags;
uint32_t id;
uint32_t size;
uint32_t offset;
} FITHeader;
typedef struct {
FITHeader header;
RawData data;
} FFSBlock;
typedef struct {
uint16_t id;
uint16_t parent_id;
uint32_t unknown;
uint16_t data_id;
uint32_t attributes;
uint16_t next_part;
std::string name;
} FileHeader;
typedef struct {
uint16_t id;
uint16_t parent_id;
uint32_t unknown;
uint16_t data_id;
uint16_t unknown2;
uint16_t prev_id;
uint16_t next_part;
} FilePart;
using FSBlocksMap = std::map<uint16_t, FFSBlock>;
using FSMap = std::map<std::string, Directory::Ptr>;
Blocks & blocks;
FSMap fs_map;
void parse_FIT();
void scan(const std::string &block_name, FSBlocksMap &ffs_map, Directory::Ptr dir, const FileHeader &header, std::string path = "/");
void read_recurse(FSBlocksMap &ffs_map, RawData &data, uint16_t next_id);
RawData read_full_data(FSBlocksMap &ffs_map, const FileHeader &header);
static void print_fit_header(const SGOLD::FITHeader &header);
static void print_file_header(const SGOLD::FileHeader &header);
static void print_file_part(const SGOLD::FilePart &part);
static SGOLD::FileHeader read_file_header(const RawData &data);
static SGOLD::FilePart read_file_part(const RawData &data);
void unpack(Directory::Ptr dir, std::string path = "/");
};
};
};
#endif

13
inc/ffshit/help.h Normal file
View file

@ -0,0 +1,13 @@
#ifndef HELP_H
#define HELP_H
#include <cstring>
template<typename T>
static char *read_data(char *dst, char *src, size_t size) {
memcpy(dst, src, sizeof(T) * size);
return src + sizeof(T) * size;
}
#endif

51
inc/ffshit/rawdata.h Normal file
View file

@ -0,0 +1,51 @@
#ifndef FULLFLASH_FILESYSTEM_DATA_H
#define FULLFLASH_FILESYSTEM_DATA_H
#include <cstddef>
#include <memory>
#include <fstream>
namespace FULLFLASH {
class RawData {
public:
using Data = std::shared_ptr<char[]>;
RawData();
RawData(const RawData &prev);
RawData(const RawData &prev, size_t offset, size_t size);
RawData(std::ifstream &file, size_t offset, size_t size);
RawData(char *data, size_t size);
void reverse(size_t align_size);
void add(char *data, size_t size);
void add(const RawData &data);
void add_top(char *data, size_t size);
void write(size_t offset, char *data, size_t size);
void read(size_t offset, char *data, size_t size) const;
void read_string(size_t offset, std::string &str, size_t step = 1) const;
void read_wstring(size_t offset, std::wstring &str) const;
template<typename T>
void read(size_t &offset, char *dst, size_t count) const {
read(offset, dst, count * sizeof(T));
offset += count * sizeof(T);
}
Data get_data() const;
const size_t get_size() const;
private:
size_t size;
Data data;
};
};
#endif

19
inc/ffshit/system.h Normal file
View file

@ -0,0 +1,19 @@
#ifndef FF_SYSTEM_H
#define FF_SYSTEM_H
#include <string>
#include <filesystem>
namespace System {
bool is_file_exists(const std::string &path);
bool is_directory_exists(const std::string &path);
bool remove_directory(const std::filesystem::path path);
bool create_directory(const std::string &path, std::filesystem::perms perms);
void to_lower(std::string &str);
void to_upper(std::string &str);
};
#endif

335
src/blocks.cpp Normal file
View file

@ -0,0 +1,335 @@
#include "ffshit/blocks.h"
#include "ffshit/help.h"
#include "ffshit/ex.h"
#include <cctype>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <spdlog/spdlog.h>
namespace FULLFLASH {
static constexpr size_t BC65_BC75_OFFSET = 0x870;
static constexpr size_t BC85_OFFSET = 0xC70;
static constexpr size_t X65_MODEL_OFFSET = 0x210;
static constexpr size_t X75_MODEL_OFFSET = 0x210;
static constexpr size_t X85_MODEL_OFFSET = 0x3E000;
static constexpr size_t X65_IMEI_OFFSET = 0x65C;
static constexpr size_t X65_7X_IMEI_OFFSET = 0x660;
static constexpr size_t X75_IMEI_OFFSET = 0x660;
static constexpr size_t X85_IMEI_OFFSET = 0x3E410;
Blocks::Blocks(std::string fullflash_path) {
std::ifstream file;
file.open(fullflash_path, std::ios_base::binary | std::ios_base::in);
if (!file.is_open()) {
throw Exception("Couldn't open file '{}': {}\n", fullflash_path, std::string(strerror(errno)));
}
file.seekg(0, std::ios_base::end);
size_t data_size = file.tellg();
file.seekg(0, std::ios_base::beg);
this->data = RawData(file, 0, data_size);
detect_platform();
switch (platform) {
case Platform::X65:
case Platform::X75: block_size = 0x10000; search_blocks(); break;
case Platform::X85: block_size = 0x10000; search_blocks_x85(); break;
default: throw Exception("Couldn't detect fullflash platform");
}
}
Blocks::Blocks(std::string fullflash_path, Platform platform) {
std::ifstream file;
file.open(fullflash_path, std::ios_base::binary | std::ios_base::in);
if (!file.is_open()) {
throw Exception("Couldn't open file '{}': {}\n", fullflash_path, std::string(strerror(errno)));
}
file.seekg(0, std::ios_base::end);
size_t data_size = file.tellg();
file.seekg(0, std::ios_base::beg);
this->data = RawData(file, 0, data_size);
this->platform = platform;
switch (platform) {
case Platform::X65:
case Platform::X75: block_size = 0x10000; search_blocks(); break;
case Platform::X85: block_size = 0x10000; search_blocks_x85(); break;
default: throw Exception("Couldn't detect fullflash platform");
}
}
static size_t search_end(const char *buf, size_t size) {
for (size_t i = 0; i < size; ++i) {
unsigned char data = buf[i];
if (data == 0x0) {
return i;
}
}
return size;
}
static bool is_printable(const char *buf, size_t size) {
for (size_t i = 0; i < size; ++i) {
if (isprint(static_cast<unsigned char>(buf[i]))) {
continue;;
}
return false;
}
return true;
}
static bool is_empty(const char *buf, size_t size) {
for (size_t i = 0; i < size; ++i) {
if (static_cast<const uint8_t>(buf[i]) != 0xFF) {
return false;
}
}
return true;
}
void Blocks::detect_platform() {
std::string bc;
data.read_string(BC65_BC75_OFFSET, bc, 1);
if (bc == "BC65") {
platform = Platform::X65;
data.read_string(X65_MODEL_OFFSET, model);
data.read_string(X65_IMEI_OFFSET, imei);
if (imei.length() != 15) {
imei.clear();
data.read_string(X65_7X_IMEI_OFFSET, imei);
}
} else if (bc == "BC75") {
platform = Platform::X75;
data.read_string(X75_MODEL_OFFSET, model);
data.read_string(X75_IMEI_OFFSET, imei);
} else {
bc.clear();
data.read_string(BC85_OFFSET, bc, 1);
if (bc == "BC85") {
platform = Platform::X85;
data.read_string(X85_MODEL_OFFSET, model);
data.read_string(X85_IMEI_OFFSET, imei);
} else {
platform = Platform::UNK;
}
}
}
void Blocks::search_blocks() {
char *buf = data.get_data().get();
for (size_t offset = 0; offset < data.get_size(); offset += block_size) {
char * ptr = buf + offset;
constexpr size_t header_size = 4 + 2 + 2 + 8;
if (is_empty(ptr, header_size)) {
continue;
}
BlockHeader header;
ptr = read_data<char>(header.name, ptr, 8);
ptr = read_data<uint16_t>(reinterpret_cast<char *>(&header.unknown_1), ptr, 1);
ptr = read_data<uint16_t>(reinterpret_cast<char *>(&header.unknown_2), ptr, 1);
ptr = read_data<uint32_t>(reinterpret_cast<char *>(&header.unknown_3), ptr, 1);
if (header.unknown_3 != 0xFFFFFFF0) {
continue;
}
// fmt::print("Name: {}, Unk1: {:04X}, Unk2: {:04X}, Unk3: {:08X}\n", header.name, header.unknown_1, header.unknown_2, header.unknown_3);
if (header.unknown_2 != 0x0000 && header.unknown_3 != 0xFFFFFFF0) {
// fmt::print("\n");
continue;
}
size_t end_of_name = search_end(header.name, 8);
if (end_of_name == 8) {
continue;
}
if (!is_printable(header.name, end_of_name)) {
continue;
}
header.name[end_of_name] = '\0';
std::string block_name(header.name);
std::vector<std::string> names = { "EEFULL", "EELITE", "FFS" };
bool any_find = false;
for (const auto &name : names) {
if (block_name.find(name) != std::string::npos) {
any_find = true;
break;
}
}
if (any_find == false) {
continue;
}
if (!blocks_map.count(block_name)) {
blocks_map[block_name] = std::vector<Block>();
}
Block block;
block.header = header;
block.offset = offset;
block.count = 2;
block.data = RawData(buf + offset, block_size * block.count);
// block.size = block_size * block.count;
// block.data = std::shared_ptr<char[]>(new char[block.size]);
// ptr = buf + offset;
// memcpy(block.data.get(), ptr, block.size);
blocks_map[block_name].push_back(block);
offset += block_size;
}
}
void Blocks::search_blocks_x85() {
spdlog::debug("search_blocks_x85() {}", data.get_size());
char *buf = data.get_data().get();
for (size_t offset = 0; offset < data.get_size(); offset += block_size) {
char * ptr = buf + offset;
constexpr size_t header_size = 4 + 2 + 2 + 8;
if (is_empty(ptr, header_size)) {
continue;
}
BlockHeader header;
ptr = read_data<char>(header.name, ptr + block_size - 32, 8);
ptr = read_data<uint16_t>(reinterpret_cast<char *>(&header.unknown_1), ptr, 1);
ptr = read_data<uint16_t>(reinterpret_cast<char *>(&header.unknown_2), ptr, 1);
ptr = read_data<uint32_t>(reinterpret_cast<char *>(&header.unknown_3), ptr, 1);
if (header.unknown_3 != 0xFFFFFFF0) {
continue;
}
// spdlog::debug("Name: {}, Unk1: {:04X}, Unk2: {:04X}, Unk3: {:08X}", header.name, header.unknown_1, header.unknown_2, header.unknown_3);
// if (header.unknown_2 != 0x0000 && header.unknown_3 != 0xFFFFFFF0) {
// continue;
// }
size_t end_of_name = search_end(header.name, 8);
if (end_of_name == 8) {
continue;
}
if (!is_printable(header.name, end_of_name)) {
continue;
}
header.name[end_of_name] = '\0';
std::string block_name(header.name);
std::vector<std::string> names = { "EEFULL", "EELITE", "FFS" };
bool any_find = false;
for (const auto &name : names) {
if (block_name.find(name) != std::string::npos) {
any_find = true;
break;
}
}
if (any_find == false) {
continue;
}
if (!blocks_map.count(block_name)) {
blocks_map[block_name] = std::vector<Block>();
}
Block block;
block.header = header;
block.offset = offset - (block_size * 3);
block.count = 4;
block.data = RawData(buf + block.offset, block_size * block.count);
block.name = block_name;
blocks_map[block_name].push_back(block);
// offset += block_size;
// offset += block_size * (block.count - 1);
}
}
void Blocks::print() {
for (const auto &pair : blocks_map) {
spdlog::debug("{} Count: {}:", pair.first, pair.second.size());
for (const auto &block : pair.second) {
spdlog::debug(" 0x{:08X}: {}, Size: {}", block.offset, block.header.name, block.data.get_size());
}
}
}
const Platform Blocks::get_platform() const {
return platform;
}
const std::string & Blocks::get_imei() const {
return imei;
}
const std::string & Blocks::get_model() const {
return model;
}
Blocks::Map &Blocks::get_blocks() {
return blocks_map;
}
RawData &Blocks::get_data() {
return data;
}
};

View file

@ -0,0 +1,33 @@
#include "ffshit/filesystem/directory.h"
namespace FULLFLASH {
namespace Filesystem {
Directory::Directory(std::string name) : name(name) { }
Directory::Ptr Directory::build(std::string name) {
return std::make_shared<Directory>(name);
}
void Directory::add_subdir(Ptr dir) {
subdirs.push_back(dir);
}
void Directory::add_file(File::Ptr file) {
files.push_back(file);
}
const std::string Directory::get_name() const {
return name;
}
const Directory::Directories & Directory::get_subdirs() const {
return subdirs;
}
const File::Files & Directory::get_files() const {
return files;
}
};
};

View file

@ -0,0 +1,86 @@
#include "ffshit/filesystem/extract.h"
#include "ffshit/filesystem/ex.h"
#include "ffshit/system.h"
#include <iostream>
#include <spdlog/spdlog.h>
namespace FULLFLASH {
namespace Filesystem {
void extract(const std::string &path, bool overwrite, std::function<void(std::string)> extractor) {
spdlog::info("Extracting filesystem");
if (System::is_file_exists(path)) {
std::string yes_no;
if (overwrite) {
yes_no = "y";
} else {
while (yes_no != "n" && yes_no != "y") {
spdlog::warn("'{}' is regular file. Delete? (y/n)", path);
yes_no.clear();
std::cin >> yes_no;
System::to_lower(yes_no);
}
}
if (yes_no == "y") {
bool r = System::remove_directory(path);
if (!r) {
throw Exception("Couldn't delete directory '{}'", path);
}
} else {
return;
}
}
if (System::is_directory_exists(path)) {
std::string yes_no;
if (overwrite) {
yes_no = "y";
} else {
while (yes_no != "n" && yes_no != "y") {
spdlog::warn("Directory '{}' already exists. Delete? (y/n)", path);
yes_no.clear();
std::cin >> yes_no;
std::transform(yes_no.begin(), yes_no.end(), yes_no.begin(), [](unsigned char c){
return std::tolower(c);
});
}
}
if (yes_no == "y") {
bool r = System::remove_directory(path);
if (!r) {
throw Exception("Couldn't delete directory '{}'", path);
}
} else {
return;
}
}
bool r = System::create_directory(path,
std::filesystem::perms::owner_read | std::filesystem::perms::owner_write | std::filesystem::perms::owner_exec |
std::filesystem::perms::group_read | std::filesystem::perms::group_exec |
std::filesystem::perms::others_read | std::filesystem::perms::others_exec);
if (!r) {
throw Exception("Couldn't create directory '{}'", path);
}
extractor(path);
};
};
};

26
src/filesystem/file.cpp Normal file
View file

@ -0,0 +1,26 @@
#include "ffshit/filesystem/file.h"
namespace FULLFLASH {
namespace Filesystem {
File::File(const std::string name, const RawData &data) : name(name), data(data) {
}
File::Ptr File::build(const std::string name, const RawData &data) {
return std::make_shared<File>(name, data);
}
const std::string File::get_name() const {
return name;
}
RawData File::get_data() const {
return data;
}
const size_t File::get_size() const {
return data.get_size();
}
};
};

401
src/filesystem/newsgold.cpp Normal file
View file

@ -0,0 +1,401 @@
#include "ffshit/filesystem/newsgold.h"
#include "ffshit/filesystem/ex.h"
#include "ffshit/filesystem/extract.h"
#include "ffshit/help.h"
#include "ffshit/system.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <spdlog/spdlog.h>
#include <iconv.h>
namespace FULLFLASH {
namespace Filesystem {
NewSGOLD::NewSGOLD(Blocks &blocks) : blocks(blocks) { }
void NewSGOLD::load() {
parse_FIT();
}
void NewSGOLD::extract(std::string path, bool overwrite) {
FULLFLASH::Filesystem::extract(path, overwrite, [&](std::string dst_path) {
for (const auto &fs : fs_map) {
std::string fs_name = fs.first;
auto root = fs.second;
spdlog::info("Extracting {}", fs_name);
unpack(root, dst_path + "/" + fs_name);
};
});
}
void NewSGOLD::print_fit_header(const NewSGOLD::FITHeader &header) {
spdlog::debug("===========================");
spdlog::debug("FIT:");
spdlog::debug("Flags: {:08X}", header.flags);
spdlog::debug("ID: {:d}", header.id);
spdlog::debug("Size: {:d}", header.size);
spdlog::debug("Offset: {:04X}", header.offset);
}
void NewSGOLD::print_file_header(const NewSGOLD::FileHeader &header) {
spdlog::debug("===========================");
spdlog::debug("File:");
spdlog::debug("ID: {}", header.id);
spdlog::debug("Parent ID: {}", header.parent_id);
spdlog::debug("Next part ID: {}", header.next_part);
spdlog::debug("Unknown2: {:04X} {}", header.unknown2, header.unknown2);
spdlog::debug("Unknown3: {:04X} {}", header.unknown3, header.unknown3);
spdlog::debug("Unknown4: {:04X} {}", header.unknown4, header.unknown4);
spdlog::debug("Unknown5: {:04X} {}", header.unknown5, header.unknown5);
spdlog::debug("Unknown6: {:04X} {}", header.unknown6, header.unknown6);
spdlog::debug("Unknown7: {:04X} {}", header.unknown7, header.unknown7);
spdlog::debug("Name: {}", header.name);
}
void NewSGOLD::print_file_part(const FilePart &part) {
spdlog::debug("===========================");
spdlog::debug("Part:");
spdlog::debug("ID: {}", part.id);
spdlog::debug("Parent ID: {}", part.parent_id);
spdlog::debug("Next part ID: {}", part.next_part);
}
NewSGOLD::FileHeader NewSGOLD::read_file_header(const RawData &data) {
FileHeader header;
size_t offset = 0;
data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.id), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.unknown1), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.next_part), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.parent_id), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown2), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown3), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown4), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown5), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown6), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown7), 1);
iconv_t iccd = iconv_open("UTF-8", "UTF-16LE");
if (iccd == ((iconv_t)-1)) {
throw Exception("iconv_open(): {}", strerror(errno));
}
offset = 28;
size_t str_size = data.get_size() - 28;
size_t from_size = str_size;
char * from = new char[str_size];
size_t to_size = str_size;
char * to = new char[to_size];
data.read<char>(offset, from, from_size);
char *inptr = from;
char *ouptr = to;
int r = iconv(iccd, &inptr, &from_size, &ouptr, &to_size);
if (r == -1) {
delete[] from;
delete[] to;
throw Exception("iconv(): {}", strerror(errno));
}
to[str_size - to_size] = 0x00;
header.name = std::string(to);
delete []from;
delete []to;
return header;
}
NewSGOLD::FilePart NewSGOLD::read_file_part(const RawData &data) {
FilePart part;
size_t offset = 0;
data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.id), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.parent_id), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.next_part), 1);
return part;
}
void NewSGOLD::parse_FIT() {
Blocks::Map &bl = blocks.get_blocks();
for (const auto &block : blocks.get_blocks()) {
const auto &ffs_block_name = block.first;
const auto &ffs = block.second;
FSBlocksMap ffs_map;
if (ffs_block_name.find("FFS") != std::string::npos) {
spdlog::debug("{} Blocks: {}", ffs_block_name, ffs.size());
} else {
continue;
}
for (auto &block : ffs) {
spdlog::debug(" Block {:08X} Size: {}", block.offset, block.data.get_size());
const RawData & block_data = block.data;
size_t block_size = block_data.get_size();
for (ssize_t offset = block_size - 16; offset > 0; offset -= 16) {
FFSBlock fs_block;
size_t offset_header = offset;
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.flags), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.id), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.size), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.offset), 1);
if (fs_block.header.flags == 0xFFFFFFFF) {
break;
}
if (fs_block.header.flags == 0xFFFFFF00) {
continue;
}
print_fit_header(fs_block.header);
std::string data_print;
for (size_t i = 0; i < 16; ++i) {
char *c = block_data.get_data().get() + offset + i;
data_print += fmt::format("{:02X} ", (unsigned char) *c);
if ((i + 1) % 4 == 0) {
spdlog::debug(data_print);
data_print.clear();
}
}
fs_block.data = RawData(block_data, fs_block.header.offset, fs_block.header.size);
if (ffs_map.count(fs_block.header.id)) {
throw Exception("Duplicate id {}", fs_block.header.id);
}
ffs_map[fs_block.header.id] = fs_block;
// print_fit_header(fs_block.header);
// spdlog::info("Data:\n");
// for (size_t i = 0; i < fs_block.data.get_size(); ++i) {
// spdlog::info("{:02X} ", (unsigned char) *(fs_block.data.get_data().get() + i));
// if ((i + 1) % 32 == 0) {
// spdlog::info("\n");
// }
// }
// spdlog::info("\n");
// spdlog::info("=============================\n");
}
}
// for (const auto &block_pair : ffs_map) {
// const auto &fs_block = block_pair.second;
// // if (fs_block.data.get_size() > 30 && fs_block.data.get_size() < 100) {
// // } else {
// // continue;
// // }
// print_fit_header(fs_block.header);
// spdlog::info("Data:\n");
// for (size_t i = 0; i < fs_block.data.get_size(); ++i) {
// spdlog::info("{:02X} ", (unsigned char) *(fs_block.data.get_data().get() + i));
// if ((i + 1) % 32 == 0) {
// spdlog::info("\n");
// }
// }
// spdlog::info("\n");
// spdlog::info("=============================\n");
// }
// const FFSBlock & root_block = ffs_map.at(0x14);
// FileHeader root_header = read_file_header(root_block.data);
// print_fit_header(root_block.header);
// print_file_header(root_header);
// const FFSBlock & root_block = ffs_map.at(3686);
if (!ffs_map.count(10)) {
throw Exception("Root block (ID: 10) not found. Broken filesystem?");
}
const FFSBlock & root_block = ffs_map.at(10);
FileHeader root_header = read_file_header(root_block.data);
Directory::Ptr root = Directory::build(root_header.name);
scan(ffs_block_name, ffs_map, root, root_header);
fs_map[ffs_block_name] = root;
}
}
void NewSGOLD::read_recurse(FSBlocksMap &ffs_map, RawData &data, uint16_t next_id) {
if (!ffs_map.count(next_id)) {
throw Exception("Reading part. Couldn't find block with id: {}", next_id);
}
const FFSBlock &block = ffs_map.at(next_id);
FilePart part = read_file_part(block.data);
uint16_t data_id = part.id + 1;
print_file_part(part);
if (!ffs_map.count(data_id)) {
throw Exception("Reading part data. Couldn't find block with id: {}", data_id);
}
FFSBlock & block_data = ffs_map.at(data_id);
data.add(block_data.data);
if (part.next_part != 0xFFFFFFFF) {
read_recurse(ffs_map, data, part.next_part);
}
}
RawData NewSGOLD::read_full_data(FSBlocksMap &ffs_map, const FileHeader &header) {
print_file_header(header);
uint32_t data_id = header.id + 1;
if (!ffs_map.count(data_id)) {
throw Exception("Reading file data. Couldn't find block with id: {}", data_id);
}
const FFSBlock &block = ffs_map.at(data_id);
RawData data_full(block.data);
if (header.next_part != 0xFFFFFFFF) {
read_recurse(ffs_map, data_full, header.next_part);
}
return data_full;
}
void NewSGOLD::scan(const std::string &block_name, FSBlocksMap &ffs_map, Directory::Ptr dir, const FileHeader &header, std::string path) {
RawData data = read_full_data(ffs_map, header);
size_t offset = 0;
while (offset < data.get_size()) {
fflush(stdout);
uint32_t raw;
data.read<uint32_t>(offset, reinterpret_cast<char *>(&raw), 1);
offset += 4;
uint16_t id = raw & 0xFFFF;
uint16_t unk = (raw >> 16) & 0xFFFF;
if (id == 0xFFFF) {
break;
}
if (id == 0) {
continue;
}
if (!ffs_map.count(id)) {
throw Exception("FFS Block ID: {} not found", id);
}
const FFSBlock & file_block = ffs_map.at(id);
FileHeader file_header = read_file_header(file_block.data);
spdlog::info("Found ID: {:5d}, Path: {}{}", id, block_name, path + file_header.name);
if (file_header.unknown6 & 0x10) {
Directory::Ptr dir_next = Directory::build(file_header.name);
dir->add_subdir(dir_next);
scan(block_name, ffs_map, dir_next, file_header, path + file_header.name + "/");
} else {
try {
RawData file_data;
uint32_t data_id = file_header.id + 1;
if (ffs_map.count(data_id)) {
file_data = read_full_data(ffs_map, file_header);
}
File::Ptr file = File::build(file_header.name, file_data);
dir->add_file(file);
} catch (const Exception &e) {
spdlog::info("Warning! Broken file: {}", e.what());
}
}
}
}
void NewSGOLD::unpack(Directory::Ptr dir, std::string path) {
bool r = System::create_directory(path,
std::filesystem::perms::owner_read | std::filesystem::perms::owner_write | std::filesystem::perms::owner_exec |
std::filesystem::perms::group_read | std::filesystem::perms::group_exec |
std::filesystem::perms::others_read | std::filesystem::perms::others_exec);
if (!r) {
throw Exception("Couldn't create directory '{}'", path);
}
const auto &subdirs = dir->get_subdirs();
const auto &files = dir->get_files();
for (const auto &file : files) {
if (file->get_name().length() == 0) {
continue;
}
std::string file_path = path + "/" + file->get_name();
std::ofstream file_stream;
spdlog::info(" Extracting {}", file_path);
file_stream.open(file_path, std::ios_base::binary | std::ios_base::trunc);
if (!file_stream.is_open()) {
throw Exception("Couldn't create file '{}': {}", file_path, strerror(errno));
}
file_stream.write(file->get_data().get_data().get(), file->get_data().get_size());
file_stream.close();
}
for (const auto &subdir : subdirs) {
unpack(subdir, path + "/" + subdir->get_name());
}
}
};
};

View file

@ -0,0 +1,759 @@
#include "ffshit/filesystem/newsgold_x85.h"
#include "ffshit/filesystem/ex.h"
#include "ffshit/filesystem/extract.h"
#include <iconv.h>
#include <sys/stat.h>
#include <unistd.h>
#include <spdlog/spdlog.h>
namespace FULLFLASH {
namespace Filesystem {
NewSGOLD_X85::NewSGOLD_X85(Blocks &blocks) : blocks(blocks) {
parse_FIT();
}
void NewSGOLD_X85::load() {
}
static bool is_directory_exists(std::string path) {
struct stat sb;
if (stat(path.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
return true;
}
return false;
}
void NewSGOLD_X85::extract(std::string path, bool overwrite) {
FULLFLASH::Filesystem::extract(path, overwrite, [&](std::string dst_path) {
for (const auto &fs : fs_map) {
std::string fs_name = fs.first;
auto root = fs.second;
spdlog::info("Extracting {}", fs_name);
unpack(root, dst_path + "/" + fs_name);
}
});
}
void NewSGOLD_X85::print_fit_header(const NewSGOLD_X85::FITHeader &header) {
spdlog::debug(" ===========================");
spdlog::debug(" FIT:");
spdlog::debug(" Flags: {:08X}", header.flags);
spdlog::debug(" ID: {:08X} {:d}", header.id, header.id);
spdlog::debug(" Size: {:08X} {:d}", header.size, header.size);
spdlog::debug(" Offset: {:08X}", header.offset);
spdlog::debug(" Unk1: {:08X} {:d}", header.unk1, header.unk1);
spdlog::debug(" Unk2: {:08X} {:d}", header.unk2, header.unk2);
spdlog::debug(" Unk3: {:08X} {:d}", header.unk3, header.unk3);
spdlog::debug(" Unk4: {:08X} {:d}", header.unk4, header.unk4);
}
void NewSGOLD_X85::print_dir_header(const DirHeader &header) {
spdlog::debug("===========================");
spdlog::debug("Dir header:");
spdlog::debug(" ID: {:04X} {}", header.id, header.id);
spdlog::debug(" Unknown1: {:04X} {}", header.unknown1, header.unknown1);
spdlog::debug(" Unknown2: {:04X} {}", header.unknown2, header.unknown2);
spdlog::debug(" Unknown3: {:04X} {}", header.unknown3, header.unknown3);
}
void NewSGOLD_X85::print_file_header(const NewSGOLD_X85::FileHeader &header) {
spdlog::debug("===========================");
spdlog::debug("File:");
spdlog::debug(" ID: {:04X} {}", header.id, header.id);
spdlog::debug(" Unknown1: {:04X} {}", header.unknown1, header.unknown1);
spdlog::debug(" Parent ID: {:04X} {}", header.parent_id, header.parent_id);
spdlog::debug(" Next part ID: {:04X} {}", header.next_part, header.next_part);
spdlog::debug(" Size: {:08X} {}", header.unknown2, header.unknown2);
spdlog::debug(" Unknown4: {:04X} {}", header.unknown4, header.unknown4);
spdlog::debug(" Unknown5: {:04X} {}", header.unknown5, header.unknown5);
spdlog::debug(" Unknown6: {:04X} {}", header.unknown6, header.unknown6);
spdlog::debug(" Unknown7: {:04X} {}", header.unknown7, header.unknown7);
spdlog::debug(" Name: {}", header.name);
}
void NewSGOLD_X85::print_file_part(const FilePart &part) {
spdlog::debug("===========================");
spdlog::debug("Part:");
spdlog::debug(" ID: {:04X} {}", part.id, part.id);
spdlog::debug(" Parent ID: {:04X} {}", part.parent_id, part.parent_id);
spdlog::debug(" Next part ID: {:04X} {}", part.next_part, part.next_part);
}
RawData NewSGOLD_X85::read_aligned(const FFSBlock &block) {
const auto & data = block.data;
const auto & fit = block.header;
char * data_ptr = data.get_data().get() + data.get_size();
size_t to_read = fit.size;
return read_aligned(data_ptr, fit.size);
}
RawData NewSGOLD_X85::read_aligned(char *data, size_t size) {
RawData data_ret;
char * data_ptr = data;
size_t to_read = size;
while(to_read != 0) {
size_t read_size = 16;
size_t skip = 0;
if (to_read > 16) {
// read_size = 16;
} else {
// read_size = to_read;
skip = 16 - to_read;
}
data_ptr -= 32;
data_ret.add_top(data_ptr + skip, read_size - skip);
to_read -= read_size - skip;
}
return data_ret;
}
NewSGOLD_X85::FileHeader NewSGOLD_X85::read_file_header(const FFSBlock &block) {
RawData header_data = read_aligned(block);
NewSGOLD_X85::FileHeader header;
size_t offset = 0;
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.id), 1);
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.unknown1), 1);
// offset += 4;
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.next_part), 1);
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.parent_id), 1);
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.unknown2), 1);
header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown4), 1);
header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown5), 1);
header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown6), 1);
header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown7), 1);
// ======================================================================
offset = 28;
size_t str_size = header_data.get_size() - 28;
size_t from_n = str_size;
char * from = new char[str_size];
size_t to_n = str_size;
char * to = new char[str_size];
header_data.read<char>(offset, from, from_n);
iconv_t iccd = iconv_open("UTF-8", "UTF-16LE");
if (iccd == ((iconv_t)-1)) {
throw Exception("iconv_open(): {}", strerror(errno));
}
char *inptr = from;
char *ouptr = to;
int r = iconv(iccd, &inptr, &from_n, &ouptr, &to_n);
if (r == -1) {
throw Exception("iconv(): {}", strerror(errno));
}
to[str_size - to_n] = 0x00;
header.name = std::string(to);
delete []from;
delete []to;
return header;
}
// NewSGOLD_X85::FileHeader NewSGOLD_X85::read_file_header2(const FFSBlock &block) {
// RawData header_data = block.data_from_header;
// NewSGOLD_X85::FileHeader header;
// size_t offset = 0;
// header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.id), 1);
// header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.unknown1), 1);
// // offset += 4;
// header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.next_part), 1);
// header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.parent_id), 1);
// header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.unknown2), 1);
// header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown4), 1);
// header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown5), 1);
// header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown6), 1);
// header_data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.unknown7), 1);
// // ======================================================================
// offset = 28;
// size_t str_size = header_data.get_size() - 28;
// size_t from_n = str_size;
// char * from = new char[str_size];
// size_t to_n = str_size;
// char * to = new char[str_size];
// header_data.read<char>(offset, from, from_n);
// iconv_t iccd = iconv_open("UTF-8", "UTF-16LE");
// if (iccd == ((iconv_t)-1)) {
// throw Exception("iconv_open(): {}", strerror(errno));
// }
// char *inptr = from;
// char *ouptr = to;
// int r = iconv(iccd, &inptr, &from_n, &ouptr, &to_n);
// if (r == -1) {
// throw Exception("iconv(): {}", strerror(errno));
// }
// to[str_size - to_n] = 0x00;
// header.name = std::string(to);
// delete []from;
// delete []to;
// return header;
// }
NewSGOLD_X85::FilePart NewSGOLD_X85::read_file_part(const FFSBlock &block) {
RawData header_data;
const auto & data = block.data;
const auto & fit = block.header;
char * data_ptr = data.get_data().get() + data.get_size();
size_t to_read = fit.size;
while(to_read != 0) {
size_t read_size = 16;
size_t skip = 0;
if (to_read > 16) {
// read_size = 16;
} else {
// read_size = to_read;
skip = 16 - to_read;
}
data_ptr -= 32;
header_data.add_top(data_ptr + skip, read_size - skip);
to_read -= read_size - skip;
}
// ======================================================================
FilePart part;
size_t offset = 0;
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.id), 1);
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.parent_id), 1);
header_data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.next_part), 1);
return part;
}
void NewSGOLD_X85::dump_data(const RawData &raw_data) {
if (!raw_data.get_data()) {
throw Exception("raw_data == nullptr");
}
bool is_aligned = false;
std::string bin_print;
for (size_t i = 0; i < raw_data.get_size(); ++i) {
is_aligned = false;
bin_print += fmt::format("{:02X} ", (unsigned char) *(raw_data.get_data().get() + i));
if ((i + 1) % 16 == 0) {
spdlog::debug("{}", bin_print);
bin_print.clear();
is_aligned = true;
}
}
if (!is_aligned) {
spdlog::debug("{}", bin_print);
}
}
void NewSGOLD_X85::dump_block(const NewSGOLD_X85::FFSBlock &block, bool is_dump_data) {
spdlog::debug(" ==================================================");
spdlog::debug(" {} FFS Block addr: {:08X}, FIT Record addr {:08X}", block.block_ptr->name, block.ff_boffset, block.ff_offset);
print_fit_header(block.header);
spdlog::debug("Header data (size: {}): ", block.data_header.get_size());
if (is_dump_data) {
dump_data(block.data_header);
if (block.data_from_header.get_size() > 0) {
spdlog::debug("Header aligned data (size: {}): ", block.data_from_header.get_size());
dump_data(block.data_from_header);
}
}
spdlog::debug("Data (size: {}):", block.data.get_size());
if (is_dump_data) {
dump_data(block.data);
}
}
void NewSGOLD_X85::parse_FIT() {
Blocks::Map &bl = blocks.get_blocks();
for (const auto &block : blocks.get_blocks()) {
const auto &ffs_block_name = block.first;
const auto &ffs = block.second;
FSBlocksMap ffs_map_C0;
FSBlocksMapList ffs_map_00;
if (ffs_block_name.find("FFS") != std::string::npos) {
spdlog::debug("{} Blocks: {}", ffs_block_name, ffs.size());
} else {
continue;
}
for (auto &block : ffs) {
spdlog::debug(" Block {:08X} {:08X} {:08X} {:08x} Size: {}",
block.offset,
block.header.unknown_1,
block.header.unknown_2,
block.header.unknown_3,
block.data.get_size());
std::vector<uint32_t> id_list_C0;
std::vector<uint32_t> id_list_00;
const RawData & block_data = block.data;
size_t block_size = block_data.get_size();
size_t fit_size = 0;
size_t last_offset = block_size - 32;
for (ssize_t offset = block_size - 64; offset > 0; offset -= 32) {
FFSBlock fs_block;
size_t offset_header = offset;
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.flags), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.id), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.size), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.offset), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.unk1), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.unk2), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.unk3), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.unk4), 1);
// Конец fit табитцы. Корявое определение. Не очень понятно
// как определять конец, или где находится её размер
// uint32_t end_marker;
// block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&end_marker), 1);
if (fs_block.header.unk1 != 0xFFFFFFFF) {
fit_size = (block.offset + block_size) - (block.offset + offset) - 32;
break;
}
if (fs_block.header.flags == 0xFFFFFFC0 || fs_block.header.flags == 0xFFFFFF00) {
fs_block.data_header.add(block_data.get_data().get() + offset, last_offset - offset + 32);
// spdlog::debug(" {:08X}", block.offset + offset);
fs_block.ff_boffset = block.offset;
fs_block.ff_offset = block.offset + offset;
last_offset = offset - 32;
size_t size_data = ((fs_block.header.size / 16) + 1) * 32;
size_t offset_data = offset - size_data;
fs_block.data = RawData(block_data, offset_data, size_data);
fs_block.block_ptr = &block;
if (fs_block.header.flags == 0xFFFFFFC0) {
if (ffs_map_C0.count(fs_block.header.id)) {
throw Exception("ffs_map_C0 Duplicate id {}", fs_block.header.id);
} else {
ffs_map_C0[fs_block.header.id] = fs_block;
id_list_C0.push_back(fs_block.header.id);
}
}
if (fs_block.header.flags == 0xFFFFFF00) {
if (fs_block.data_header.get_size() > 32) {
ssize_t data_size = fs_block.header.size;
size_t block_size = fs_block.data_header.get_size();
size_t offset = 32;
char *data_ptr = fs_block.data_header.get_data().get();
while (offset != block_size) {
char tmp[16];
memcpy(tmp, data_ptr + offset, 16);
fs_block.data_from_header.add(tmp, 16);
offset += 32;
}
// size_t offset = fs_block.data_header.get_size() - 1;
// while (data_size != 0) {
// offset -= 16;
// size_t to_read;
// if (data_size - 16 > 0) {
// to_read = 16;
// } else {
// to_read = data_size;
// }
// data_size -= to_read;
// offset -= to_read - 1;
// char tmp[16];
// memcpy(tmp, fs_block.data_header.get_data().get() + offset, to_read);
// // spdlog::debug("{}", to_read);
// fs_block.data_from_header.add_top(tmp, to_read);
// // fs_block.data_from_header.reverse(1);
// }
// fs_block.data_from_header = read_aligned(fs_block.data_header.get_data().get() + 32, fs_block.header.size);
}
ffs_map_00[fs_block.header.id].push_back(fs_block);
id_list_00.push_back(fs_block.header.id);
}
dump_block(fs_block);
}
}
spdlog::debug(" C0 ID List:");
for (const auto &id : id_list_C0) {
spdlog::debug(" {}", id);
}
spdlog::debug(" 00 ID List:");
for (const auto &id : id_list_00) {
spdlog::debug(" {}", id);
}
}
if (!ffs_map_C0.count(10)) {
throw Exception("Root block (ID: 10) not found. Broken filesystem?");
}
// return;
spdlog::debug("ROOOOOOOT");
const FFSBlock & root_block = ffs_map_C0.at(10);
FileHeader root_header = read_file_header(root_block);
dump_block(root_block);
Directory::Ptr root = Directory::build(root_header.name);
scan(ffs_map_C0, ffs_map_00, root, root_block);
fs_map[ffs_block_name] = root;
}
}
NewSGOLD_X85::DirList NewSGOLD_X85::get_directory(FSBlocksMap &ffs_map_C0, FSBlocksMapList &ffs_map_00, const FFSBlock &block) {
DirList dir_list;
if (!ffs_map_C0.count(block.header.id + 1)) {
spdlog::warn("get_directory() block ID {} not found in ffs_map", block.header.id + 1);
// exit(0);
return dir_list;
}
const FFSBlock &dir_block = ffs_map_C0.at(block.header.id + 1);
dump_block(dir_block);
const auto & dir_data = dir_block.data;
const size_t dir_data_size = dir_block.data.get_size();
RawData data;
size_t offset = 0;
while (offset < dir_data_size) {
data.add(dir_data.get_data().get() + offset, 16);
offset += 32;
}
// =======================================================
offset = 0;
while (offset < data.get_size()) {
DirHeader dir_header;
data.read<uint16_t>(offset, reinterpret_cast<char *>(&dir_header.id), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&dir_header.unknown1), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&dir_header.unknown2), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&dir_header.unknown3), 1);
if (dir_header.id == 0xFFFF) {
continue;;
}
if (dir_header.id == 0) {
continue;
}
if (dir_header.unknown3 != 0xFFFF) {
continue;
}
print_dir_header(dir_header);
dir_list.push_back(dir_header);
// fmt::print("ID: {:04X}, Unk: {:04X} Unk: {:04X} Unk: {:04X}\n", id, unk, unk2, unk3);
}
return dir_list;
}
uint32_t NewSGOLD_X85::read_part(const FFSBlock &prev_part, const FileHeader &file_header, const FSBlocksMap &ffs_map_C0, const FSBlocksMapList &ffs_map_00, uint32_t next_part, uint32_t last_offset, RawData &data, size_t start_offset) {
if (!ffs_map_C0.count(next_part)) {
throw Exception("read_part() block ID {} not found in ffs_map", next_part);
}
const FFSBlock &part_block = ffs_map_C0.at(next_part);
FilePart part = read_file_part(part_block);
print_file_part(part);
if (!ffs_map_C0.count(next_part + 1)) {
throw Exception("read_part() block ID+1 {} not found in ffs_map", next_part + 1);
}
const FFSBlock &part_data = ffs_map_C0.at(next_part + 1);
print_fit_header(part_data.header);
// dump_block(part_data, false);
// spdlog::debug("ID: {} Full size: {}, data size: {}, maybe size: {}", next_part, file_header.unknown2, data.get_size(), data.get_size() + part_data.header.size);
// spdlog::debug("ID: {} Last offset: {:08X} part_data.header.offset: {:08X}", next_part, last_offset, part_data.header.offset);
if (last_offset == part_data.header.offset) {
spdlog::warn("Add end. Last offset: {:08X} part_data.header.offset: {:08X}\n", last_offset, part_data.header.offset);
auto end = read_aligned(part_data);
data.add(end);
dump_data(end);
return next_part;
}
// size_t data_addr = part_block.ff_boffset + part_data.header.offset + ((part_block.header.offset + part_block.fit_size) & 0x40000);
// size_t data_addr = start_offset + part_data.header.offset;
size_t data_addr = part_data.ff_boffset + part_data.header.offset;
spdlog::debug("Data addr: {:08X} Block offset: {:08X} End data ddr: {:08X}", data_addr, part_data.ff_boffset, (data_addr + part_data.header.size) & 0xFFFFFF00);
// if (part_block.header.offset != part_data.header.offset) {
// data_addr += part_block.header.offset + part_block.fit_size + 0x800;
// }
RawData file_data(this->blocks.get_data(), data_addr, part_data.header.size);
data.add(file_data);
// spdlog::debug("ID: {}, FF Block offset: {:08X} Part block offset {:08X} Size: {:08X} Part data offset {:08X} Size: {:08X} - Data addr: {:08X}",
// next_part, part_block.ff_boffset,
// part_block.header.offset, part_block.header.size,
// part_data.header.offset, part_data.header.size,
// data_addr);
// dump_data(file_data);
if (part.next_part != 0xFFFFFFFF) {
return read_part(part_data, file_header, ffs_map_C0, ffs_map_00, part.next_part, last_offset, data, start_offset);
}
return next_part;
}
void NewSGOLD_X85::read_file(const FSBlocksMap &ffs_map_C0, const FSBlocksMapList &ffs_map_00, const FFSBlock &file_block, RawData &data) {
const FITHeader & fit_header = file_block.header;
FileHeader file_header = read_file_header(file_block);;
if (!ffs_map_C0.count(file_header.id + 1)) {
throw Exception("Block {} not found", file_header.id + 1);
}
print_file_header(file_header);
// if (file_header.name != "Bali_RiceTerraces .jpg") {
// return;
// }
dump_block(file_block);
const FFSBlock &file_data_block = ffs_map_C0.at(file_header.id + 1);
spdlog::debug(" {:08X} Start: {:04X}, {:08X}", file_data_block.ff_boffset, file_data_block.header.offset, file_data_block.ff_boffset + file_data_block.header.offset);
// fmt::print("{:08X} {:04X} {:04X} Data offset: {:04X}\n", file_data.ff_boffset, file_data.header.offset, file_data.header.offset, file_data.ff_boffset + file_data.header.offset - file_data.header.offset);
RawData file_data(this->blocks.get_data(), file_data_block.ff_boffset + file_data_block.header.offset, file_data_block.header.size);
data.add(file_data);
if (file_header.next_part != 0xFFFFFFFF) {
uint32_t last_part = read_part(file_data_block, file_header, ffs_map_C0, ffs_map_00, file_header.next_part, fit_header.offset, data, file_data_block.ff_boffset);
}
if (file_header.next_part != 0xFFFFFFFF) {
// const FFSBlock & block2 = ffs_map.at(last_part + 1);
// dump_block(block2);
// RawData aligned = read_aligned(block2);
// fmt::print("\n");
// dump_data(aligned);
}
}
void NewSGOLD_X85::scan(FSBlocksMap &ffs_map_C0, FSBlocksMapList &ffs_map_00, Directory::Ptr dir, const FFSBlock &block, std::string path) {
auto dir_list = get_directory(ffs_map_C0, ffs_map_00, block);
for (const auto &dir_info : dir_list) {
const FFSBlock * file_block;
if (!ffs_map_C0.count(dir_info.id)) {
spdlog::warn("scan() ID {} not found in ffs_map_C0", dir_info.id);
continue;
if (!ffs_map_00.count(dir_info.id)) {
throw Exception("scan() ID {} not found in ffs_map_00", dir_info.id);
}
// file_block = &ffs_map_00.at(dir_info.id).at(0);
// dump_block(*file_block);
// spdlog::debug(" !!!!! ");
// FileHeader file_header = read_file_header2(*file_block);
// print_file_header(file_header);
// exit(0);
} else {
file_block = &ffs_map_C0.at(dir_info.id);
}
const FITHeader & fit_header = file_block->header;
// dump_block(*file_block);
FileHeader file_header = read_file_header(*file_block);;
spdlog::debug("{:5d} {}", dir_info.id, path + file_header.name);
// spdlog::debug("Block: {:08X}", file_block.ff_boffset);
// spdlog::debug("FF Offset: {:08X}", file_block.ff_offset);
// print_fit_header(file_block.header);
// print_file_header(file_header);
if (file_header.unknown6 & 0x10) {
Directory::Ptr dir_next = Directory::build(file_header.name);
dir->add_subdir(dir_next);
scan(ffs_map_C0, ffs_map_00, dir_next, *file_block, path + file_header.name + "/");
} else {
try {
RawData file_data;
size_t size = file_header.unknown2;
if (file_header.unknown2 != 0) {
read_file(ffs_map_C0, ffs_map_00, *file_block, file_data);
if (size != file_data.get_size()) {
throw Exception("Result size {} != header size {}", file_data.get_size(), size);
}
File::Ptr file = File::build(file_header.name, file_data);
dir->add_file(file);
}
} catch (const Exception &e) {
spdlog::warn("Warning! Broken file: {}\n", e.what());
}
}
}
}
void NewSGOLD_X85::unpack(Directory::Ptr dir, std::string path) {
int r = mkdir(path.c_str(), 0755);
if (r == -1) {
throw Exception("Couldn't create directory '{}': {}", path, strerror(errno));
}
const auto &subdirs = dir->get_subdirs();
const auto &files = dir->get_files();
for (const auto &file : files) {
if (file->get_name().length() == 0) {
continue;
}
std::string file_path = path + "/" + file->get_name();
std::ofstream file_stream;
spdlog::info(" Extracting {}", file_path);
file_stream.open(file_path, std::ios_base::binary | std::ios_base::trunc);
if (!file_stream.is_open()) {
throw Exception("Couldn't create file '{}': {}", file_path, strerror(errno));
}
file_stream.write(file->get_data().get_data().get(), file->get_data().get_size());
file_stream.close();
}
for (const auto &subdir : subdirs) {
unpack(subdir, path + "/" + subdir->get_name());
}
}
};
};

395
src/filesystem/sgold.cpp Normal file
View file

@ -0,0 +1,395 @@
#include "ffshit/filesystem/sgold.h"
#include "ffshit/filesystem/ex.h"
#include "ffshit/filesystem/extract.h"
#include "ffshit/help.h"
#include <sys/stat.h>
#include <fstream>
#include <spdlog/spdlog.h>
// Судя по всему, структура заголовка такая
// Например
// 6C 01 20 01 00 00 21 30 6D 01 00 00 FF FF 6E 01 68 61 74 34 2E 70 6E 67 00
// 6C 01 - ID записи
// 20 01 - ID Родителя (родительский каталог)
// 00 00 21 30 Пока не понятно
// 6D 01 - Вероятно, ID блока с данныем, который идёт хвостом
// 00 00 FF FF - Какие-то аттрибуты если каталог
// 10 00 FF FF - Какие-то аттрибуты если файл
// 6E 01 - Если файл умещается в 1024 байта оно равно FF FF, в противном случае - ID следующего описательного блока
// 68 61 74 34 2E 70 6E 67 00 - Имя файла/каталога
// За загаловком следует блок данных файла
// =============================================================
// Т.е. если файл умещается в 1 блок 1024
// Загаловок
// Данные
// Если файл не умещается в 1024
// Заголовок
// Данные
// Загаловок part
// Данные
// Загаловок part
// Данные
// ....
// пока не влезем
// =============================================================
// Загаловок part - пока не полностью понятно
// 6E 01 20 01 00 00 21 30 6F 01 00 00 6C 01 70 01
// 6E 01 - ID
// 20 01 - Родитель
// 00 00 21 30 Пока не понятно
// 6F 01 - ID блока с данными
// 6C 01 - ID предыдущего блока
// 70 01 - ID следующего описательного part блока
// Последние 4 байта - ID следующего блока. Если последний - FF FF
// =============================================================
// Например hat4.png
// 6C 01 20 01 00 00 21 30 6D 01 00 00 FF FF 6E 01 68 61 74 34 2E 70 6E 67 00
// Данные ID 6D 01 - исходя из заголовка
// 6E 01 20 01 00 00 21 30 6F 01 00 00 6C 01 70 01
// Данные ID 6F 01 - исходя из заголовка
// 70 01 20 01 00 00 21 30 71 01 00 00 6E 01 FF FF
// Данные ID 71 01 - исходя из заголовка
namespace FULLFLASH {
namespace Filesystem {
SGOLD::SGOLD(Blocks &blocks) : blocks(blocks) { }
void SGOLD::load() {
parse_FIT();
}
void SGOLD::extract(std::string path, bool overwrite) {
FULLFLASH::Filesystem::extract(path, overwrite, [&](std::string dst_path) {
for (const auto &fs : fs_map) {
std::string fs_name = fs.first;
auto root = fs.second;
spdlog::info("Extracting {}", fs_name);
unpack(root, dst_path + "/" + fs_name);
};
});
// spdlog::info("Extracting filesystem");
// int r = mkdir(path.c_str(), 0755);
// if (r == -1) {
// throw Exception("Couldn't create directory '{}': {}", path, strerror(errno));
// }
// for (const auto &fs : fs_map) {
// std::string fs_name = fs.first;
// auto root = fs.second;
// spdlog::info("Extracting {}", fs_name);
// unpack(root, path + "/" + fs_name);
// }
}
void SGOLD::print_fit_header(const SGOLD::FITHeader &header) {
spdlog::debug("===========================");
spdlog::debug("FIT:");
spdlog::debug("Flags: {:08X}", header.flags);
spdlog::debug("ID: {:d}", header.id);
spdlog::debug("Size: {:d}", header.size);
spdlog::debug("Offset: {:08X}", header.offset);
}
void SGOLD::print_file_header(const SGOLD::FileHeader &header) {
spdlog::debug("===========================");
spdlog::debug("File:");
spdlog::debug("ID: {}", header.id);
spdlog::debug("Parent ID: {}", header.parent_id);
spdlog::debug("Unknown: {:04X}", header.unknown);
spdlog::debug("Data ID: {}", header.data_id);
spdlog::debug("Attributes: {:04X}", header.attributes);
spdlog::debug("Next part ID: {}", header.next_part);
spdlog::debug("Name: {}", header.name);
}
void SGOLD::print_file_part(const SGOLD::FilePart &part) {
spdlog::debug("===========================");
spdlog::debug("File part:");
spdlog::debug("ID: {}", part.id);
spdlog::debug("Parent ID: {}", part.parent_id);
spdlog::debug("Unknown: {:04X}", part.unknown);
spdlog::debug("Data ID: {}", part.data_id);
spdlog::debug("Unknown2: {:04X}", part.unknown2);
spdlog::debug("Prev ID: {}", part.prev_id);
spdlog::debug("Next part ID: {}", part.next_part);
}
SGOLD::FileHeader SGOLD::read_file_header(const RawData &data) {
SGOLD::FileHeader header;
size_t offset = 0;
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.id), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.parent_id), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.unknown), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.data_id), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&header.attributes), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&header.next_part), 1);
data.read_string(offset, header.name);
return header;
}
SGOLD::FilePart SGOLD::read_file_part(const RawData &data) {
SGOLD::FilePart part;
size_t offset = 0;
data.read<uint16_t>(offset, reinterpret_cast<char *>(&part.id), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&part.parent_id), 1);
data.read<uint32_t>(offset, reinterpret_cast<char *>(&part.unknown), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&part.data_id), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&part.unknown2), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&part.prev_id), 1);
data.read<uint16_t>(offset, reinterpret_cast<char *>(&part.next_part), 1);
return part;
}
void SGOLD::parse_FIT() {
Blocks::Map &bl = blocks.get_blocks();
for (const auto &block : blocks.get_blocks()) {
const auto &ffs_block_name = block.first;
const auto &ffs = block.second;
FSBlocksMap ffs_map;
if (ffs_block_name.find("FFS") != std::string::npos) {
spdlog::debug("{} Blocks:", ffs_block_name, ffs.size());
} else {
continue;
}
bool data_end = true;
size_t max_block = 0;
for (auto &block : ffs) {
spdlog::debug(" Block {:08X} Size: {}", block.offset, block.data.get_size());
const RawData & block_data = block.data;
size_t block_size = block_data.get_size();
for (ssize_t offset = block_size - 16; offset > 0; offset -= 16) {
FFSBlock fs_block;
size_t offset_header = offset;
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.flags), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.id), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.size), 1);
block_data.read<uint32_t>(offset_header, reinterpret_cast<char *>(&fs_block.header.offset), 1);
// spdlog::debug(" ==== Offset: {:08X} ====", block.offset + offset);
// spdlog::debug(" ID: {:08X}", fs_block.header.id);
// spdlog::debug(" Size: {:08X} {}", fs_block.header.size, fs_block.header.size);
// spdlog::debug(" Offset: {:08X}", fs_block.header.offset);
// spdlog::debug(" Flags: {:08X}", fs_block.header.flags);
if (fs_block.header.flags == 0xFFFFFFFF) {
break;
}
if (fs_block.header.flags == 0xFFFFFF00) {
continue;
}
print_fit_header(fs_block.header);
std::string data_print;
for (size_t i = 0; i < 16; ++i) {
char *c = block_data.get_data().get() + offset + i;
data_print += fmt::format("{:02X} ", (unsigned char) *c);
if ((i + 1) % 4 == 0) {
spdlog::debug(data_print);
data_print.clear();
}
}
// fs_block.data = RawData(block_data_ptr + fs_block.header.offset, fs_block.header.size);
fs_block.data = RawData(block_data, fs_block.header.offset, fs_block.header.size);
if (ffs_map.count(fs_block.header.id)) {
throw Exception("Duplicate id {}", fs_block.header.id);
}
ffs_map[fs_block.header.id] = fs_block;
if (fs_block.header.id > max_block) {
max_block = fs_block.header.id;
}
}
}
if (!ffs_map.count(6)) {
throw Exception("Root block (ID: 6) not found. Broken filesystem?");
}
const FFSBlock & root_block = ffs_map.at(6);
FileHeader root_header = read_file_header(root_block.data);
Directory::Ptr root = Directory::build(root_header.name);
scan(ffs_block_name, ffs_map, root, root_header);
fs_map[ffs_block_name] = root;
}
}
void SGOLD::unpack(Directory::Ptr dir, std::string path) {
int r = mkdir(path.c_str(), 0755);
if (r == -1) {
throw Exception("Couldn't create directory '{}': {}", path, strerror(errno));
}
const auto &subdirs = dir->get_subdirs();
const auto &files = dir->get_files();
for (const auto &file : files) {
if (file->get_name().length() == 0) {
continue;
}
std::string file_path = path + "/" + file->get_name();
std::ofstream file_stream;
spdlog::info(" Extracting {}", file_path);
file_stream.open(file_path, std::ios_base::binary | std::ios_base::trunc);
if (!file_stream.is_open()) {
throw Exception("Couldn't create file '{}': {}", file_path, strerror(errno));
}
file_stream.write(file->get_data().get_data().get(), file->get_data().get_size());
file_stream.close();
}
for (const auto &subdir : subdirs) {
unpack(subdir, path + "/" + subdir->get_name());
}
}
void SGOLD::scan(const std::string &block_name, FSBlocksMap &ffs_map, Directory::Ptr dir, const FileHeader &header, std::string path) {
RawData data = read_full_data(ffs_map, header);
size_t offset = 0;
while (offset < data.get_size()) {
uint32_t raw;
data.read<uint32_t>(offset, reinterpret_cast<char *>(&raw), 1);
uint16_t id = raw & 0xFFFF;
uint16_t unk = (raw >> 16) & 0xFFFF;
if (id == 0xFFFF) {
continue;
}
if (id == 0) {
continue;
}
if (!ffs_map.count(id)) {
throw Exception("FFS Block ID: {} not found", id);
}
const FFSBlock &tmp = ffs_map.at(id);
FileHeader title = read_file_header(tmp.data);
spdlog::info("Found ID: {:5d}, Path: {}{}{}", id, block_name, path, title.name);
if (title.attributes & 0x10) {
Directory::Ptr dir_next = Directory::build(title.name);
dir->add_subdir(dir_next);
scan(block_name, ffs_map, dir_next, title, path + title.name + "/");
} else {
try {
RawData file_data;
if (ffs_map.count(title.data_id)) {
file_data = read_full_data(ffs_map, title);
}
File::Ptr file = File::build(title.name, file_data);
dir->add_file(file);
} catch (const Exception &e) {
spdlog::warn("Warning! Broken file: {}", e.what());
}
}
}
}
void SGOLD::read_recurse(FSBlocksMap &ffs_map, RawData &data, uint16_t next_id) {
if (!ffs_map.count(next_id)) {
throw Exception("Reading part. Couldn't find block with id: {}", next_id);
}
const FFSBlock &block = ffs_map.at(next_id);
FilePart part = read_file_part(block.data);
print_file_part(part);
if (!ffs_map.count(part.data_id)) {
throw Exception("Reading part data. Couldn't find block with id: {}", part.data_id);
}
FFSBlock & block_data = ffs_map.at(part.data_id);
data.add(block_data.data);
if (part.next_part != 0xFFFF) {
read_recurse(ffs_map, data, part.next_part);
}
}
RawData SGOLD::read_full_data(FSBlocksMap &ffs_map, const FileHeader &header) {
print_file_header(header);
if (!ffs_map.count(header.data_id)) {
throw Exception("Reading file data. Couldn't find block with id: {}", header.data_id);
}
const FFSBlock &block = ffs_map.at(header.data_id);
RawData data_full(block.data);
if (header.next_part != 0xFFFF) {
read_recurse(ffs_map, data_full, header.next_part);
}
return data_full;
}
};
};

166
src/rawdata.cpp Normal file
View file

@ -0,0 +1,166 @@
#include "ffshit/rawdata.h"
#include "ffshit/ex.h"
#include <cstring>
namespace FULLFLASH {
RawData::RawData() : size(0) { }
RawData::RawData(char *data, size_t size) {
this->data = Data(new char[size]);
memcpy(this->data.get(), data, size);
this->size = size;
}
RawData::RawData(const RawData &prev) {
this->size = prev.size;
this->data = Data(new char[prev.size]);
memcpy(this->data.get(), prev.data.get(), prev.size);
}
RawData::RawData(const RawData &prev, size_t offset, size_t size) {
if (offset + size > prev.get_size()) {
throw Exception("RawData() offset + size > prev. size");
}
this->size = size;
this->data = Data(new char[size]);
memcpy(this->data.get(), prev.data.get() + offset, size);
}
RawData::RawData(std::ifstream &file, size_t offset, size_t size) {
this->size = size;
this->data = Data(new char[size]);
file.seekg(offset, std::ios_base::beg);
file.read(data.get(), size);
}
void RawData::reverse(size_t align_size) {
}
void RawData::add(char *data, size_t size) {
size_t size_new = this->size + size;
Data tmp_data;
if (this->size > 0) {
tmp_data = Data(new char[this->size]);
memcpy(tmp_data.get(), this->data.get(), this->size);
}
this->data = Data(new char[size_new]);
if (this->size > 0) {
memcpy(this->data.get(), tmp_data.get(), this->size);
}
memcpy(this->data.get() + this->size, data, size);
this->size = size_new;
}
void RawData::add_top(char *data, size_t size) {
size_t size_new = this->size + size;
Data tmp_data;
if (this->data) {
tmp_data = Data(new char[this->size]);
memcpy(tmp_data.get(), this->data.get(), this->size);
}
this->data = Data(new char[size_new]);
memcpy(this->data.get(), data, size);
if (tmp_data) {
memcpy(this->data.get() + size, tmp_data.get(), this->size);
}
this->size = size_new;
}
void RawData::add(const RawData &data) {
add(data.data.get(), data.size);
}
void RawData::write(size_t offset, char *data, size_t size) {
if (offset >= this->size) {
throw Exception("Offset >= data size. Offset: {}, Data size: {}", offset, this->size);
}
if (offset + size > this->size) {
throw Exception("Write size + offset > data size; Offset: {}, Write size: {}, Data size: {}", offset, size, this->size);
}
memcpy(this->data.get() + offset, data, size);
}
void RawData::read(size_t offset, char *data, size_t size) const {
if (offset >= this->size) {
throw Exception("Offset >= data size. Offset: {}, Data size: {}", offset, this->size);
}
if (offset + size > this->size) {
throw Exception("Read size + offset > data size; Offset: {}, Read size: {}, Data size: {}", offset, size, this->size);
}
memcpy(data, this->data.get() + offset, size);
}
void RawData::read_string(size_t offset, std::string &str, size_t step) const {
size_t offset_start = offset;
while(1) {
if (offset >= size) {
break;
// throw Exception("Couldn't find end of string. Offset: {}, Size: {}", offset_start, size);
}
char *c = data.get() + offset;
if (*c == 0x0) {
break;
}
str.push_back(*c);
offset += step;
}
}
void RawData::read_wstring(size_t offset, std::wstring &str) const {
while(1) {
if (offset >= size) {
break;
}
wchar_t *c = (wchar_t *) (data.get() + offset);
if (*c == 0x0) {
break;
}
str.push_back(*c);
offset += 2;
}
}
RawData::Data RawData::get_data() const {
return data;
}
const size_t RawData::get_size() const {
return size;
}
};

70
src/system.cpp Normal file
View file

@ -0,0 +1,70 @@
#include "ffshit/system.h"
#include <algorithm>
namespace System {
bool is_file_exists(const std::string &path) {
if (std::filesystem::exists(path)) {
if (std::filesystem::is_regular_file(path)) {
return true;
}
}
return false;
}
bool is_directory_exists(const std::string &path) {
if (std::filesystem::exists(path)) {
if (std::filesystem::is_directory(path)) {
return true;
}
}
return false;
}
bool remove_directory(const std::filesystem::path path) {
if (!std::filesystem::exists(path)) {
return true;
}
for (const auto& entry : std::filesystem::directory_iterator(path)) {
if (std::filesystem::is_directory(entry)) {
if (!remove_directory(entry)) {
return false;
}
} else {
if (!std::filesystem::remove(entry)) {
return false;
}
}
}
return std::filesystem::remove(path);
}
bool create_directory(const std::string &path, std::filesystem::perms perms) {
if (std::filesystem::create_directory(path)) {
std::filesystem::permissions(path, perms, std::filesystem::perm_options::replace);
return true;
}
return false;
}
void to_lower(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){
return std::tolower(c);
});
}
void to_upper(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){
return std::toupper(c);
});
}
};