1
0
Fork 0
mirror of https://github.com/DarkMatterCore/nxdumptool.git synced 2024-11-14 06:26:57 +00:00
nxdumptool/source/utils.c

609 lines
16 KiB
C
Raw Normal View History

2020-04-16 01:06:41 +01:00
/*
* utils.c
2020-04-16 01:06:41 +01:00
*
* Copyright (c) 2018-2020, WerWolv.
* Copyright (c) 2020, DarkMatterCore <pabloacurielz@gmail.com>.
*
* This file is part of nxdumptool (https://github.com/DarkMatterCore/nxdumptool).
*
* nxdumptool is free software; you can redistribute it and/or modify it
2020-04-16 01:06:41 +01:00
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* nxdumptool is distributed in the hope it will be useful, but WITHOUT
2020-04-16 01:06:41 +01:00
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "utils.h"
2020-04-15 21:50:07 +01:00
//#include "freetype_helper.h"
//#include "lvgl_helper.h"
2020-04-16 11:13:11 +01:00
#include "keys.h"
2020-04-15 21:50:07 +01:00
#include "gamecard.h"
2020-04-16 11:13:11 +01:00
#include "services.h"
#include "nca.h"
#include "usb.h"
2020-07-25 06:56:35 +01:00
#include "title.h"
#include "fatfs/ff.h"
2020-04-15 21:50:07 +01:00
#define LOGFILE_PATH "./" APP_TITLE ".log"
2020-04-15 21:50:07 +01:00
/* Global variables. */
2020-05-03 00:40:50 +01:00
static bool g_resourcesInitialized = false;
static Mutex g_resourcesMutex = 0;
static FsFileSystem *g_sdCardFileSystem = NULL;
static FsStorage g_emmcBisSystemPartitionStorage = {0};
static FATFS *g_emmcBisSystemPartitionFatFsObj = NULL;
static AppletType g_programAppletType = 0;
static bool g_homeButtonBlocked = false;
static Mutex g_homeButtonMutex = 0;
2020-04-16 11:13:11 +01:00
static u8 g_customFirmwareType = UtilsCustomFirmwareType_Unknown;
2020-04-15 21:50:07 +01:00
static AppletHookCookie g_systemOverclockCookie = {0};
static Mutex g_logfileMutex = 0;
static const char *g_sizeSuffixes[] = { "B", "KiB", "MiB", "GiB" };
static const u32 g_sizeSuffixesCount = MAX_ELEMENTS(g_sizeSuffixes);
2020-04-15 21:50:07 +01:00
/* Function prototypes. */
2020-05-03 00:40:50 +01:00
static bool utilsMountEmmcBisSystemPartitionStorage(void);
static void utilsUnmountEmmcBisSystemPartitionStorage(void);
2020-08-01 05:43:55 +01:00
static bool utilsGetDeviceFileSystemAndFilePathFromAbsolutePath(const char *path, FsFileSystem **out_fs, char **out_filepath);
2020-04-16 11:13:11 +01:00
static void _utilsGetCustomFirmwareType(void);
2020-04-15 21:50:07 +01:00
static void utilsOverclockSystemAppletHook(AppletHookType hook, void *param);
2020-05-03 00:40:50 +01:00
bool utilsInitializeResources(void)
{
mutexLock(&g_resourcesMutex);
bool ret = g_resourcesInitialized;
if (ret) goto end;
2020-05-03 00:40:50 +01:00
2020-08-01 05:43:55 +01:00
/* Retrieve pointer to the SD card FsFileSystem element. */
if (!(g_sdCardFileSystem = fsdevGetDeviceFileSystem("sdmc:")))
{
LOGFILE("Failed to retrieve FsFileSystem from SD card!");
goto end;
}
/* Initialize needed services. */
2020-05-03 00:40:50 +01:00
if (!servicesInitialize())
{
LOGFILE("Failed to initialize needed services!");
goto end;
2020-05-03 00:40:50 +01:00
}
/* Initialize USB interface. */
if (!usbInitialize())
{
LOGFILE("Failed to initialize USB interface!");
goto end;
}
/* Load NCA keyset. */
2020-05-03 00:40:50 +01:00
if (!keysLoadNcaKeyset())
{
LOGFILE("Failed to load NCA keyset!");
goto end;
2020-05-03 00:40:50 +01:00
}
/* Allocate NCA crypto buffer. */
2020-05-03 00:40:50 +01:00
if (!ncaAllocateCryptoBuffer())
{
LOGFILE("Unable to allocate memory for NCA crypto buffer!");
goto end;
2020-05-03 00:40:50 +01:00
}
/* Initialize gamecard interface. */
2020-05-03 00:40:50 +01:00
if (!gamecardInitialize())
{
LOGFILE("Failed to initialize gamecard interface!");
goto end;
2020-05-03 00:40:50 +01:00
}
2020-07-25 06:56:35 +01:00
/* Initialize title interface. */
if (!titleInitialize())
{
LOGFILE("Failed to initialize the title interface!");
goto end;
}
/* Mount eMMC BIS System partition. */
if (!utilsMountEmmcBisSystemPartitionStorage()) goto end;
2020-05-03 00:40:50 +01:00
/* Get applet type. */
2020-05-03 00:40:50 +01:00
g_programAppletType = appletGetAppletType();
/* Disable screen dimming and auto sleep. */
2020-05-03 00:40:50 +01:00
appletSetMediaPlaybackState(true);
/* Retrieve custom firmware type. */
2020-05-03 00:40:50 +01:00
_utilsGetCustomFirmwareType();
/* Overclock system. */
2020-05-03 00:40:50 +01:00
utilsOverclockSystem(true);
/* Setup an applet hook to change the hardware clocks after a system mode change (docked <-> undocked). */
2020-05-03 00:40:50 +01:00
appletHook(&g_systemOverclockCookie, utilsOverclockSystemAppletHook, NULL);
/* Initialize FreeType. */
2020-05-03 00:40:50 +01:00
//if (!freeTypeHelperInitialize()) return false;
/* Initialize LVGL. */
2020-05-03 00:40:50 +01:00
//if (!lvglHelperInitialize()) return false;
ret = g_resourcesInitialized = true;
end:
2020-05-03 00:40:50 +01:00
mutexUnlock(&g_resourcesMutex);
return ret;
}
void utilsCloseResources(void)
{
mutexLock(&g_resourcesMutex);
/* Free LVGL resources. */
2020-05-03 00:40:50 +01:00
//lvglHelperExit();
/* Free FreeType resources. */
2020-05-03 00:40:50 +01:00
//freeTypeHelperExit();
/* Unset our overclock applet hook. */
2020-05-03 00:40:50 +01:00
appletUnhook(&g_systemOverclockCookie);
/* Restore hardware clocks. */
2020-05-03 00:40:50 +01:00
utilsOverclockSystem(false);
/* Enable screen dimming and auto sleep. */
2020-05-03 00:40:50 +01:00
appletSetMediaPlaybackState(false);
/* Unblock HOME button presses. */
2020-05-03 00:40:50 +01:00
utilsChangeHomeButtonBlockStatus(false);
/* Unmount eMMC BIS System partition. */
2020-05-03 00:40:50 +01:00
utilsUnmountEmmcBisSystemPartitionStorage();
2020-07-25 06:56:35 +01:00
/* Deinitialize title interface. */
titleExit();
/* Deinitialize gamecard interface. */
2020-05-03 00:40:50 +01:00
gamecardExit();
/* Free NCA crypto buffer. */
2020-05-03 00:40:50 +01:00
ncaFreeCryptoBuffer();
/* Close USB interface. */
usbExit();
/* Close initialized services. */
2020-05-03 00:40:50 +01:00
servicesClose();
g_resourcesInitialized = false;
mutexUnlock(&g_resourcesMutex);
}
u64 utilsHidKeysAllDown(void)
2020-04-15 21:50:07 +01:00
{
u64 keys_down = 0;
2020-08-01 05:43:55 +01:00
for(u32 i = 0; i < CONTROLLER_UNKNOWN; i++) keys_down |= hidKeysDown(i);
return keys_down;
}
u64 utilsHidKeysAllHeld(void)
{
u64 keys_held = 0;
2020-08-01 05:43:55 +01:00
for(u32 i = 0; i < CONTROLLER_UNKNOWN; i++) keys_held |= hidKeysHeld(i);
return keys_held;
2020-04-15 21:50:07 +01:00
}
void utilsWaitForButtonPress(u64 flag)
2020-04-15 21:50:07 +01:00
{
2020-08-01 05:43:55 +01:00
/* Don't consider touch screen presses nor stick movement as button inputs. */
if (!flag) flag = ~(KEY_TOUCH | KEY_LSTICK_LEFT | KEY_LSTICK_RIGHT | KEY_LSTICK_UP | KEY_LSTICK_DOWN | KEY_RSTICK_LEFT | KEY_RSTICK_RIGHT | KEY_RSTICK_UP | KEY_RSTICK_DOWN);
2020-04-15 21:50:07 +01:00
while(appletMainLoop())
{
hidScanInput();
2020-08-01 05:43:55 +01:00
u64 keys_down = utilsHidKeysAllDown();
2020-04-15 21:50:07 +01:00
if (keys_down & flag) break;
}
}
void utilsWriteMessageToLogFile(const char *func_name, const char *fmt, ...)
2020-04-15 21:50:07 +01:00
{
if (!func_name || !strlen(func_name) || !fmt || !strlen(fmt)) return;
2020-04-15 21:50:07 +01:00
mutexLock(&g_logfileMutex);
va_list args;
FILE *logfile = NULL;
logfile = fopen(LOGFILE_PATH, "a+");
if (!logfile) goto end;
2020-04-15 21:50:07 +01:00
time_t now = time(NULL);
struct tm *ts = localtime(&now);
2020-07-12 16:29:08 +01:00
fprintf(logfile, "%d-%02d-%02d %02d:%02d:%02d -> %s: ", ts->tm_year + 1900, ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec, func_name);
2020-04-15 21:50:07 +01:00
va_start(args, fmt);
vfprintf(logfile, fmt, args);
va_end(args);
fprintf(logfile, "\r\n");
fclose(logfile);
2020-08-01 05:43:55 +01:00
utilsCommitSdCardFileSystemChanges();
2020-04-15 21:50:07 +01:00
end:
2020-04-15 21:50:07 +01:00
mutexUnlock(&g_logfileMutex);
}
void utilsWriteMessageToLogBuffer(char *dst, size_t dst_size, const char *func_name, const char *fmt, ...)
{
if (!dst || !dst_size || !func_name || !strlen(func_name) || !fmt || !strlen(fmt)) return;
va_list args;
time_t now = time(NULL);
struct tm *ts = localtime(&now);
char msg[512] = {0};
size_t msg_len = 0, dst_len = strlen(dst);
snprintf(msg, sizeof(msg), "%d-%02d-%02d %02d:%02d:%02d -> %s: ", ts->tm_year + 1900, ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec, func_name);
msg_len = strlen(msg);
va_start(args, fmt);
vsnprintf(msg + msg_len, sizeof(msg) - msg_len, fmt, args);
va_end(args);
msg_len = strlen(msg);
if ((dst_size - dst_len) > (msg_len + 2)) snprintf(dst + dst_len, dst_size - dst_len, "%s\r\n", msg);
}
void utilsWriteLogBufferToLogFile(const char *src)
{
if (!src || !strlen(src)) return;
mutexLock(&g_logfileMutex);
FILE *logfile = fopen(LOGFILE_PATH, "a+");
if (!logfile) goto end;
fprintf(logfile, "%s", src);
fclose(logfile);
2020-08-01 05:43:55 +01:00
utilsCommitSdCardFileSystemChanges();
end:
mutexUnlock(&g_logfileMutex);
}
void utilsLogFileMutexControl(bool lock)
{
if (lock)
{
mutexLock(&g_logfileMutex);
} else {
mutexUnlock(&g_logfileMutex);
}
}
void utilsReplaceIllegalCharacters(char *str, bool ascii_only)
2020-05-03 00:40:50 +01:00
{
size_t strsize = 0;
2020-04-16 11:13:11 +01:00
2020-05-03 00:40:50 +01:00
if (!str || !(strsize = strlen(str))) return;
2020-04-15 21:50:07 +01:00
2020-05-03 00:40:50 +01:00
for(size_t i = 0; i < strsize; i++)
{
if (memchr("?[]/\\=+<>:;\",*|^", str[i], sizeof("?[]/\\=+<>:;\",*|^") - 1) || str[i] < 0x20 || (!ascii_only && str[i] == 0x7F) || (ascii_only && str[i] >= 0x7F)) str[i] = '_';
}
2020-04-15 21:50:07 +01:00
}
2020-05-03 00:40:50 +01:00
void utilsTrimString(char *str)
2020-04-15 21:50:07 +01:00
{
2020-05-03 00:40:50 +01:00
size_t strsize = 0;
char *start = NULL, *end = NULL;
2020-04-15 21:50:07 +01:00
2020-05-03 00:40:50 +01:00
if (!str || !(strsize = strlen(str))) return;
2020-04-15 21:50:07 +01:00
2020-05-03 00:40:50 +01:00
start = str;
end = (start + strsize);
2020-04-15 21:50:07 +01:00
2020-05-03 00:40:50 +01:00
while(--end >= start)
{
if (!isspace((unsigned char)*end)) break;
}
2020-05-03 00:40:50 +01:00
*(++end) = '\0';
2020-05-03 00:40:50 +01:00
while(isspace((unsigned char)*start)) start++;
2020-05-03 00:40:50 +01:00
if (start != str) memmove(str, start, end - start + 1);
2020-04-16 11:13:11 +01:00
}
void utilsGenerateHexStringFromData(char *dst, size_t dst_size, const void *src, size_t src_size)
{
if (!src || !src_size || !dst || dst_size < ((src_size * 2) + 1)) return;
size_t i, j;
const u8 *src_u8 = (const u8*)src;
for(i = 0, j = 0; i < src_size; i++)
{
2020-04-19 23:44:22 +01:00
char h_nib = ((src_u8[i] >> 4) & 0xF);
char l_nib = (src_u8[i] & 0xF);
2020-04-19 23:44:22 +01:00
dst[j++] = (h_nib + (h_nib < 0xA ? 0x30 : 0x57));
dst[j++] = (l_nib + (l_nib < 0xA ? 0x30 : 0x57));
}
dst[j] = '\0';
}
void utilsGenerateFormattedSizeString(u64 size, char *dst, size_t dst_size)
{
if (!dst || dst_size < 2) return;
double converted_size = (double)size;
for(u32 i = 0; i < g_sizeSuffixesCount; i++)
{
if (converted_size >= pow(1024.0, i + 1) && (i + 1) < g_sizeSuffixesCount) continue;
converted_size /= pow(1024.0, i);
snprintf(dst, dst_size, "%.*f %s", (converted_size >= 100.0 ? 0 : (converted_size >= 10.0 ? 1 : 2)), converted_size, g_sizeSuffixes[i]);
break;
}
}
2020-08-01 05:43:55 +01:00
bool utilsGetFreeSpaceFromFileSystem(FsFileSystem *fs, u64 *out)
{
2020-08-01 05:43:55 +01:00
if (!fs || !serviceIsActive(&(fs->s)) || !out)
2020-05-03 00:40:50 +01:00
{
LOGFILE("Invalid parameters!");
return false;
}
2020-04-16 11:13:11 +01:00
2020-05-03 00:40:50 +01:00
Result rc = fsFsGetFreeSpace(fs, "/", (s64*)out);
2020-08-01 05:43:55 +01:00
if (R_FAILED(rc)) LOGFILE("fsFsGetFreeSpace failed! (0x%08X).", rc);
return R_SUCCEEDED(rc);
}
bool utilsGetFreeSpaceFromFileSystemByPath(const char *path, u64 *out)
{
FsFileSystem *fs = NULL;
if (!utilsGetDeviceFileSystemAndFilePathFromAbsolutePath(path, &fs, NULL) || !out)
2020-04-16 11:13:11 +01:00
{
2020-08-01 05:43:55 +01:00
LOGFILE("Invalid parameters!");
2020-05-03 00:40:50 +01:00
return false;
}
2020-08-01 05:43:55 +01:00
return utilsGetFreeSpaceFromFileSystem(fs, out);
}
bool utilsGetFreeSdCardFileSystemSpace(u64 *out)
{
return utilsGetFreeSpaceFromFileSystem(g_sdCardFileSystem, out);
}
bool utilsCommitFileSystemChangesByPath(const char *path)
{
Result rc = 0;
FsFileSystem *fs = NULL;
if (!utilsGetDeviceFileSystemAndFilePathFromAbsolutePath(path, &fs, NULL)) return false;
rc = fsFsCommit(fs);
return R_SUCCEEDED(rc);
}
bool utilsCommitSdCardFileSystemChanges(void)
{
if (!g_sdCardFileSystem) return false;
Result rc = fsFsCommit(g_sdCardFileSystem);
return R_SUCCEEDED(rc);
2020-05-03 00:40:50 +01:00
}
bool utilsCheckIfFileExists(const char *path)
{
if (!path || !strlen(path)) return false;
FILE *chkfile = fopen(path, "rb");
if (chkfile)
2020-04-16 11:13:11 +01:00
{
2020-05-03 00:40:50 +01:00
fclose(chkfile);
return true;
2020-04-16 11:13:11 +01:00
}
2020-05-03 00:40:50 +01:00
return false;
2020-04-16 11:13:11 +01:00
}
2020-05-03 00:40:50 +01:00
bool utilsCreateConcatenationFile(const char *path)
2020-04-15 21:50:07 +01:00
{
2020-05-03 00:40:50 +01:00
if (!path || !strlen(path))
{
LOGFILE("Invalid parameters!");
return false;
}
2020-04-15 21:50:07 +01:00
/* Safety check: remove any existant file/directory at the destination path. */
2020-05-03 00:40:50 +01:00
remove(path);
fsdevDeleteDirectoryRecursively(path);
/* Create ConcatenationFile */
/* If the call succeeds, the caller function will be able to operate on this file using stdio calls. */
2020-08-01 05:43:55 +01:00
Result rc = fsdevCreateFile(path, 0, FsCreateOption_BigFile);
if (R_FAILED(rc)) LOGFILE("fsdevCreateFile failed for \"%s\"! (0x%08X).", path, rc);
2020-05-03 00:40:50 +01:00
2020-08-01 05:43:55 +01:00
utilsCommitFileSystemChangesByPath(path);
return R_SUCCEEDED(rc);
2020-05-03 00:40:50 +01:00
}
void utilsCreateDirectoryTree(const char *path, bool create_last_element)
{
char *ptr = NULL, *tmp = NULL;
size_t path_len = 0;
if (!path || !(path_len = strlen(path))) return;
tmp = calloc(path_len + 1, sizeof(char));
if (!tmp) return;
ptr = strchr(path, '/');
while(ptr)
{
sprintf(tmp, "%.*s", (int)(ptr - path), path);
mkdir(tmp, 0777);
ptr = strchr(++ptr, '/');
}
if (create_last_element) mkdir(path, 0777);
free(tmp);
2020-08-01 05:43:55 +01:00
utilsCommitFileSystemChangesByPath(path);
}
2020-05-03 00:40:50 +01:00
bool utilsAppletModeCheck(void)
{
return (g_programAppletType != AppletType_Application && g_programAppletType != AppletType_SystemApplication);
}
void utilsChangeHomeButtonBlockStatus(bool block)
{
mutexLock(&g_homeButtonMutex);
/* Only change HOME button blocking status if we're running as a regular application or a system application, and if it's current blocking status is different than the requested one. */
2020-05-03 00:40:50 +01:00
if (!utilsAppletModeCheck() && block != g_homeButtonBlocked)
{
if (block)
{
appletBeginBlockingHomeButtonShortAndLongPressed(0);
} else {
appletEndBlockingHomeButtonShortAndLongPressed();
}
g_homeButtonBlocked = block;
}
mutexUnlock(&g_homeButtonMutex);
}
u8 utilsGetCustomFirmwareType(void)
{
return g_customFirmwareType;
}
FsStorage *utilsGetEmmcBisSystemPartitionStorage(void)
{
return &g_emmcBisSystemPartitionStorage;
}
void utilsOverclockSystem(bool overclock)
{
u32 cpuClkRate = ((overclock ? CPU_CLKRT_OVERCLOCKED : CPU_CLKRT_NORMAL) * 1000000);
u32 memClkRate = ((overclock ? MEM_CLKRT_OVERCLOCKED : MEM_CLKRT_NORMAL) * 1000000);
servicesChangeHardwareClockRates(cpuClkRate, memClkRate);
2020-04-15 21:50:07 +01:00
}
static bool utilsMountEmmcBisSystemPartitionStorage(void)
{
Result rc = 0;
FRESULT fr = FR_OK;
rc = fsOpenBisStorage(&g_emmcBisSystemPartitionStorage, FsBisPartitionId_System);
if (R_FAILED(rc))
{
LOGFILE("Failed to open eMMC BIS System partition storage! (0x%08X).", rc);
return false;
}
2020-04-19 23:44:22 +01:00
g_emmcBisSystemPartitionFatFsObj = calloc(1, sizeof(FATFS));
if (!g_emmcBisSystemPartitionFatFsObj)
{
LOGFILE("Unable to allocate memory for FatFs element!");
return false;
}
2020-04-19 23:44:22 +01:00
fr = f_mount(g_emmcBisSystemPartitionFatFsObj, BIS_SYSTEM_PARTITION_MOUNT_NAME, 1);
if (fr != FR_OK)
{
LOGFILE("Failed to mount eMMC BIS System partition! (%u).", fr);
return false;
}
return true;
}
static void utilsUnmountEmmcBisSystemPartitionStorage(void)
{
2020-04-19 23:44:22 +01:00
if (g_emmcBisSystemPartitionFatFsObj)
{
f_unmount(BIS_SYSTEM_PARTITION_MOUNT_NAME);
2020-04-19 23:44:22 +01:00
free(g_emmcBisSystemPartitionFatFsObj);
g_emmcBisSystemPartitionFatFsObj = NULL;
}
if (serviceIsActive(&(g_emmcBisSystemPartitionStorage.s)))
{
fsStorageClose(&g_emmcBisSystemPartitionStorage);
memset(&g_emmcBisSystemPartitionStorage, 0, sizeof(FsStorage));
}
}
2020-05-03 00:40:50 +01:00
2020-08-01 05:43:55 +01:00
static bool utilsGetDeviceFileSystemAndFilePathFromAbsolutePath(const char *path, FsFileSystem **out_fs, char **out_filepath)
{
FsFileSystem *fs = NULL;
char *name_end = NULL, *filepath = NULL, name[32] = {0};
if (!path || !strlen(path) || !(name_end = strchr(path, ':')) || (size_t)(name_end - path) >= MAX_ELEMENTS(name) || (!out_fs && !out_filepath) || \
(out_filepath && *(filepath = (name_end + 1)) != '/')) return false;
sprintf(name, "%.*s", (int)(name_end - path), path);
fs = fsdevGetDeviceFileSystem(name);
if (!fs) return false;
if (out_fs) *out_fs = fs;
if (out_filepath) *out_filepath = filepath;
return true;
}
2020-05-03 00:40:50 +01:00
static void _utilsGetCustomFirmwareType(void)
{
bool tx_srv = servicesCheckRunningServiceByName("tx");
bool rnx_srv = servicesCheckRunningServiceByName("rnx");
g_customFirmwareType = (rnx_srv ? UtilsCustomFirmwareType_ReiNX : (tx_srv ? UtilsCustomFirmwareType_SXOS : UtilsCustomFirmwareType_Atmosphere));
}
static void utilsOverclockSystemAppletHook(AppletHookType hook, void *param)
{
(void)param;
if (hook != AppletHookType_OnOperationMode && hook != AppletHookType_OnPerformanceMode) return;
/* To do: read config here to actually know the value to use with utilsOverclockSystem. */
2020-05-03 00:40:50 +01:00
utilsOverclockSystem(false);
}