1
0
Fork 0
mirror of https://github.com/DarkMatterCore/nxdumptool.git synced 2024-11-22 18:26:39 +00:00

Complete set of changes since the latest commit made by MCMrARM.

This commit is contained in:
Pablo Curiel 2018-06-21 02:42:46 -04:00
parent 83e4633aea
commit c6ad72f182
20 changed files with 3351 additions and 807 deletions

124
LICENSE.md Normal file
View file

@ -0,0 +1,124 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the 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 Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
One line to give the program's name and a brief idea of what it does.
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.

View file

@ -9,7 +9,37 @@ endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
TARGET := swupdatedumper
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm".
# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional)
#
# NO_ICON: if set to anything, do not use icon.
# NO_NACP: if set to anything, no .nacp file is generated.
# APP_TITLE is the name of the app stored in the .nacp file (Optional)
# APP_AUTHOR is the author of the app stored in the .nacp file (Optional)
# APP_VERSION is the version of the app stored in the .nacp file (Optional)
# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional)
# ICON is the filename of the icon (.jpg), relative to the project folder.
# If not set, it attempts to use one of the following (in this order):
# - <Project name>.jpg
# - icon.jpg
# - <libnx folder>/default_icon.jpg
#---------------------------------------------------------------------------------
VERSION_MAJOR := 1
VERSION_MINOR := 0
VERSION_MICRO := 0
APP_TITLE := Game Card Dump Tool
APP_AUTHOR := MCMrARM, DarkMatterCore
APP_VERSION := ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO}
TARGET := gcdumptool
BUILD := build
SOURCES := source
DATA := data

22
README.md Normal file
View file

@ -0,0 +1,22 @@
# gcdumptool
Nintendo Switch Game Card Dump Tool
Main features
--------------
* Generates full XCI cartridge dumps (with optional certificate removal). All dumps are padded with 0xFF up to the actual game card size.
* Precise HFS0 raw partition dumping (using the root HFS0 header from the game card).
* Partition filesystem data dumping.
* Partition filesystem browser (with manual file dump support).
* Manual game card certificate dump.
* Free SD card space checks in place.
* File splitting support for all operations, using 2 GiB parts.
* Game card Title ID and Control.nacp retrieval support using NCM and NS services.
Thanks to
--------------
* MCMrARM, for creating the original application.
* Foen, for giving me some pretty good hints about how to use the NCM service.
* Yellows8, for helping me fix a silly bug in my implementation of some NCM service IPC calls.
* The folks from ReSwitched, for working towards the creation of a good homebrew ecosystem.

BIN
icon.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -1,9 +0,0 @@
#pragma once
#define C_RESET "\x1b[0m"
#define C_DIM "\x1b[2m"
#define C_RED "\x1b[31m"
#define C_GREEN "\x1b[32m"
#define C_CYAN "\x1b[36m"
#define C_INVERT "\x1b[7m"
#define C_CLEAR_LINE "\x1b[2K"

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,62 @@
#pragma once
#ifndef __DUMPER_H__
#define __DUMPER_H__
#include <switch.h>
#define DUMP_BUFFER_SIZE (u64)0x100000 // 1 MiB
#define ISTORAGE_PARTITION_CNT 2
#define SPLIT_FILE_MIN (u64)0xEE6B2800 // 4 GB (4000000000 bytes)
#define SPLIT_FILE_2GiB (u64)0x80000000
#define CERT_OFFSET 0x7000
#define CERT_SIZE 0x200
#define GAMECARD_HEADER_SIZE 0x200
#define GAMECARD_SIZE_ADDR 0x10D
#define HFS0_OFFSET_ADDR 0x130
#define HFS0_SIZE_ADDR 0x138
#define HFS0_MAGIC 0x48465330 // "HFS0"
#define HFS0_FILE_COUNT_ADDR 0x04
#define HFS0_ENTRY_TABLE_ADDR 0x10
#define GAMECARD_TYPE1_PARTITION_CNT 3 // "update" (0), "normal" (1), "update" (2)
#define GAMECARD_TYPE2_PARTITION_CNT 4 // "update" (0), "logo" (1), "normal" (2), "update" (3)
#define GAMECARD_TYPE(x) ((x) == GAMECARD_TYPE1_PARTITION_CNT ? "Type 0x01" : ((x) == GAMECARD_TYPE2_PARTITION_CNT ? "Type 0x02" : "Unknown"))
#define GAMECARD_SIZE_1GiB (u64)0x40000000
#define GAMECARD_SIZE_2GiB (u64)0x80000000
#define GAMECARD_SIZE_4GiB (u64)0x100000000
#define GAMECARD_SIZE_8GiB (u64)0x200000000
#define GAMECARD_SIZE_16GiB (u64)0x400000000
#define GAMECARD_SIZE_32GiB (u64)0x800000000
#define bswap_32(a) ((((a) << 24) & 0xff000000) | (((a) << 8) & 0xff0000) | (((a) >> 8) & 0xff00) | (((a) >> 24) & 0xff))
typedef struct
{
u64 file_offset;
u64 file_size;
u32 filename_offset;
u32 hashed_region_size;
u64 reserved;
u8 hashed_region_sha256[0x20];
} PACKED hfs0_entry_table;
void workaroundPartitionZeroAccess(FsDeviceOperator* fsOperator);
bool getRootHfs0Header(FsDeviceOperator* fsOperator);
bool getHsf0PartitionDetails(u32 partition, u64 *out_offset, u64 *out_size);
bool dumpGameCartridge(FsDeviceOperator* fsOperator, bool isFat32, bool dumpCert);
bool dumpRawPartition(FsDeviceOperator* fsOperator, u32 partition, bool doSplitting);
bool openPartitionFs(FsFileSystem* ret, FsDeviceOperator* fsOperator, u32 partition);
bool dumpPartitionRaw(FsDeviceOperator* fsOperator, u32 partition);
bool copyFile(const char* source, const char* dest, bool doSplitting);
bool copyDirectory(const char* source, const char* dest, bool doSplitting);
bool copyDirectory(const char* source, const char* dest, bool doSplitting);
void removeDirectory(const char *path);
bool getDirectorySize(const char *path, u64 *out_size);
bool dumpPartitionData(FsDeviceOperator* fsOperator, u32 partition);
bool mountViewPartition(FsDeviceOperator *fsOperator, u32 partition);
bool dumpGameCertificate(FsDeviceOperator *fsOperator);
#endif

View file

@ -1,81 +0,0 @@
#include "filebrowser.h"
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
static MenuItem* currentFileListBuf;
static const char* currentBasePath;
static void (*currentExitCb)();
static void freeCurrentFileListBuf() {
MenuItem* ptr = currentFileListBuf;
while (ptr != NULL) {
free(ptr->text);
if (ptr->userdata != NULL)
free(ptr->userdata);
ptr++;
}
free(currentFileListBuf);
}
static void exitFileList() {
freeCurrentFileListBuf();
currentBasePath = NULL;
currentExitCb();
}
static char* getParentDir(const char* path, const char* basePath) {
char* ptr = strrchr(path, '/');
if (ptr == NULL || (ptr - path < strlen(basePath) && strcmp(path, basePath) == 0))
return NULL;
char* retval = (char*) malloc(ptr - path + 1);
memcpy(retval, path, ptr - path);
retval[ptr - path] = '\0';
return retval;
}
static char* pathJoin(const char* p1, const char* p2) {
size_t p1s = strlen(p1);
if (p1s == 0)
return strdup(p2);
size_t p2s = strlen(p2);
char* retval = (char*) malloc(p1s + 1 + p2s + 1);
memcpy(retval, p1, p1s);
retval[p1s] = '/';
memcpy(&retval[p1s + 1], p2, p2s + 1); // copy with null terminator
return retval;
}
static void printFilesInDirMenuItem(MenuItem* item);
void printFilesInDir(const char* path, const char* basePath, void (*exitCb)()) {
int maxMenuItemCount = 48;
MenuItem* buf = (MenuItem*) malloc(sizeof(MenuItem) * (maxMenuItemCount + 1));
currentFileListBuf = buf;
currentBasePath = basePath;
currentExitCb = exitCb;
DIR* dir = opendir(path);
struct dirent* ent;
int bufi = 0;
char* parentDir = getParentDir(path, basePath);
if (parentDir != NULL) {
buf[bufi].userdata = parentDir;
buf[bufi].text = strdup("..");
buf[bufi].callback = printFilesInDirMenuItem;
bufi++;
}
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_DIR) {
buf[bufi].text = pathJoin(ent->d_name, "");
buf[bufi].userdata = pathJoin(path, ent->d_name);
buf[bufi].callback = printFilesInDirMenuItem;
} else {
buf[bufi].text = strdup(ent->d_name);
buf[bufi].userdata = buf[bufi].callback = NULL;
}
if (++bufi >= maxMenuItemCount)
break;
}
buf[bufi].text = NULL;
closedir(dir);
menuSetCurrent(buf, exitFileList);
}
static void printFilesInDirMenuItem(MenuItem* item) {
printFilesInDir(item->userdata, currentBasePath, currentExitCb);
}

View file

@ -1,5 +0,0 @@
#pragma once
#include "menu.h"
void printFilesInDir(const char* path, const char* basePath, void (*exitCb)());

View file

@ -1,236 +1,237 @@
#include <switch/kernel/ipc.h>
#include <stdlib.h>
#include <string.h>
#include "fsext.h"
#include <switch/kernel/ipc.h>
// IFileSystemProxy
Result fsOpenGameCardStorage(FsStorage* out, u32 handle, u32 partition) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u32 handle;
u32 partition;
} PACKED *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 30;
raw->handle = handle;
raw->partition = partition;
Result rc = serviceIpcDispatch(fsGetServiceSession());
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
serviceCreate(&out->s, r.Handles[0]);
}
}
return rc;
}
Result fsMountGameCard(FsFileSystem* out, u32 handle, u32 partition) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u32 handle;
u32 partition;
} PACKED *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 31;
raw->handle = handle;
raw->partition = partition;
Result rc = serviceIpcDispatch(fsGetServiceSession());
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
serviceCreate(&out->s, r.Handles[0]);
}
}
return rc;
Result fsOpenGameCardStorage(FsStorage* out, u32 handle, u32 partition)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u32 handle;
u32 partition;
} PACKED *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 30;
raw->handle = handle;
raw->partition = partition;
Result rc = serviceIpcDispatch(fsGetServiceSession());
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) serviceCreate(&out->s, r.Handles[0]);
}
return rc;
}
Result fsOpenGameCardFileSystem(FsFileSystem* out, u32 handle, u32 partition)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u32 handle;
u32 partition;
} PACKED *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 31;
raw->handle = handle;
raw->partition = partition;
Result rc = serviceIpcDispatch(fsGetServiceSession());
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) serviceCreate(&out->s, r.Handles[0]);
}
return rc;
}
// IDeviceOperator
Result fsDeviceOperatorIsGameCardInserted(FsDeviceOperator* d, bool* out) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 200;
Result rc = serviceIpcDispatch(&d->s);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u8 is_inserted;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
*out = resp->is_inserted != 0;
}
}
return rc;
Result fsDeviceOperatorIsGameCardInserted(FsDeviceOperator* d, bool* out)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 200;
Result rc = serviceIpcDispatch(&d->s);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u8 is_inserted;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) *out = resp->is_inserted != 0;
}
return rc;
}
Result fsDeviceOperatorUpdatePartitionInfo(FsDeviceOperator* d, u32 handle, u32* out_title_version, u64* out_title_id) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u32 handle;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 203;
raw->handle = handle;
Result rc = serviceIpcDispatch(&d->s);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 title_ver;
u64 title_id;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
if (out_title_version != NULL)
*out_title_version = resp->title_ver;
if (out_title_id != NULL)
*out_title_id = resp->title_id;
}
}
return rc;
Result fsDeviceOperatorGetGameCardHandle(FsDeviceOperator* d, u32* out)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 202;
Result rc = serviceIpcDispatch(&d->s);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 handle;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) *out = resp->handle;
}
return rc;
}
Result fsDeviceOperatorGetGameCardHandle(FsDeviceOperator* d, u32* out) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 202;
Result rc = serviceIpcDispatch(&d->s);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 handle;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
*out = resp->handle;
}
}
return rc;
Result fsDeviceOperatorUpdatePartitionInfo(FsDeviceOperator* d, u32 handle, u32* out_title_version, u64* out_title_id)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u32 handle;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 203;
raw->handle = handle;
Result rc = serviceIpcDispatch(&d->s);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u32 title_ver;
u64 title_id;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc))
{
if (out_title_version != NULL) *out_title_version = resp->title_ver;
if (out_title_id != NULL) *out_title_id = resp->title_id;
}
}
return rc;
}
// FsStorage
Result fsStorageGetSize(FsStorage* s, u64* out) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 4;
Result rc = serviceIpcDispatch(&s->s);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u64 size;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
*out = resp->size;
}
}
return rc;
}
Result fsStorageGetSize(FsStorage* s, u64* out)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 4;
Result rc = serviceIpcDispatch(&s->s);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u64 size;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) *out = resp->size;
}
return rc;
}

View file

@ -1,18 +1,21 @@
#pragma once
#ifndef __FSEXT_H__
#define __FSEXT_H__
#include <switch/types.h>
#include <switch/services/fs.h>
// IFileSystemProxy
Result fsOpenGameCardStorage(FsStorage* out, u32 handle, u32 partition);
Result fsMountGameCard(FsFileSystem* out, u32 handle, u32 partition);
Result fsOpenGameCardFileSystem(FsFileSystem* out, u32 handle, u32 partition);
// IDeviceOperator
Result fsDeviceOperatorIsGameCardInserted(FsDeviceOperator* d, bool* out);
Result fsDeviceOperatorGetGameCardHandle(FsDeviceOperator* d, u32* out);
Result fsDeviceOperatorUpdatePartitionInfo(FsDeviceOperator* d, u32 handle, u32* out_title_version, u64* out_title_id);
// FsStorage
Result fsStorageGetSize(FsStorage* s, u64* out);
Result fsStorageGetSize(FsStorage* s, u64* out);
#endif

View file

@ -1,148 +1,169 @@
#include <stdio.h>
#include <malloc.h>
#include <switch.h>
#include <memory.h>
#include "menu.h"
#include <switch/services/ns.h>
#include "dumper.h"
#include "ccolor.h"
#include "filebrowser.h"
#include "ncmext.h"
#include "ui.h"
#include "util.h"
FsDeviceOperator fsOperatorInstance;
bool shouldExit = false;
bool shouldWaitForAnyButton = false;
bool gameCardInserted;
u64 gameCardSize = 0;
char gameCardSizeStr[32] = {'\0'};
char *hfs0_header = NULL;
u64 hfs0_offset = 0, hfs0_size = 0;
u32 hfs0_partition_cnt = 0;
void menuExit() {
shouldExit = true;
}
u64 gameCardTitleID = 0;
char gameCardName[0x201] = {'\0'}, gameCardAuthor[0x101] = {'\0'}, gameCardVersion[0x11] = {'\0'};
void menuWaitForAnyButton() {
printf(C_DIM "Press any button to return to menu\n");
shouldWaitForAnyButton = true;
}
void startOperation(const char* title) {
consoleClear();
printf(C_DIM "%s\n\n" C_RESET, title);
}
void dumpPartitionRawMenuItem(MenuItem* item) {
u32 partition = (u32) (size_t) item->userdata;
char titlebuf[64];
sprintf(titlebuf, "Dump Partition %i (Raw)", partition);
startOperation(titlebuf);
if (partition == 0 || partition == 1)
workaroundPartitionZeroAccess(&fsOperatorInstance);
dumpPartitionRaw(&fsOperatorInstance, partition);
menuWaitForAnyButton();
}
void dumpPartitionDataMenuItem(MenuItem* item) {
u32 partition = (u32) (size_t) item->userdata;
char titlebuf[64];
sprintf(titlebuf, "Dump Partition %i", partition);
startOperation(titlebuf);
if (partition == 0 || partition == 1)
workaroundPartitionZeroAccess(&fsOperatorInstance);
FsFileSystem fs;
if (openPartitionFs(&fs, &fsOperatorInstance, partition) &&
fsdevMountDevice("gamecard", fs) != -1) {
char outbuf[64];
sprintf(outbuf, "/dump_%u", partition);
printf("Copying to %s\n", outbuf);
if (copyDirectory("gamecard:/", outbuf, true)) {
printf("Done!\n");
}
}
fsdevUnmountDevice("dump");
menuWaitForAnyButton();
}
void openMainMenu();
void viewPartitionExitCb() {
fsdevUnmountDevice("view");
openMainMenu();
}
void viewPartitionMenuItem(MenuItem* item) {
u32 partition = (u32) (size_t) item->userdata;
startOperation("View Files");
if (partition == 0 || partition == 1)
workaroundPartitionZeroAccess(&fsOperatorInstance);
FsFileSystem fs;
if (!openPartitionFs(&fs, &fsOperatorInstance, partition)) {
menuWaitForAnyButton();
return;
}
if (fsdevMountDevice("view", fs) == -1) {
printf("fsdevMountDevice failed\n");
menuWaitForAnyButton();
return;
}
printFilesInDir("view://", "view://", viewPartitionExitCb);
}
MenuItem mainMenu[] = {
{ .text = "Dump Partition 0 (SysUpdate)", .callback = dumpPartitionDataMenuItem, .userdata = (void*) 0 },
{ .text = "Dump Partition 1 (Normal)", .callback = dumpPartitionDataMenuItem, .userdata = (void*) 1 },
{ .text = "Dump Partition 2 (Secure)", .callback = dumpPartitionDataMenuItem, .userdata = (void*) 2 },
{ .text = "Raw Dump Partition 0 (SysUpdate)", .callback = dumpPartitionRawMenuItem, .userdata = (void*) 0 },
{ .text = "Raw Dump Partition 1 (Normal)", .callback = dumpPartitionRawMenuItem, .userdata = (void*) 1 },
{ .text = "Raw Dump Partition 2 (Secure)", .callback = dumpPartitionRawMenuItem, .userdata = (void*) 2 },
{ .text = "View files on Game Card (SysUpdate)", .callback = viewPartitionMenuItem, .userdata = (void*) 0 },
{ .text = "View files on Game Card (Normal)", .callback = viewPartitionMenuItem, .userdata = (void*) 1 },
{ .text = "View files on Game Card (Secure)", .callback = viewPartitionMenuItem, .userdata = (void*) 2 },
{ .text = NULL }
};
void openMainMenu() {
menuSetCurrent(mainMenu, menuExit);
}
int main(int argc, char **argv) {
gfxInitDefault();
consoleInit(NULL);
if (R_FAILED(fsOpenDeviceOperator(&fsOperatorInstance))) {
printf("Failed to open device operator\n");
return -1;
}
openMainMenu();
while(appletMainLoop())
{
bool btnWait = shouldWaitForAnyButton;
hidScanInput();
if (!btnWait)
menuUpdate(&fsOperatorInstance);
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (kDown & KEY_PLUS) break;
if (btnWait && (kDown & (KEY_A | KEY_B | KEY_X | KEY_Y | KEY_L | KEY_R | KEY_ZL | KEY_ZR | KEY_MINUS |
KEY_DLEFT | KEY_DRIGHT | KEY_DUP | KEY_DDOWN))) {
shouldWaitForAnyButton = false;
menuPrint();
}
if (shouldExit)
break;
gfxFlushBuffers();
gfxSwapBuffers();
gfxWaitForVsync();
}
fsDeviceOperatorClose(&fsOperatorInstance);
u32 currentFBWidth, currentFBHeight;
u8 *currentFB;
int main(int argc, char **argv)
{
gfxInitResolutionDefault();
gfxInitDefault();
gfxConfigureAutoResolutionDefault(true);
uiInit();
currentFB = gfxGetFramebuffer(&currentFBWidth, &currentFBHeight);
int ret = 0;
if (R_SUCCEEDED(ncmInitialize()))
{
if (R_SUCCEEDED(nsInitialize()))
{
if (R_SUCCEEDED(fsOpenDeviceOperator(&fsOperatorInstance)))
{
bool exitLoop = false;
while(appletMainLoop())
{
currentFB = gfxGetFramebuffer(&currentFBWidth, &currentFBHeight);
gameCardInserted = isGameCardInserted(&fsOperatorInstance);
if (gameCardInserted)
{
if (hfs0_header == NULL)
{
// Don't access the gamecard immediately to avoid conflicts with the fs-srv, ncm and ns services
delay(1);
getRootHfs0Header(&fsOperatorInstance);
getGameCardTitleID(&gameCardTitleID);
getGameCardControlNacp(gameCardTitleID, gameCardName, sizeof(gameCardName), gameCardAuthor, sizeof(gameCardAuthor), gameCardVersion, sizeof(gameCardVersion));
}
} else {
if (hfs0_header != NULL)
{
gameCardSize = 0;
memset(gameCardSizeStr, 0, sizeof(gameCardSizeStr));
free(hfs0_header);
hfs0_header = NULL;
hfs0_offset = hfs0_size = 0;
hfs0_partition_cnt = 0;
gameCardTitleID = 0;
memset(gameCardName, 0, sizeof(gameCardName));
memset(gameCardAuthor, 0, sizeof(gameCardAuthor));
memset(gameCardVersion, 0, sizeof(gameCardVersion));
}
}
hidScanInput();
u32 keysDown = hidKeysDown(CONTROLLER_P1_AUTO);
UIResult result = uiLoop(keysDown);
switch(result)
{
case resultShowMainMenu:
uiSetState(stateMainMenu);
break;
case resultShowXciDumpMenu:
uiSetState(stateXciDumpMenu);
break;
case resultDumpXci:
uiSetState(stateDumpXci);
break;
case resultShowRawPartitionDumpMenu:
uiSetState(stateRawPartitionDumpMenu);
break;
case resultDumpRawPartition:
uiSetState(stateDumpRawPartition);
break;
case resultShowPartitionDataDumpMenu:
uiSetState(statePartitionDataDumpMenu);
break;
case resultDumpPartitionData:
uiSetState(stateDumpPartitionData);
break;
case resultShowViewGameCardFsMenu:
uiSetState(stateViewGameCardFsMenu);
break;
case resultShowViewGameCardFsGetList:
uiSetState(stateViewGameCardFsGetList);
break;
case resultShowViewGameCardFsBrowser:
uiSetState(stateViewGameCardFsBrowser);
break;
case resultViewGameCardFsBrowserCopyFile:
uiSetState(stateViewGameCardFsBrowserCopyFile);
break;
case resultDumpGameCardCertificate:
uiSetState(stateDumpGameCardCertificate);
break;
case resultExit:
exitLoop = true;
break;
default:
break;
}
if (exitLoop) break;
syncDisplay();
}
fsDeviceOperatorClose(&fsOperatorInstance);
} else {
uiDrawString("Failed to open device operator.", 0, 0, 255, 255, 255);
delay(5);
ret = -3;
}
nsExit();
} else {
uiDrawString("Failed to initialize the NS service.", 0, 0, 255, 255, 255);
delay(5);
ret = -2;
}
ncmExit();
} else {
uiDrawString("Failed to initialize the NCM service.", 0, 0, 255, 255, 255);
delay(5);
ret = -1;
}
if (hfs0_header != NULL) free(hfs0_header);
uiDeinit();
gfxExit();
return 0;
return ret;
}

View file

@ -1,79 +0,0 @@
#include "menu.h"
#include <stdio.h>
#include "ccolor.h"
#include "util.h"
MenuItem* menuCurrent;
int menuCurrentCount;
bool menuCardIsInserted;
int menuSelIndex = 0;
void (*menuExitCallback)();
void menuPrint() {
consoleClear();
printf(C_CYAN "Game Card dump tool" C_RESET "\n");
printf(menuCardIsInserted ? C_GREEN "Game Card is inserted\n" : C_RED "Game Card is NOT inserted\n");
printf(C_RESET "\n");
int index = 0;
MenuItem* menuItems = menuCurrent;
while (menuItems->text) {
if (index == menuSelIndex)
printf(C_INVERT "%s" C_RESET "\n", menuItems->text);
else
printf("%s\n", menuItems->text);
menuItems++;
index++;
}
}
bool menuHandleGameCardStatus(FsDeviceOperator* fsOperator) {
bool cardInserted = isGameCardInserted(fsOperator);
if (menuCardIsInserted != cardInserted) {
menuCardIsInserted = cardInserted;
return true;
}
return false;
}
int menuHandleInput() {
bool needsRefresh = false;
u64 keys = hidKeysDown(CONTROLLER_P1_AUTO);
if ((keys & KEY_A) && menuCurrent[menuSelIndex].callback != NULL) {
menuCurrent[menuSelIndex].callback(&menuCurrent[menuSelIndex]);
return -1;
}
if ((keys & KEY_B) && menuExitCallback != NULL) {
menuExitCallback();
return -1;
}
if (((keys & KEY_RSTICK_UP) | (keys & KEY_LSTICK_UP)) && menuSelIndex > 0) {
menuSelIndex--;
needsRefresh = true;
}
if (((keys & KEY_RSTICK_DOWN) | (keys & KEY_LSTICK_DOWN)) && menuSelIndex + 1 < menuCurrentCount) {
menuSelIndex++;
needsRefresh = true;
}
return needsRefresh ? 1 : 0;
}
void menuSetCurrent(MenuItem* menuItems, void (*exitCallback)()) {
menuExitCallback = exitCallback;
menuCurrent = menuItems;
menuCurrentCount = 0;
while ((menuItems++)->text != NULL)
menuCurrentCount++;
menuSelIndex = 0;
menuPrint();
}
void menuUpdate(FsDeviceOperator* fsOperator) {
int inputStatus = menuHandleInput();
if (inputStatus == -1)
return;
if (inputStatus || menuHandleGameCardStatus(fsOperator))
menuPrint();
}

View file

@ -1,13 +0,0 @@
#pragma once
#include <switch.h>
typedef struct _MenuItem {
char* text;
void (*callback)(struct _MenuItem* item);
void* userdata;
} MenuItem;
void menuPrint();
void menuSetCurrent(MenuItem* menuItems, void (*exitCallback)());
void menuUpdate(FsDeviceOperator* fsOperator);

170
source/ncmext.c Normal file
View file

@ -0,0 +1,170 @@
#include <switch/arm/atomics.h>
#include <switch/kernel/ipc.h>
#include <stdlib.h>
#include <string.h>
#include "ncmext.h"
static Service g_ncm;
static u64 g_refCnt;
// IContentManager
Result ncmInitialize(void)
{
atomicIncrement64(&g_refCnt);
if (serviceIsActive(&g_ncm)) return 0;
Result rc = smGetService(&g_ncm, "ncm");
return rc;
}
void ncmExit(void)
{
if (atomicDecrement64(&g_refCnt) == 0) serviceClose(&g_ncm);
}
Result ncmGetContentMetaDatabase(ncmContentMetaDatabase *out, FsStorageId storage_id)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u8 storage_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 5;
raw->storage_id = storage_id;
Result rc = serviceIpcDispatch(&g_ncm);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) serviceCreate(&out->s, r.Handles[0]);
}
return rc;
}
Result ncmOpenContentMetaDatabase(FsStorageId storage_id)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u8 storage_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 11;
raw->storage_id = storage_id;
Result rc = serviceIpcDispatch(&g_ncm);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
}
return rc;
}
Result ncmCloseContentMetaDatabase(FsStorageId storage_id)
{
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u8 storage_id;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 12;
raw->storage_id = storage_id;
Result rc = serviceIpcDispatch(&g_ncm);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
}
return rc;
}
// IContentMetaDatabase
Result ncmMetaDatabaseListApplication(ncmContentMetaDatabase *md, ncmApplicationMetaKey *buffer, size_t size, u8 filter)
{
IpcCommand c;
ipcInitialize(&c);
ipcAddRecvBuffer(&c, buffer, size, BufferType_Normal);
struct {
u64 magic;
u64 cmd_id;
u8 filter;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 7;
raw->filter = filter;
Result rc = serviceIpcDispatch(&md->s);
if (R_SUCCEEDED(rc))
{
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
} *resp = r.Raw;
rc = resp->result;
}
return rc;
}

36
source/ncmext.h Normal file
View file

@ -0,0 +1,36 @@
#pragma once
#ifndef __NCMEXT_H__
#define __NCMEXT_H__
#include <switch/types.h>
#include <switch/services/fs.h>
typedef struct {
Service s;
} ncmContentMetaDatabase;
typedef struct {
u64 titleID;
u32 titleVersion;
u8 type;
u8 unk1;
u16 unk2;
} ncmContentMetaKey;
typedef struct {
ncmContentMetaKey meta_record;
u64 base_title_id;
} ncmApplicationMetaKey;
// IContentManager
Result ncmInitialize(void);
void ncmExit(void);
Result ncmGetContentMetaDatabase(ncmContentMetaDatabase *out, FsStorageId storage_id);
Result ncmOpenContentMetaDatabase(FsStorageId storage_id);
Result ncmCloseContentMetaDatabase(FsStorageId storage_id);
// IContentMetaDatabase
Result ncmMetaDatabaseListApplication(ncmContentMetaDatabase *md, ncmApplicationMetaKey *buffer, size_t size, u8 filter);
#endif

730
source/ui.c Normal file
View file

@ -0,0 +1,730 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <switch.h>
#include "dumper.h"
#include "fsext.h"
#include "ui.h"
#include "util.h"
extern FsDeviceOperator fsOperatorInstance;
extern bool gameCardInserted;
extern u32 currentFBWidth, currentFBHeight;
extern u8 *currentFB;
extern char gameCardSizeStr[32];
extern char *hfs0_header;
extern u64 hfs0_offset, hfs0_size;
extern u32 hfs0_partition_cnt;
extern u64 gameCardTitleID;
extern char gameCardName[0x201], gameCardAuthor[0x101], gameCardVersion[0x11];
static u32 selectedOption;
static char statusMessage[2048] = {'\0'};
static int statusMessageFadeout = 0;
static char fileCopyPath[NAME_BUF_LEN * 2] = {'\0'};
static char currentDirectory[NAME_BUF_LEN] = {'\0'};
static int cursor = 0;
static int scroll = 0;
static int headlineCnt = 0;
int breaks = 0;
u64 freeSpace = 0;
static char freeSpaceStr[64] = {'\0'};
static char titlebuf[NAME_BUF_LEN * 2] = {'\0'};
static const int maxListElements = 45;
static char *filenameBuffer = NULL;
static char *filenames[FILENAMES_COUNT_MAX];
static int filenamesCount = 0;
static UIState uiState;
static const char *appHeadline = "Nintendo Switch Game Card Dump Tool v" APP_VERSION ".\nOriginal code by MCMrARM.\nAdditional modifications by DarkMatterCore.\n\n";
static const char *appControls = "[D-Pad / Analog Stick] Move | [A] Select | [B] Back | [+] Exit";
static const char *mainMenuItems[] = { "Raw XCI Dump (Full)", "Raw Partition Dump", "Partition Data Dump", "View Game Card Files", "Dump Game Card Certificate" };
static const char *xciDumpMenuItems[] = { "Full Dump with Certificate (exFAT)", "Full Dump without Certificate (exFAT)", "Full Dump with Certificate (FAT32 - 2 GiB chunks)", "Full Dump without Certificate (FAT32 - 2 GiB chunks)" };
static const char *partitionDumpType1MenuItems[] = { "Dump Partition 0 (SysUpdate)", "Dump Partition 1 (Normal)", "Dump Partition 2 (Secure)" };
static const char *partitionDumpType2MenuItems[] = { "Dump Partition 0 (SysUpdate)", "Dump Partition 1 (Logo)", "Dump Partition 2 (Normal)", "Dump Partition 3 (Secure)" };
static const char *viewGameCardFsType1MenuItems[] = { "View Files from Partition 0 (SysUpdate)", "View Files from Partition 1 (Normal)", "View Files from Partition 2 (Secure)" };
static const char *viewGameCardFsType2MenuItems[] = { "View Files from Partition 0 (SysUpdate)", "View Files from Partition 1 (Logo)", "View Files from Partition 2 (Normal)", "View Files from Partition 3 (Secure)" };
static unsigned char asciiData[128][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x3E, 0x41, 0x55, 0x41, 0x55, 0x49, 0x3E},
{0x00, 0x3E, 0x7F, 0x6B, 0x7F, 0x6B, 0x77, 0x3E}, {0x00, 0x22, 0x77, 0x7F, 0x7F, 0x3E, 0x1C, 0x08},
{0x00, 0x08, 0x1C, 0x3E, 0x7F, 0x3E, 0x1C, 0x08}, {0x00, 0x08, 0x1C, 0x2A, 0x7F, 0x2A, 0x08, 0x1C},
{0x00, 0x08, 0x1C, 0x3E, 0x7F, 0x3E, 0x08, 0x1C}, {0x00, 0x00, 0x1C, 0x3E, 0x3E, 0x3E, 0x1C, 0x00},
{0xFF, 0xFF, 0xE3, 0xC1, 0xC1, 0xC1, 0xE3, 0xFF}, {0x00, 0x00, 0x1C, 0x22, 0x22, 0x22, 0x1C, 0x00},
{0xFF, 0xFF, 0xE3, 0xDD, 0xDD, 0xDD, 0xE3, 0xFF}, {0x00, 0x0F, 0x03, 0x05, 0x39, 0x48, 0x48, 0x30},
{0x00, 0x08, 0x3E, 0x08, 0x1C, 0x22, 0x22, 0x1C}, {0x00, 0x18, 0x14, 0x10, 0x10, 0x30, 0x70, 0x60},
{0x00, 0x0F, 0x19, 0x11, 0x13, 0x37, 0x76, 0x60}, {0x00, 0x08, 0x2A, 0x1C, 0x77, 0x1C, 0x2A, 0x08},
{0x00, 0x60, 0x78, 0x7E, 0x7F, 0x7E, 0x78, 0x60}, {0x00, 0x03, 0x0F, 0x3F, 0x7F, 0x3F, 0x0F, 0x03},
{0x00, 0x08, 0x1C, 0x2A, 0x08, 0x2A, 0x1C, 0x08}, {0x00, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66},
{0x00, 0x3F, 0x65, 0x65, 0x3D, 0x05, 0x05, 0x05}, {0x00, 0x0C, 0x32, 0x48, 0x24, 0x12, 0x4C, 0x30},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F}, {0x00, 0x08, 0x1C, 0x2A, 0x08, 0x2A, 0x1C, 0x3E},
{0x00, 0x08, 0x1C, 0x3E, 0x7F, 0x1C, 0x1C, 0x1C}, {0x00, 0x1C, 0x1C, 0x1C, 0x7F, 0x3E, 0x1C, 0x08},
{0x00, 0x08, 0x0C, 0x7E, 0x7F, 0x7E, 0x0C, 0x08}, {0x00, 0x08, 0x18, 0x3F, 0x7F, 0x3F, 0x18, 0x08},
{0x00, 0x00, 0x00, 0x70, 0x70, 0x70, 0x7F, 0x7F}, {0x00, 0x00, 0x14, 0x22, 0x7F, 0x22, 0x14, 0x00},
{0x00, 0x08, 0x1C, 0x1C, 0x3E, 0x3E, 0x7F, 0x7F}, {0x00, 0x7F, 0x7F, 0x3E, 0x3E, 0x1C, 0x1C, 0x08},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18},
{0x00, 0x36, 0x36, 0x14, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36},
{0x00, 0x08, 0x1E, 0x20, 0x1C, 0x02, 0x3C, 0x08}, {0x00, 0x60, 0x66, 0x0C, 0x18, 0x30, 0x66, 0x06},
{0x00, 0x3C, 0x66, 0x3C, 0x28, 0x65, 0x66, 0x3F}, {0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00},
{0x00, 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06}, {0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60},
{0x00, 0x00, 0x36, 0x1C, 0x7F, 0x1C, 0x36, 0x00}, {0x00, 0x00, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x60}, {0x00, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60}, {0x00, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00},
{0x00, 0x3C, 0x66, 0x6E, 0x76, 0x66, 0x66, 0x3C}, {0x00, 0x18, 0x18, 0x38, 0x18, 0x18, 0x18, 0x7E},
{0x00, 0x3C, 0x66, 0x06, 0x0C, 0x30, 0x60, 0x7E}, {0x00, 0x3C, 0x66, 0x06, 0x1C, 0x06, 0x66, 0x3C},
{0x00, 0x0C, 0x1C, 0x2C, 0x4C, 0x7E, 0x0C, 0x0C}, {0x00, 0x7E, 0x60, 0x7C, 0x06, 0x06, 0x66, 0x3C},
{0x00, 0x3C, 0x66, 0x60, 0x7C, 0x66, 0x66, 0x3C}, {0x00, 0x7E, 0x66, 0x0C, 0x0C, 0x18, 0x18, 0x18},
{0x00, 0x3C, 0x66, 0x66, 0x3C, 0x66, 0x66, 0x3C}, {0x00, 0x3C, 0x66, 0x66, 0x3E, 0x06, 0x66, 0x3C},
{0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00}, {0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x30},
{0x00, 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06}, {0x00, 0x00, 0x00, 0x3C, 0x00, 0x3C, 0x00, 0x00},
{0x00, 0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60}, {0x00, 0x3C, 0x66, 0x06, 0x1C, 0x18, 0x00, 0x18},
{0x00, 0x38, 0x44, 0x5C, 0x58, 0x42, 0x3C, 0x00}, {0x00, 0x3C, 0x66, 0x66, 0x7E, 0x66, 0x66, 0x66},
{0x00, 0x7C, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x7C}, {0x00, 0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C},
{0x00, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C}, {0x00, 0x7E, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x7E},
{0x00, 0x7E, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60}, {0x00, 0x3C, 0x66, 0x60, 0x60, 0x6E, 0x66, 0x3C},
{0x00, 0x66, 0x66, 0x66, 0x7E, 0x66, 0x66, 0x66}, {0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C},
{0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0x6C, 0x6C, 0x38}, {0x00, 0x66, 0x6C, 0x78, 0x70, 0x78, 0x6C, 0x66},
{0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7E}, {0x00, 0x63, 0x77, 0x7F, 0x6B, 0x63, 0x63, 0x63},
{0x00, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x63, 0x63}, {0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C},
{0x00, 0x7C, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60}, {0x00, 0x3C, 0x66, 0x66, 0x66, 0x6E, 0x3C, 0x06},
{0x00, 0x7C, 0x66, 0x66, 0x7C, 0x78, 0x6C, 0x66}, {0x00, 0x3C, 0x66, 0x60, 0x3C, 0x06, 0x66, 0x3C},
{0x00, 0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18}, {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3E},
{0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18}, {0x00, 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63},
{0x00, 0x63, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x63}, {0x00, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18},
{0x00, 0x7E, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x7E}, {0x00, 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E},
{0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x00}, {0x00, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78},
{0x00, 0x08, 0x14, 0x22, 0x41, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F},
{0x00, 0x0C, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x3C, 0x06, 0x3E, 0x66, 0x3E},
{0x00, 0x60, 0x60, 0x60, 0x7C, 0x66, 0x66, 0x7C}, {0x00, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x66, 0x3C},
{0x00, 0x06, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3E}, {0x00, 0x00, 0x00, 0x3C, 0x66, 0x7E, 0x60, 0x3C},
{0x00, 0x1C, 0x36, 0x30, 0x30, 0x7C, 0x30, 0x30}, {0x00, 0x00, 0x3E, 0x66, 0x66, 0x3E, 0x06, 0x3C},
{0x00, 0x60, 0x60, 0x60, 0x7C, 0x66, 0x66, 0x66}, {0x00, 0x00, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3C},
{0x00, 0x0C, 0x00, 0x0C, 0x0C, 0x6C, 0x6C, 0x38}, {0x00, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0x66},
{0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18}, {0x00, 0x00, 0x00, 0x63, 0x77, 0x7F, 0x6B, 0x6B},
{0x00, 0x00, 0x00, 0x7C, 0x7E, 0x66, 0x66, 0x66}, {0x00, 0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x3C},
{0x00, 0x00, 0x7C, 0x66, 0x66, 0x7C, 0x60, 0x60}, {0x00, 0x00, 0x3C, 0x6C, 0x6C, 0x3C, 0x0D, 0x0F},
{0x00, 0x00, 0x00, 0x7C, 0x66, 0x66, 0x60, 0x60}, {0x00, 0x00, 0x00, 0x3E, 0x40, 0x3C, 0x02, 0x7C},
{0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18}, {0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3E},
{0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x3C, 0x18}, {0x00, 0x00, 0x00, 0x63, 0x6B, 0x6B, 0x6B, 0x3E},
{0x00, 0x00, 0x00, 0x66, 0x3C, 0x18, 0x3C, 0x66}, {0x00, 0x00, 0x00, 0x66, 0x66, 0x3E, 0x06, 0x3C},
{0x00, 0x00, 0x00, 0x3C, 0x0C, 0x18, 0x30, 0x3C}, {0x00, 0x0E, 0x18, 0x18, 0x30, 0x18, 0x18, 0x0E},
{0x00, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18}, {0x00, 0x70, 0x18, 0x18, 0x0C, 0x18, 0x18, 0x70},
{0x00, 0x00, 0x00, 0x3A, 0x6C, 0x00, 0x00, 0x00}, {0x00, 0x08, 0x1C, 0x36, 0x63, 0x41, 0x41, 0x7F}
};
int uiGetIndex(int x, int y)
{
return (x + y * currentFBWidth) * 4;
}
void uiFill(int x, int y, int width, int height, u8 r, u8 g, u8 b)
{
if (currentFB == NULL) return;
if (x + width < 0 || y + height < 0 || x >= currentFBWidth || y >= currentFBHeight) return;
if (x < 0)
{
width += x;
x = 0;
}
if (y < 0)
{
height += y;
y = 0;
}
if (x + width >= currentFBWidth) width = currentFBWidth - x;
if (y + height >= currentFBHeight) height = currentFBHeight - y;
u8 colorLine[width * 4];
for (int ly = 0; ly < width; ly++)
{
colorLine[ly * 4 + 0] = r;
colorLine[ly * 4 + 1] = g;
colorLine[ly * 4 + 2] = b;
colorLine[ly * 4 + 3] = 255;
}
u8* fbAddr = currentFB + uiGetIndex(x, y); // - (width * 4);
for (int dx = 0; dx < height; dx++)
{
memcpy(fbAddr, colorLine, (size_t)(width * 4));
fbAddr += currentFBWidth * 4;
}
}
void uiDrawChar(char c, int x, int y, u8 r, u8 g, u8 b)
{
if (currentFB == NULL) return;
if (c & 0x80) c = '?'; // Unicode chars
unsigned char* data = asciiData[(int)c];
for (int cy = 0; cy < 8; cy++)
{
if (y + cy < 0 || y + cy >= currentFBHeight) continue;
unsigned char l = data[cy];
for (int cx = 0; cx < 8; cx++)
{
if (x + cx < 0 || x + cx >= currentFBWidth) continue;
if ((0b10000000 >> cx) & l)
{
u8* ptr = &currentFB[uiGetIndex(x + cx, y + cy)];
*(ptr + 0) = r;
*(ptr + 1) = g;
*(ptr + 2) = b;
*(ptr + 3) = 255;
}
}
}
}
void uiDrawString(const char* string, int x, int y, u8 r, u8 g, u8 b)
{
if (currentFB == NULL) return;
int len = (int)strlen(string);
int cx = x;
int cy = y;
for (int i = 0; i < len; i++)
{
char c = string[i];
if (c == '\n')
{
cx = x;
cy += 8;
} else {
uiDrawChar(c, cx, cy, r, g, b);
cx += 8;
}
if (cx > (currentFBWidth - 8)) break;
}
}
void uiStatusMsg(const char* format, ...)
{
statusMessageFadeout = 500;
va_list args;
va_start(args, format);
vsnprintf(statusMessage, sizeof(statusMessage) / sizeof(statusMessage[0]), format, args);
va_end(args);
//printf("Status message: %s\n", statusMessage);
}
void uiUpdateFreeSpace()
{
getSdCardFreeSpace(&freeSpace);
char tmp[32] = {'\0'};
convertSize(freeSpace, tmp, sizeof(tmp) / sizeof(tmp[0]));
snprintf(freeSpaceStr, sizeof(freeSpaceStr) / sizeof(freeSpaceStr[0]), "Free SD card space: %s.", tmp);
}
void uiInit()
{
uiState = stateMainMenu;
cursor = 0;
scroll = 0;
headlineCnt = 0;
filenameBuffer = (char*)malloc(FILENAMEBUFFER_SIZE);
int i, headlineLen = strlen(appHeadline);
for(i = 0; i < headlineLen; i++)
{
if (appHeadline[i] == '\n') headlineCnt++;
}
if (!headlineCnt) headlineCnt = 2;
uiUpdateFreeSpace();
}
void uiDeinit()
{
if (filenameBuffer) free(filenameBuffer);
if (uiState == stateViewGameCardFsBrowser) fsdevUnmountDevice("view");
}
void uiSetState(UIState state)
{
uiState = state;
cursor = 0;
scroll = 0;
}
UIState uiGetState()
{
return uiState;
}
void uiClearScreen()
{
uiFill(0, 0, currentFBWidth, currentFBHeight, 50, 50, 50);
}
static void enterDirectory(const char *path)
{
snprintf(currentDirectory, sizeof(currentDirectory) / sizeof(currentDirectory[0]), "%s", path);
filenamesCount = FILENAMES_COUNT_MAX;
getDirectoryContents(filenameBuffer, &filenames[0], &filenamesCount, currentDirectory, (!strcmp(currentDirectory, "view:/") && strlen(currentDirectory) == 6));
cursor = 0;
scroll = 0;
}
UIResult uiLoop(u32 keysDown)
{
UIResult res = resultNone;
uiClearScreen();
uiDrawString(appHeadline, 0, 0, 255, 255, 255);
int i;
breaks = headlineCnt;
if (uiState == stateMainMenu || uiState == stateXciDumpMenu || uiState == stateRawPartitionDumpMenu || uiState == statePartitionDataDumpMenu || uiState == stateViewGameCardFsMenu || uiState == stateViewGameCardFsBrowser)
{
// Exit
if (keysDown & KEY_PLUS) return resultExit;
uiDrawString(appControls, 0, breaks * 8, 255, 255, 255);
breaks += 2;
uiDrawString(freeSpaceStr, 0, breaks * 8, 255, 255, 255);
breaks += 2;
if (uiState != stateViewGameCardFsBrowser)
{
if (gameCardInserted && hfs0_header != NULL && (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT || hfs0_partition_cnt == GAMECARD_TYPE2_PARTITION_CNT))
{
uiDrawString("Game Card is inserted!", 0, breaks * 8, 0, 255, 0);
breaks += 2;
/*snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Root HFS0 header offset: 0x%016lX", hfs0_offset);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Root HFS0 header size: 0x%016lX", hfs0_size);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;*/
if (strlen(gameCardName) && strlen(gameCardAuthor))
{
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Name: %s", gameCardName);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Developer: %s", gameCardAuthor);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;
}
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Title ID: %016lX", gameCardTitleID);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;
if (strlen(gameCardVersion))
{
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Version: %s", gameCardVersion);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;
}
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Size: %s", gameCardSizeStr);
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
breaks++;
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Partition count: %u (%s)", hfs0_partition_cnt, GAMECARD_TYPE(hfs0_partition_cnt));
uiDrawString(titlebuf, 0, breaks * 8, 0, 255, 0);
} else {
if (gameCardInserted)
{
if (hfs0_header != NULL)
{
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Error: unknown root HFS0 header partition count! (%u)", hfs0_partition_cnt);
uiDrawString(titlebuf, 0, breaks * 8, 255, 0, 0);
} else {
uiDrawString("Error: unable to get root HFS0 header data!", 0, breaks * 8, 255, 0, 0);
}
} else {
uiDrawString("Game Card is not inserted!", 0, breaks * 8, 255, 0, 0);
}
res = resultShowMainMenu;
}
breaks += 2;
}
if (gameCardInserted && hfs0_header != NULL && (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT || hfs0_partition_cnt == GAMECARD_TYPE2_PARTITION_CNT))
{
const char **menu = NULL;
int menuItemsCount;
switch(uiState)
{
case stateMainMenu:
menu = mainMenuItems;
menuItemsCount = sizeof(mainMenuItems) / sizeof(mainMenuItems[0]);
break;
case stateXciDumpMenu:
menu = xciDumpMenuItems;
menuItemsCount = sizeof(xciDumpMenuItems) / sizeof(xciDumpMenuItems[0]);
uiDrawString(mainMenuItems[0], 0, breaks * 8, 115, 115, 255);
break;
case stateRawPartitionDumpMenu:
case statePartitionDataDumpMenu:
menu = (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? partitionDumpType1MenuItems : partitionDumpType2MenuItems);
menuItemsCount = (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? (sizeof(partitionDumpType1MenuItems) / sizeof(partitionDumpType1MenuItems[0])) : (sizeof(partitionDumpType2MenuItems) / sizeof(partitionDumpType2MenuItems[0])));
uiDrawString((uiState == stateRawPartitionDumpMenu ? mainMenuItems[1] : mainMenuItems[2]), 0, breaks * 8, 115, 115, 255);
break;
case stateViewGameCardFsMenu:
menu = (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? viewGameCardFsType1MenuItems : viewGameCardFsType2MenuItems);
menuItemsCount = (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? (sizeof(viewGameCardFsType1MenuItems) / sizeof(viewGameCardFsType1MenuItems[0])) : (sizeof(viewGameCardFsType2MenuItems) / sizeof(viewGameCardFsType2MenuItems[0])));
uiDrawString(mainMenuItems[3], 0, breaks * 8, 115, 115, 255);
break;
case stateViewGameCardFsBrowser:
menu = (const char**)filenames;
menuItemsCount = filenamesCount;
uiDrawString((hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? viewGameCardFsType1MenuItems[selectedOption] : viewGameCardFsType2MenuItems[selectedOption]), 0, breaks * 8, 115, 115, 255);
breaks += 2;
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Current directory: %s", currentDirectory);
uiDrawString(titlebuf, 0, breaks * 8, 255, 255, 255);
break;
default:
break;
}
if (menu && menuItemsCount)
{
if (uiState != stateMainMenu) breaks += 2;
int scrollAmount = 0;
if ((keysDown & KEY_DOWN) || (keysDown & KEY_RSTICK_DOWN) || (keysDown & KEY_LSTICK_DOWN)) scrollAmount = 1;
if ((keysDown & KEY_UP) || (keysDown & KEY_RSTICK_UP) || (keysDown & KEY_LSTICK_UP)) scrollAmount = -1;
if ((keysDown & KEY_LEFT) || (keysDown & KEY_RSTICK_LEFT) || (keysDown & KEY_LSTICK_LEFT)) scrollAmount = -5;
if ((keysDown & KEY_RIGHT) || (keysDown & KEY_RSTICK_RIGHT) || (keysDown & KEY_LSTICK_RIGHT)) scrollAmount = 5;
if (scrollAmount > 0)
{
for (i = 0; i < scrollAmount; i++)
{
if (cursor < menuItemsCount - 1)
{
cursor++;
if ((cursor - scroll) >= maxListElements) scroll++;
}
}
} else
if (scrollAmount < 0)
{
for (i = 0; i < -scrollAmount; i++)
{
if (cursor > 0)
{
cursor--;
if ((cursor - scroll) < 0) scroll--;
}
}
}
i = 0;
for (int j = scroll; j < menuItemsCount; j++)
{
u8 color = 255;
if (i + scroll == cursor)
{
uiFill(0, (breaks * 8) + (i * 13), currentFBWidth / 2, 13, 33, 34, 39);
uiDrawString(menu[j], 0, (breaks * 8) + (i * 13) + 2, 0, 255, 197);
} else {
uiDrawString(menu[j], 0, (breaks * 8) + (i * 13) + 2, color, color, color);
}
i++;
if (i >= maxListElements) break;
}
// Select
if (keysDown & KEY_A)
{
if (uiState == stateMainMenu)
{
switch(cursor)
{
case 0:
res = resultShowXciDumpMenu;
break;
case 1:
res = resultShowRawPartitionDumpMenu;
break;
case 2:
res = resultShowPartitionDataDumpMenu;
break;
case 3:
res = resultShowViewGameCardFsMenu;
break;
case 4:
res = resultDumpGameCardCertificate;
break;
default:
break;
}
} else
if (uiState == stateXciDumpMenu)
{
selectedOption = (u32)cursor;
res = resultDumpXci;
} else
if (uiState == stateRawPartitionDumpMenu)
{
selectedOption = (u32)cursor;
res = resultDumpRawPartition;
} else
if (uiState == statePartitionDataDumpMenu)
{
selectedOption = (u32)cursor;
res = resultDumpPartitionData;
} else
if (uiState == stateViewGameCardFsMenu)
{
selectedOption = (u32)cursor;
res = resultShowViewGameCardFsGetList;
} else
if (uiState == stateViewGameCardFsBrowser)
{
char *selectedPath = (char*)malloc(strlen(currentDirectory) + 1 + strlen(filenames[cursor]) + 2);
memset(selectedPath, 0, strlen(currentDirectory) + 1 + strlen(filenames[cursor]) + 2);
if (strlen(filenames[cursor]) == 2 && !strcmp(filenames[cursor], ".."))
{
for(i = (strlen(currentDirectory) - 1); i >= 0; i--)
{
if (currentDirectory[i] == '/')
{
strncpy(selectedPath, currentDirectory, i);
selectedPath[i] = '\0';
break;
}
}
} else {
snprintf(selectedPath, strlen(currentDirectory) + 1 + strlen(filenames[cursor]) + 2, "%s/%s", currentDirectory, filenames[cursor]);
}
if (isDirectory(selectedPath))
{
enterDirectory(selectedPath);
} else {
snprintf(fileCopyPath, sizeof(fileCopyPath) / sizeof(fileCopyPath[0]), "%s", selectedPath);
res = resultViewGameCardFsBrowserCopyFile;
}
free(selectedPath);
}
}
// Back
if (keysDown & KEY_B)
{
if (uiState == stateXciDumpMenu || uiState == stateRawPartitionDumpMenu || uiState == statePartitionDataDumpMenu || uiState == stateViewGameCardFsMenu)
{
res = resultShowMainMenu;
} else
if (uiState == stateViewGameCardFsBrowser)
{
if (!strcmp(currentDirectory, "view:/") && strlen(currentDirectory) == 6)
{
fsdevUnmountDevice("view");
res = resultShowViewGameCardFsMenu;
} else {
char *selectedPath = (char*)malloc(strlen(currentDirectory) + 1);
memset(selectedPath, 0, strlen(currentDirectory) + 1);
for(i = (strlen(currentDirectory) - 1); i >= 0; i--)
{
if (currentDirectory[i] == '/')
{
strncpy(selectedPath, currentDirectory, i);
selectedPath[i] = '\0';
break;
}
}
if (isDirectory(selectedPath)) enterDirectory(selectedPath);
free(selectedPath);
}
}
}
}
}
} else
if (uiState == stateDumpXci)
{
uiDrawString(xciDumpMenuItems[selectedOption], 0, breaks * 8, 115, 115, 255);
breaks += 2;
bool isFat32 = (selectedOption == 2 || selectedOption == 3);
bool dumpCert = (selectedOption == 0 || selectedOption == 2);
dumpGameCartridge(&fsOperatorInstance, isFat32, dumpCert);
waitForButtonPress();
uiUpdateFreeSpace();
res = resultShowXciDumpMenu;
} else
if (uiState == stateDumpRawPartition)
{
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Raw %s", (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? partitionDumpType1MenuItems[selectedOption] : partitionDumpType2MenuItems[selectedOption]));
uiDrawString(titlebuf, 0, breaks * 8, 115, 115, 255);
breaks += 2;
dumpRawPartition(&fsOperatorInstance, selectedOption, true);
waitForButtonPress();
uiUpdateFreeSpace();
res = resultShowRawPartitionDumpMenu;
} else
if (uiState == stateDumpPartitionData)
{
snprintf(titlebuf, sizeof(titlebuf) / sizeof(titlebuf[0]), "Data %s", (hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? partitionDumpType1MenuItems[selectedOption] : partitionDumpType2MenuItems[selectedOption]));
uiDrawString(titlebuf, 0, breaks * 8, 115, 115, 255);
breaks += 2;
dumpPartitionData(&fsOperatorInstance, selectedOption);
waitForButtonPress();
uiUpdateFreeSpace();
res = resultShowPartitionDataDumpMenu;
} else
if (uiState == stateViewGameCardFsGetList)
{
uiDrawString((hfs0_partition_cnt == GAMECARD_TYPE1_PARTITION_CNT ? viewGameCardFsType1MenuItems[selectedOption] : viewGameCardFsType1MenuItems[selectedOption]), 0, breaks * 8, 115, 115, 255);
breaks += 2;
if (mountViewPartition(&fsOperatorInstance, selectedOption))
{
enterDirectory("view:/");
res = resultShowViewGameCardFsBrowser;
} else {
breaks += 2;
waitForButtonPress();
res = resultShowViewGameCardFsMenu;
}
} else
if (uiState == stateViewGameCardFsBrowserCopyFile)
{
uiDrawString("Manual File Dump", 0, breaks * 8, 115, 115, 255);
breaks += 2;
FILE *inFile = fopen(fileCopyPath, "rb");
if (inFile)
{
fseek(inFile, 0L, SEEK_END);
u64 input_filesize = ftell(inFile);
fclose(inFile);
if (input_filesize <= freeSpace)
{
char destCopyPath[NAME_BUF_LEN] = {'\0'};
for(i = (strlen(fileCopyPath) - 1); i >= 0; i--)
{
if (fileCopyPath[i] == '/')
{
snprintf(destCopyPath, sizeof(destCopyPath) / sizeof(destCopyPath[0]), "sdmc:/%.*s", (int)(strlen(fileCopyPath) - i), fileCopyPath + i + 1);
break;
}
}
uiDrawString("Hold B to cancel", 0, breaks * 8, 255, 255, 255);
breaks += 2;
if (copyFile(fileCopyPath, destCopyPath, true))
{
breaks += 7;
uiDrawString("Process successfully completed!", 0, breaks * 8, 0, 255, 0);
}
} else {
uiDrawString("Error: not enough free space available in the SD card.", 0, breaks * 8, 255, 0, 0);
}
} else {
uiDrawString("Error: unable to get input file size.", 0, breaks * 8, 255, 0, 0);
}
breaks += 2;
waitForButtonPress();
uiUpdateFreeSpace();
res = resultShowViewGameCardFsBrowser;
} else
if (uiState == stateDumpGameCardCertificate)
{
uiDrawString(mainMenuItems[4], 0, breaks * 8, 115, 115, 255);
breaks += 2;
dumpGameCertificate(&fsOperatorInstance);
waitForButtonPress();
uiUpdateFreeSpace();
res = resultShowMainMenu;
}
if (statusMessageFadeout > 0)
{
int fadeout = (statusMessageFadeout > 255 ? 255 : statusMessageFadeout);
uiDrawString(statusMessage, 4, currentFBHeight - 12, fadeout, fadeout, fadeout);
statusMessageFadeout -= 4;
}
return res;
}

57
source/ui.h Normal file
View file

@ -0,0 +1,57 @@
#pragma once
#ifndef __UI_H__
#define __UI_H__
#define FILENAMEBUFFER_SIZE (1024 * 32) // 32 KiB
#define FILENAMES_COUNT_MAX 2048
typedef enum {
resultNone,
resultShowMainMenu,
resultShowXciDumpMenu,
resultDumpXci,
resultShowRawPartitionDumpMenu,
resultDumpRawPartition,
resultShowPartitionDataDumpMenu,
resultDumpPartitionData,
resultShowViewGameCardFsMenu,
resultShowViewGameCardFsGetList,
resultShowViewGameCardFsBrowser,
resultViewGameCardFsBrowserCopyFile,
resultDumpGameCardCertificate,
resultExit
} UIResult;
typedef enum {
stateMainMenu,
stateXciDumpMenu,
stateDumpXci,
stateRawPartitionDumpMenu,
stateDumpRawPartition,
statePartitionDataDumpMenu,
stateDumpPartitionData,
stateViewGameCardFsMenu,
stateViewGameCardFsGetList,
stateViewGameCardFsBrowser,
stateViewGameCardFsBrowserCopyFile,
stateDumpGameCardCertificate
} UIState;
void uiStatusMsg(const char* fmt, ...);
void uiFill(int x, int y, int width, int height, u8 r, u8 g, u8 b);
void uiDrawString(const char* string, int x, int y, u8 r, u8 g, u8 b);
void uiUpdateFreeSpace();
void uiInit();
void uiDeinit();
void uiSetState(UIState state);
UIState uiGetState();
void uiClearScreen();
UIResult uiLoop(u32 keysDown);
#endif

View file

@ -1,14 +1,280 @@
#include "util.h"
#include "fsext.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
#include <time.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <switch/services/ns.h>
bool isGameCardInserted(FsDeviceOperator* o) {
#include "fsext.h"
#include "ncmext.h"
#include "ui.h"
#include "util.h"
extern int breaks;
bool isGameCardInserted(FsDeviceOperator* o)
{
bool inserted;
if (R_FAILED(fsDeviceOperatorIsGameCardInserted(o, &inserted)))
return false;
if (R_FAILED(fsDeviceOperatorIsGameCardInserted(o, &inserted))) return false;
return inserted;
}
void syncDisplay() {
void syncDisplay()
{
gfxFlushBuffers();
gfxSwapBuffers();
gfxWaitForVsync();
}
}
void delay(u8 seconds)
{
if (!seconds) return;
time_t timer;
time(&timer);
while(time(NULL) < (timer + seconds)) syncDisplay();
}
bool getGameCardTitleID(u64 *titleID)
{
bool success = false;
Result result;
ncmContentMetaDatabase ncmDb;
ncmApplicationMetaKey *appList = (ncmApplicationMetaKey*)malloc(sizeof(ncmApplicationMetaKey));
if (appList)
{
memset(appList, 0, sizeof(ncmApplicationMetaKey));
if (R_SUCCEEDED(result = ncmOpenContentMetaDatabase(FsStorageId_GameCard)))
{
if (R_SUCCEEDED(result = ncmGetContentMetaDatabase(&ncmDb, FsStorageId_GameCard)))
{
if (R_SUCCEEDED(result = ncmMetaDatabaseListApplication(&ncmDb, appList, sizeof(ncmApplicationMetaKey), 0)))
{
*titleID = appList->meta_record.titleID;
success = true;
} else {
uiStatusMsg("MetaDatabaseListApplication failed! (0x%08x)", result);
}
} else {
uiStatusMsg("GetContentMetaDatabase failed! (0x%08x)", result);
}
} else {
uiStatusMsg("OpenContentMetaDatabase failed! (0x%08x)", result);
}
// Seems to cause problems
//if (R_FAILED(result = ncmCloseContentMetaDatabase(FsStorageId_GameCard))) uiStatusMsg("CloseContentMetaDatabase failed! (0x%08x)", result);
free(appList);
} else {
uiStatusMsg("Unable to allocate memory for the NCM service operations.");
}
return success;
}
bool getGameCardControlNacp(u64 titleID, char *nameBuf, int nameBufSize, char *authorBuf, int authorBufSize, char *versionBuf, int versionBufSize)
{
if (titleID == 0) return false;
bool success = false;
Result result;
size_t outsize = 0;
NsApplicationControlData *buf = NULL;
NacpLanguageEntry *langentry = NULL;
buf = (NsApplicationControlData*)malloc(sizeof(NsApplicationControlData));
if (buf)
{
memset(buf, 0, sizeof(NsApplicationControlData));
if (R_SUCCEEDED(result = nsGetApplicationControlData(1, titleID, buf, sizeof(NsApplicationControlData), &outsize)))
{
if (outsize >= sizeof(buf->nacp))
{
if (R_SUCCEEDED(result = nacpGetLanguageEntry(&buf->nacp, &langentry)))
{
strncpy(nameBuf, langentry->name, nameBufSize - 1);
strncpy(authorBuf, langentry->author, authorBufSize - 1);
strncpy(versionBuf, buf->nacp.version, versionBufSize - 1);
success = true;
} else {
uiStatusMsg("GetLanguageEntry failed! (0x%08x)", result);
}
} else {
uiStatusMsg("Control.nacp buffer size (%u bytes) is too small! Expected: %u bytes", outsize, sizeof(buf->nacp));
}
} else {
uiStatusMsg("GetApplicationControlData failed! (0x%08x)", result);
}
free(buf);
} else {
uiStatusMsg("Unable to allocate memory for the NS service operations.");
}
return success;
}
int getSdCardFreeSpace(u64 *out)
{
struct statvfs st;
int rc;
rc = statvfs("sdmc:/", &st);
if (rc != 0)
{
uiStatusMsg("Unable to get SD card filesystem stats! statvfs: %d (%s).", errno, strerror(errno));
} else {
*out = (u64)(st.f_bsize * st.f_bfree);
}
return rc;
}
#define KiB (1024.0)
#define MiB (1024.0 * KiB)
#define GiB (1024.0 * MiB)
void convertSize(u64 size, char *out, int bufsize)
{
char buffer[16];
double bytes = (double)size;
if (bytes < 1000.0)
{
snprintf(buffer, sizeof(buffer), "%.0lf B", bytes);
} else
if (bytes < 10.0*KiB)
{
snprintf(buffer, sizeof(buffer), "%.2lf KiB", floor((bytes*100.0)/KiB)/100.0);
} else
if (bytes < 100.0*KiB)
{
snprintf(buffer, sizeof(buffer), "%.1lf KiB", floor((bytes*10.0)/KiB)/10.0);
} else
if (bytes < 1000.0*KiB)
{
snprintf(buffer, sizeof(buffer), "%.0lf KiB", floor(bytes/KiB));
} else
if (bytes < 10.0*MiB)
{
snprintf(buffer, sizeof(buffer), "%.2lf MiB", floor((bytes*100.0)/MiB)/100.0);
} else
if (bytes < 100.0*MiB)
{
snprintf(buffer, sizeof(buffer), "%.1lf MiB", floor((bytes*10.0)/MiB)/10.0);
} else
if (bytes < 1000.0*MiB)
{
snprintf(buffer, sizeof(buffer), "%.0lf MiB", floor(bytes/MiB));
} else
if (bytes < 10.0*GiB)
{
snprintf(buffer, sizeof(buffer), "%.2lf GiB", floor((bytes*100.0)/GiB)/100.0);
} else
if (bytes < 100.0*GiB)
{
snprintf(buffer, sizeof(buffer), "%.1lf GiB", floor((bytes*10.0)/GiB)/10.0);
} else {
snprintf(buffer, sizeof(buffer), "%.0lf GiB", floor(bytes/GiB));
}
snprintf(out, bufsize, "%s", buffer);
}
void getCurrentTimestamp(char *out, int bufsize)
{
time_t timer;
time(&timer);
struct tm *timeinfo = localtime(&timer);
char buffer[32] = {'\0'};
strftime(buffer, sizeof(buffer) / sizeof(buffer[0]), "%Y%m%d-%H%M%S", timeinfo);
snprintf(out, bufsize, "%s", buffer);
}
void waitForButtonPress()
{
uiDrawString("Press any button to continue", 0, breaks * 8, 255, 255, 255);
syncDisplay();
while(true)
{
hidScanInput();
u32 keysDown = hidKeysDown(CONTROLLER_P1_AUTO);
if (keysDown && !(keysDown & KEY_TOUCH)) break;
}
}
bool isDirectory(char *path)
{
DIR* dir = opendir(path);
if (!dir) return false;
closedir(dir);
return true;
}
void addString(char **filenames, int *filenamesCount, char **nextFilename, const char *string)
{
filenames[(*filenamesCount)++] = *nextFilename;
strcpy(*nextFilename, string);
*nextFilename += strlen(string) + 1;
}
static int sortAlpha(const void* a, const void* b)
{
return strcasecmp(*((const char**)a), *((const char**)b));
}
void getDirectoryContents(char *filenameBuffer, char **filenames, int *filenamesCount, const char *directory, bool skipParent)
{
struct dirent *ent;
int i, maxFilenamesCount = *filenamesCount;
char *nextFilename = filenameBuffer;
char *slash = (char*)malloc(strlen(directory) + 2);
memset(slash, 0, strlen(directory) + 2);
snprintf(slash, strlen(directory) + 2, "%s/", directory);
*filenamesCount = 0;
if (!skipParent) addString(filenames, filenamesCount, &nextFilename, "..");
DIR* dir = opendir(slash);
if (dir)
{
for(i = 0; i < maxFilenamesCount; i++)
{
ent = readdir(dir);
if (!ent) break;
if ((strlen(ent->d_name) == 1 && !strcmp(ent->d_name, ".")) || (strlen(ent->d_name) == 2 && !strcmp(ent->d_name, ".."))) continue;
addString(filenames, filenamesCount, &nextFilename, ent->d_name);
}
closedir(dir);
}
free(slash);
// ".." should stay at the top
qsort(filenames + 1, (*filenamesCount) - 1, sizeof(char*), &sortAlpha);
}

View file

@ -1,6 +1,35 @@
#pragma once
#ifndef __UTIL_H__
#define __UTIL_H__
#include <switch.h>
#define APP_VERSION "1.0.0"
#define NAME_BUF_LEN 4096
bool isGameCardInserted(FsDeviceOperator* o);
void syncDisplay();
void syncDisplay();
void delay(u8 seconds);
bool getGameCardTitleID(u64 *titleID);
bool getGameCardControlNacp(u64 titleID, char *nameBuf, int nameBufSize, char *authorBuf, int authorBufSize, char *versionBuf, int versionBufSize);
int getSdCardFreeSpace(u64 *out);
void convertSize(u64 size, char *out, int bufsize);
void getCurrentTimestamp(char *out, int bufsize);
void waitForButtonPress();
bool isDirectory(char *path);
void addString(char **filenames, int *filenamesCount, char **nextFilename, const char *string);
void getDirectoryContents(char *filenameBuffer, char **filenames, int *filenamesCount, const char *directory, bool skipParent);
#endif