From 5fe997f33e0a5f4c373cdb742fa84b8c551abbe2 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:14:11 +0000 Subject: [PATCH 01/11] decompile SD memory setup helpers --- include/scene/sdChannelMemory/iplSDMemory.h | 86 +++++++++++++++++++ src/scene/sdChannelMemory/iplSDMemory.cpp | 93 +++++++++++++++++++++ 2 files changed, 179 insertions(+) create mode 100644 include/scene/sdChannelMemory/iplSDMemory.h create mode 100644 src/scene/sdChannelMemory/iplSDMemory.cpp diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h new file mode 100644 index 00000000..684098be --- /dev/null +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -0,0 +1,86 @@ +#ifndef IPL_SCENE_SD_MEMORY_H +#define IPL_SCENE_SD_MEMORY_H + +#include + +#include "layout/iplLayout.h" +#include "scene/board/iplFocusObject.h" +#include "scene/channelEdit/iplNandSDCardManager.h" + +namespace ipl { + namespace scene { + class SDMemory { + public: + SDMemory(); + ~SDMemory(); + + void resetScrollArrows(); + void showDownArrow(); + void showUpArrow(); + void hideDownArrow(); + void hideUpArrow(); + void showLeftArrow(); + void showRightArrow(); + void hideLeftArrow(); + void hideRightArrow(); + + private: + layout::Object* mpMainLayout; + layout::Object* mpTitleLayout; + layout::Object* mpDialogLayout; + layout::Object* mpProgressLayout; + DialogWindow* mpDialogs[3]; + u32 mDialogState; + u32 mProcessState; + u32 mDisplayMode; + u32 mMessageId; + u32 mErrorCode; + u32 mCommandState; + u32 mSelectionState; + u32 mDisplayState; + u32 mCurrentOperation; + u32 mCurrentResult; + u32 mDialogFlags; + u32 mLayoutFlags; + u32 mPanelFlags; + u32 mPanelAnimationStates[4]; + NandSDCardManager* mpNandSDCardManager; + u32 mReadState; + u32 mListState; + u32 mPageOffset; + u32 mPageCount; + u32 mTitleCount; + u32 mCurrentTitle; + u32 mTitleFlags; + ESTitleId mTitleIds[96]; + wchar_t mTitleNames[96][21]; + u32 mTitleNameCount; + u32 mNandTitleNameCount; + ESTitleId mNandTitleIds[96]; + u32 mNandTitleCount; + u32 mSDTitleCount; + ESTitleId mSDTitleIds[96]; + wchar_t mCurrentTitleName[0x840]; + u32 mTransferFlags; + u32 mTransferStatus; + u64 mTransferStartTime; + s32 mTransferFrame; + struct TitleListState { + ESTitleId* mpTitles; + u32 mCount; + ESTitleId* mpSecondaryTitles; + u32 mSecondaryCount; + ESTitleId* mpNames; + u32 mNameCount; + } mTitleListState; + scroller mScroller; + u32 mButtonState; + u32 mPageButtonState; + u8 mControllerFlags[4]; + u32 mFinalState[3]; + u8 mFinalFlags[4]; + }; + } // namespace scene +} // namespace ipl + +#endif diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp new file mode 100644 index 00000000..da8bf26a --- /dev/null +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -0,0 +1,93 @@ +#include "scene/sdChannelMemory/iplSDMemory.h" + +namespace ipl { + namespace scene { + SDMemory::SDMemory() : mScroller() {} + + SDMemory::~SDMemory() {} + + void SDMemory::resetScrollArrows() { + mControllerFlags[0] = 0; + mControllerFlags[1] = 0; + mControllerFlags[2] = 0; + mControllerFlags[3] = 0; + mpDialogLayout->getAnim(16)->initAnmFrame(); + mpDialogLayout->getAnim(16)->initFrame(); + mpDialogLayout->getAnim(16)->restart(); + mpDialogLayout->getAnim(14)->initAnmFrame(); + mpDialogLayout->getAnim(14)->initFrame(); + mpDialogLayout->getAnim(14)->restart(); + if (!mScroller.isDownEnd()) { + showUpArrow(); + } + } + + void SDMemory::showDownArrow() { + if (mControllerFlags[0] == 0) { + mpDialogLayout->getAnim(16)->initAnmFrame(); + mpDialogLayout->getAnim(16)->initFrame(); + mpDialogLayout->getAnim(16)->restart(); + mControllerFlags[0] = 1; + } + } + + void SDMemory::showUpArrow() { + if (mControllerFlags[1] == 0) { + mpDialogLayout->getAnim(14)->initAnmFrame(); + mpDialogLayout->getAnim(14)->initFrame(); + mpDialogLayout->getAnim(14)->restart(); + mControllerFlags[1] = 1; + } + } + + void SDMemory::hideDownArrow() { + if (mControllerFlags[0] != 0) { + mpDialogLayout->getAnim(17)->initAnmFrame(); + mpDialogLayout->getAnim(17)->initFrame(); + mpDialogLayout->getAnim(17)->restart(); + mControllerFlags[0] = 0; + } + } + + void SDMemory::hideUpArrow() { + if (mControllerFlags[1] != 0) { + mpDialogLayout->getAnim(15)->initAnmFrame(); + mpDialogLayout->getAnim(15)->initFrame(); + mpDialogLayout->getAnim(15)->restart(); + mControllerFlags[1] = 0; + } + } + + void SDMemory::showLeftArrow() { + if (mControllerFlags[2] == 0) { + mpDialogLayout->getAnim(19)->initFrame(); + mpDialogLayout->getAnim(19)->restart(); + mControllerFlags[2] = 1; + } + } + + void SDMemory::showRightArrow() { + if (mControllerFlags[3] == 0) { + mpDialogLayout->getAnim(21)->initFrame(); + mpDialogLayout->getAnim(21)->restart(); + mControllerFlags[3] = 1; + } + } + + void SDMemory::hideLeftArrow() { + if (mControllerFlags[2] != 0) { + mpDialogLayout->getAnim(20)->initFrame(); + mpDialogLayout->getAnim(20)->restart(); + mControllerFlags[2] = 0; + } + } + + void SDMemory::hideRightArrow() { + if (mControllerFlags[3] != 0) { + mpDialogLayout->getAnim(22)->initFrame(); + mpDialogLayout->getAnim(22)->restart(); + mControllerFlags[3] = 0; + } + } + } +} -- 2.49.1 From dc1102f90c931239f77730fb8ec721d2a3a4f195 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:30:07 +0000 Subject: [PATCH 02/11] match SD memory arrow helpers --- config/43U/symbols.txt | 20 +++--- include/scene/sdChannelMemory/iplSDMemory.h | 2 +- src/scene/sdChannelMemory/iplSDMemory.cpp | 71 ++++++++++++++------- 3 files changed, 58 insertions(+), 35 deletions(-) diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 2ab7fbb1..b4148641 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4841,17 +4841,17 @@ iplSDMemory_813EB690 = .text:0x813EB690; // type:function size:0x10A0 iplSDMemory_813EC730 = .text:0x813EC730; // type:function size:0xD4 iplSDMemory_813EC804 = .text:0x813EC804; // type:function size:0x144 iplSDMemory_813EC948 = .text:0x813EC948; // type:function size:0x20 -iplSDMemory_813EC968 = .text:0x813EC968; // type:function size:0x84 -iplSDMemory_813EC9EC = .text:0x813EC9EC; // type:function size:0x9C -iplSDMemory_813ECA88 = .text:0x813ECA88; // type:function size:0x74 -iplSDMemory_813ECAFC = .text:0x813ECAFC; // type:function size:0x74 -iplSDMemory_813ECB70 = .text:0x813ECB70; // type:function size:0x78 -iplSDMemory_813ECBE8 = .text:0x813ECBE8; // type:function size:0x78 +resetScrollArrows__Q33ipl5scene8SDMemoryFv = .text:0x813EC968; // type:function size:0x84 +updateScrollArrows__Q33ipl5scene8SDMemoryFUlUlUlUl = .text:0x813EC9EC; // type:function size:0x9C +showDownArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECA88; // type:function size:0x74 +showUpArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECAFC; // type:function size:0x74 +hideDownArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECB70; // type:function size:0x78 +hideUpArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECBE8; // type:function size:0x78 iplSDMemory_813ECC60 = .text:0x813ECC60; // type:function size:0x160 -iplSDMemory_813ECDC0 = .text:0x813ECDC0; // type:function size:0x60 -iplSDMemory_813ECE20 = .text:0x813ECE20; // type:function size:0x60 -iplSDMemory_813ECE80 = .text:0x813ECE80; // type:function size:0x64 -iplSDMemory_813ECEE4 = .text:0x813ECEE4; // type:function size:0x64 +showLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECDC0; // type:function size:0x60 +showRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE20; // type:function size:0x60 +hideLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE80; // type:function size:0x64 +hideRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECEE4; // type:function size:0x64 iplSDMemory_813ECF48 = .text:0x813ECF48; // type:function size:0x13C iplSDMemory_813ED084 = .text:0x813ED084; // type:function size:0x268 iplSDMemory_813ED2EC = .text:0x813ED2EC; // type:function size:0x4CC diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h index 684098be..1079392c 100644 --- a/include/scene/sdChannelMemory/iplSDMemory.h +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -15,6 +15,7 @@ namespace ipl { ~SDMemory(); void resetScrollArrows(); + void updateScrollArrows(u32 previousDownEnd, u32 previousUpEnd, u32 downEnd, u32 upEnd); void showDownArrow(); void showUpArrow(); void hideDownArrow(); @@ -75,7 +76,6 @@ namespace ipl { } mTitleListState; scroller mScroller; u32 mButtonState; - u32 mPageButtonState; u8 mControllerFlags[4]; u32 mFinalState[3]; u8 mFinalFlags[4]; diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index da8bf26a..ff281fa2 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -12,80 +12,103 @@ namespace ipl { mControllerFlags[2] = 0; mControllerFlags[3] = 0; mpDialogLayout->getAnim(16)->initAnmFrame(); - mpDialogLayout->getAnim(16)->initFrame(); - mpDialogLayout->getAnim(16)->restart(); mpDialogLayout->getAnim(14)->initAnmFrame(); - mpDialogLayout->getAnim(14)->initFrame(); - mpDialogLayout->getAnim(14)->restart(); if (!mScroller.isDownEnd()) { showUpArrow(); } } + void SDMemory::updateScrollArrows(u32 previousDownEnd, u32 previousUpEnd, u32 downEnd, u32 upEnd) { + if (previousDownEnd != 1 && downEnd == 1) { + hideDownArrow(); + } + if (previousDownEnd == 1 && downEnd != 1) { + showDownArrow(); + } + if (previousUpEnd != 1 && upEnd == 1) { + hideUpArrow(); + } + if (previousUpEnd == 1 && upEnd != 1) { + showUpArrow(); + } + } + void SDMemory::showDownArrow() { if (mControllerFlags[0] == 0) { - mpDialogLayout->getAnim(16)->initAnmFrame(); - mpDialogLayout->getAnim(16)->initFrame(); - mpDialogLayout->getAnim(16)->restart(); + layout::Animator* initAnimation = mpDialogLayout->getAnim(16); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(16); + playAnimation->initFrame(); + playAnimation->restart(); mControllerFlags[0] = 1; } } void SDMemory::showUpArrow() { if (mControllerFlags[1] == 0) { - mpDialogLayout->getAnim(14)->initAnmFrame(); - mpDialogLayout->getAnim(14)->initFrame(); - mpDialogLayout->getAnim(14)->restart(); + layout::Animator* initAnimation = mpDialogLayout->getAnim(14); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(14); + playAnimation->initFrame(); + playAnimation->restart(); mControllerFlags[1] = 1; } } void SDMemory::hideDownArrow() { if (mControllerFlags[0] != 0) { - mpDialogLayout->getAnim(17)->initAnmFrame(); - mpDialogLayout->getAnim(17)->initFrame(); - mpDialogLayout->getAnim(17)->restart(); + layout::Animator* initAnimation = mpDialogLayout->getAnim(17); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(17); + playAnimation->initFrame(); + playAnimation->restart(); mControllerFlags[0] = 0; } } void SDMemory::hideUpArrow() { if (mControllerFlags[1] != 0) { - mpDialogLayout->getAnim(15)->initAnmFrame(); - mpDialogLayout->getAnim(15)->initFrame(); - mpDialogLayout->getAnim(15)->restart(); + layout::Animator* initAnimation = mpDialogLayout->getAnim(15); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(15); + playAnimation->initFrame(); + playAnimation->restart(); mControllerFlags[1] = 0; } } void SDMemory::showLeftArrow() { if (mControllerFlags[2] == 0) { - mpDialogLayout->getAnim(19)->initFrame(); - mpDialogLayout->getAnim(19)->restart(); + layout::Animator* animation = mpDialogLayout->getAnim(19); + animation->initFrame(); + animation->restart(); mControllerFlags[2] = 1; } } void SDMemory::showRightArrow() { if (mControllerFlags[3] == 0) { - mpDialogLayout->getAnim(21)->initFrame(); - mpDialogLayout->getAnim(21)->restart(); + layout::Animator* animation = mpDialogLayout->getAnim(21); + animation->initFrame(); + animation->restart(); mControllerFlags[3] = 1; } } void SDMemory::hideLeftArrow() { if (mControllerFlags[2] != 0) { - mpDialogLayout->getAnim(20)->initFrame(); - mpDialogLayout->getAnim(20)->restart(); + layout::Animator* animation = mpDialogLayout->getAnim(20); + animation->initFrame(); + animation->restart(); mControllerFlags[2] = 0; } } void SDMemory::hideRightArrow() { if (mControllerFlags[3] != 0) { - mpDialogLayout->getAnim(22)->initFrame(); - mpDialogLayout->getAnim(22)->restart(); + layout::Animator* animation = mpDialogLayout->getAnim(22); + animation->initFrame(); + animation->restart(); mControllerFlags[3] = 0; } } -- 2.49.1 From fb81577a0fa6c2cc15aa3a8d6b209d9013c664b3 Mon Sep 17 00:00:00 2001 From: "devin-ai-integration[bot]" <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:44:43 +0000 Subject: [PATCH 03/11] Link fa/pf_api_util + pf_w_api_util (clean subset) (#245) * fa: link pf_api_util + pf_w_api_util (genuine implementations, objdiff 100%) Co-Authored-By: wch * configure: flip fa/pf_api_util + fa/pf_w_api_util to Matching Co-Authored-By: wch --------- Co-authored-by: devin Co-authored-by: wch --- configure.py | 4 +- libs/RVL_SDK/src/fa/pf_api_util.c | 127 ++++++++++++++++++++++++++++ libs/RVL_SDK/src/fa/pf_w_api_util.c | 53 ++++++++++++ 3 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 libs/RVL_SDK/src/fa/pf_api_util.c create mode 100644 libs/RVL_SDK/src/fa/pf_w_api_util.c diff --git a/configure.py b/configure.py index 6bbcff16..52f48215 100644 --- a/configure.py +++ b/configure.py @@ -1707,7 +1707,7 @@ config.libs = [ Object(NonMatching, "fa/pf_volume.c"), Object(NonMatching, "fa/pf_volume_apiadd.c"), Object(NonMatching, "fa/pf_cp932.c"), - Object(NonMatching, "fa/pf_api_util.c"), + Object(Matching, "fa/pf_api_util.c"), Object(NonMatching, "fa/pf_attach.c"), Object(NonMatching, "fa/pf_buffering.c"), Object(NonMatching, "fa/pf_cdelete.c"), @@ -1774,7 +1774,7 @@ config.libs = [ Object(NonMatching, "fa/pf_unmount.c"), Object(NonMatching, "fa/pf_unregctx.c"), Object(NonMatching, "fa/pf_xdivide.c"), - Object(NonMatching, "fa/pf_w_api_util.c"), + Object(Matching, "fa/pf_w_api_util.c"), Object(NonMatching, "fa/pf_w_cdelete.c"), Object(NonMatching, "fa/pf_w_chdir.c"), Object(NonMatching, "fa/pf_w_chdmod.c"), diff --git a/libs/RVL_SDK/src/fa/pf_api_util.c b/libs/RVL_SDK/src/fa/pf_api_util.c new file mode 100644 index 00000000..f70a9f9b --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_api_util.c @@ -0,0 +1,127 @@ +#include +#include + +static s32 pf_error_to_api_error[] = {FA_ERR_SUCCESS, FA_ERR_EINVAL, FA_ERR_EINVAL, FA_ERR_ENOENT, FA_ERR_EBUSY, FA_ERR_ENOTEMPTY, FA_ERR_ENOSPC, + FA_ERR_ENOEXEC, FA_ERR_EEXIST, FA_ERR_ENOEXEC, FA_ERR_EINVAL, FA_ERR_EWRTPROTECT, FA_ERR_ENOSYS, FA_ERR_ENOEXEC, + FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, FA_ERR_EACCES, FA_ERR_EIO, FA_ERR_ENOEXEC, FA_ERR_EACCES, FA_ERR_ENOENT, + FA_ERR_ENFILE, FA_ERR_EMFILE, FA_ERR_EISDIR, FA_ERR_EACCES, FA_ERR_EPERM, FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, + FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, FA_ERR_ENOMEM, FA_ERR_EINVAL, FA_ERR_EINVAL, FA_ERR_ENOEXEC, FA_ERR_ENOENT, + FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, FA_ERR_EFBIG, FA_ERR_EBADF, FA_ERR_ENOLCK}; + +s32 PFAPI_ParseOpenModeString(const char* mode_str) { + s32 open_mode = 0; + u32 i = 0; + + if (mode_str == NULL) { + open_mode = 10; + return open_mode; + } + + switch (mode_str[i++]) { + case 'r': { + open_mode = 2; + break; + } + case 'w': { + open_mode = 1; + break; + } + case 'a': { + open_mode = 4; + break; + } + default: { + return 0; + } + } + + if (mode_str[i] == 'b') { + i++; + } + switch (mode_str[i++]) { + case 0: { + return open_mode; + } + case 't': + default: { + return 0; + } + case '+': { + switch (mode_str[i]) { + case 0: { + return open_mode | 8; + } + default: { + return 0; + } + } + } + } + return 0; +} + +s32 PFAPI_convertError(s32 err) { + if (err == 0) { + return 0; + } + if (err == -1) { + return -1; + } + if (err > 0 && err < 0xA0) { + return pf_error_to_api_error[err]; + } + if (err == 0x1000) { + err = FA_ERR_EIO; + } + return err; +} + +s32 PFAPI_convertDriverError(s32 err) { + if (err == 0) { + return 0; + } + if (err <= 0) { + return err; + } + if ((u32)err < 0xA0) { + err = 1; + } + return err; +} + +s32 PFAPI_convertReturnValue(s32 err) { + if (err == 0) { + return 0; + } + return -1; +} + +s32 PFAPI_convertReturnValue4feof(s32 err) { + if (err == 1) { + return 1; + } + if (err == 0) { + return 0; + } + return -1; +} + +void* PFAPI_convertReturnValue2NULL(s32 err, void* p_stream) { + void* ret; + if (err) { + ret = NULL; + } else { + ret = p_stream; + } + return ret; +} + +s32 PFAPI_convertReturnValue4unmount(s32 err) { + if (err == 0) { + return 0; + } + if (err == 1) { + return 1; + } + return -1; +} diff --git a/libs/RVL_SDK/src/fa/pf_w_api_util.c b/libs/RVL_SDK/src/fa/pf_w_api_util.c new file mode 100644 index 00000000..cf7a7b2c --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_w_api_util.c @@ -0,0 +1,53 @@ +#include + +s32 PFWAPI_ParseOpenModeString(const unsigned short* mode_str) { + s32 open_mode = 0; + u32 i = 0; + + if (mode_str == NULL) { + open_mode = 10; + return open_mode; + } + + switch (mode_str[i++]) { + case 'r': { + open_mode = 2; + break; + } + case 'w': { + open_mode = 1; + break; + } + case 'a': { + open_mode = 4; + break; + } + default: { + return 0; + } + } + + if (mode_str[i] == 'b') { + i++; + } + switch (mode_str[i++]) { + case 0: { + return open_mode; + } + case 't': + default: { + return 0; + } + case '+': { + switch (mode_str[i]) { + case 0: { + return open_mode | 8; + } + default: { + return 0; + } + } + } + } + return 0; +} -- 2.49.1 From da200d5f3adbe5843547113fd0ee9746d6b3049c Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:29:48 +0000 Subject: [PATCH 04/11] match sd memory setup helpers --- config/43U/symbols.txt | 10 +- include/scene/sdChannelMemory/iplSDMemory.h | 22 ++- include/utility/iplScroller.h | 4 + src/scene/sdChannelMemory/iplSDMemory.cpp | 200 ++++++++++++++++++++ 4 files changed, 224 insertions(+), 12 deletions(-) diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index b4148641..d0aca24d 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4837,17 +4837,17 @@ onEvent__Q33ipl5scene22SDMenuEventHandlerBaseFUlUlPv = .text:0x813EB51C; // type onEventDerived__Q33ipl5scene22SDMenuEventHandlerBaseFUlUlPCQ33ipl10controller9Interface = .text:0x813EB5E8; // type:function size:0x4 __ct__Q33ipl5scene8SDMemoryFv = .text:0x813EB5EC; // type:function size:0x48 __dt__Q33ipl5scene8SDMemoryFv = .text:0x813EB634; // type:function size:0x5C -iplSDMemory_813EB690 = .text:0x813EB690; // type:function size:0x10A0 -iplSDMemory_813EC730 = .text:0x813EC730; // type:function size:0xD4 -iplSDMemory_813EC804 = .text:0x813EC804; // type:function size:0x144 -iplSDMemory_813EC948 = .text:0x813EC948; // type:function size:0x20 +create__Q33ipl5scene8SDMemoryFPQ23EGG4HeapPQ33ipl4nand10LayoutFilePQ33ipl5scene17NandSDCardManager = .text:0x813EB690; // type:function size:0x10A0 +setTitleLists__Q33ipl5scene8SDMemoryFRCQ43ipl5scene8SDMemory10TitleRangeRCQ43ipl5scene8SDMemory10TitleRange = .text:0x813EC730; // type:function size:0xD4 +setScrollLimit__Q33ipl5scene8SDMemoryFv = .text:0x813EC804; // type:function size:0x144 +init__Q33ipl7utility8ScrollerFv = .text:0x813EC948; // type:function size:0x20 resetScrollArrows__Q33ipl5scene8SDMemoryFv = .text:0x813EC968; // type:function size:0x84 updateScrollArrows__Q33ipl5scene8SDMemoryFUlUlUlUl = .text:0x813EC9EC; // type:function size:0x9C showDownArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECA88; // type:function size:0x74 showUpArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECAFC; // type:function size:0x74 hideDownArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECB70; // type:function size:0x78 hideUpArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECBE8; // type:function size:0x78 -iplSDMemory_813ECC60 = .text:0x813ECC60; // type:function size:0x160 +updateSideArrows__Q33ipl5scene8SDMemoryFv = .text:0x813ECC60; // type:function size:0x160 showLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECDC0; // type:function size:0x60 showRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE20; // type:function size:0x60 hideLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE80; // type:function size:0x64 diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h index 1079392c..68042dd1 100644 --- a/include/scene/sdChannelMemory/iplSDMemory.h +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -4,6 +4,7 @@ #include #include "layout/iplLayout.h" +#include "layout/iplGuiManager.h" #include "scene/board/iplFocusObject.h" #include "scene/channelEdit/iplNandSDCardManager.h" @@ -11,9 +12,18 @@ namespace ipl { namespace scene { class SDMemory { public: + struct TitleRange { + ESTitleId* mpTitles; + u32 mCount; + }; + SDMemory(); ~SDMemory(); + void create(EGG::Heap* heap, nand::LayoutFile* layoutFile, NandSDCardManager* manager); + void setTitleLists(const TitleRange& nandTitles, const TitleRange& sdTitles); + void setScrollLimit(); + void updateSideArrows(); void resetScrollArrows(); void updateScrollArrows(u32 previousDownEnd, u32 previousUpEnd, u32 downEnd, u32 upEnd); void showDownArrow(); @@ -30,7 +40,7 @@ namespace ipl { layout::Object* mpTitleLayout; layout::Object* mpDialogLayout; layout::Object* mpProgressLayout; - DialogWindow* mpDialogs[3]; + gui::PaneManager* mpPaneManagers[3]; u32 mDialogState; u32 mProcessState; u32 mDisplayMode; @@ -46,10 +56,8 @@ namespace ipl { u32 mPanelFlags; u32 mPanelAnimationStates[4]; NandSDCardManager* mpNandSDCardManager; - u32 mReadState; - u32 mListState; - u32 mPageOffset; - u32 mPageCount; + TitleRange mNandTitleRange; + TitleRange mSDTitleRange; u32 mTitleCount; u32 mCurrentTitle; u32 mTitleFlags; @@ -62,7 +70,7 @@ namespace ipl { u32 mSDTitleCount; ESTitleId mSDTitleIds[96]; wchar_t mCurrentTitleName[0x840]; - u32 mTransferFlags; + u8 mTransferFlags[4]; u32 mTransferStatus; u64 mTransferStartTime; s32 mTransferFrame; @@ -75,7 +83,7 @@ namespace ipl { u32 mNameCount; } mTitleListState; scroller mScroller; - u32 mButtonState; + s32 mButtonState; u8 mControllerFlags[4]; u32 mFinalState[3]; u8 mFinalFlags[4]; diff --git a/include/utility/iplScroller.h b/include/utility/iplScroller.h index bbcd685e..fe39e065 100644 --- a/include/utility/iplScroller.h +++ b/include/utility/iplScroller.h @@ -49,6 +49,9 @@ namespace ipl { public: Scroller(); +#ifdef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE + void init(); +#else void init() { mState = 0; mScroll = 0.0f; @@ -56,6 +59,7 @@ namespace ipl { mUpLimit = 0.0f; mDownLimit = 0.0f; } +#endif void calc(); f32 get() const; diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index ff281fa2..24cf3da3 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -1,11 +1,211 @@ +#define IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE #include "scene/sdChannelMemory/iplSDMemory.h" +#undef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE + +#include "system/iplSystem.h" +#include "sound/iplSound.h" namespace ipl { + namespace utility { + void Scroller::init() { + mState = 0; + mScroll = 0.0f; + unk_0x3C = 0.0f; + mUpLimit = 0.0f; + mDownLimit = 0.0f; + } + } + namespace scene { + static const char* const sControlPaneNames[] = { + "A", "B", "B_BtnA", "A", "B", "C", "D", "B_BtnA", "B_00", "C_00", "D_00", "B_BtnA", + }; + + static const char* const sDialogPaneNames[] = {"B_ArwR", "B_ArwL", "B_CalExit", "B_CalExit_00"}; + SDMemory::SDMemory() : mScroller() {} SDMemory::~SDMemory() {} + void SDMemory::create(EGG::Heap* heap, nand::LayoutFile* layoutFile, NandSDCardManager* manager) { + mpNandSDCardManager = manager; + + mpMainLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_a.brlyt"); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_DialogIn.brlan", "G_InOut", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_DialogOut.brlan", "G_InOut", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_FocusBtn_on.brlan", "G_FocusBtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_FocusBtn_off.brlan", "G_FocusBtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_SelectBtn_Ac.brlan", "G_SelectBtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnA_Rollover.brlan", "G_BtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnA_Rollout.brlan", "G_BtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnA_On.brlan", "G_BtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnB_Rollover.brlan", "G_BtnB", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnB_Rollout.brlan", "G_BtnB", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnB_On.brlan", "G_BtnB", false, true); + mpMainLayout->finishBinding(); + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(2)->initAnmFrame(); + mpMainLayout->getAnim(5)->initAnmFrame(); + mpMainLayout->getAnim(8)->initAnmFrame(); + + nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_Dialog_00"))->SetString(System::getMessage(0xB0)); + nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_05"))->SetString(System::getMessage(0xBB)); + nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_06"))->SetString(System::getMessage(0xBC)); + nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_BtnA"))->SetString(System::getMessage(0x25)); + + mpTitleLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_b.brlyt"); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_DialogIn.brlan", "G_InOut", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_DialogOut.brlan", "G_InOut", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_FocusBtn_on.brlan", "G_FocusBtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_FocusBtn_off.brlan", "G_FocusBtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_SelectBtn_Ac.brlan", "G_SelectBtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnA_Rollover.brlan", "G_BtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnA_Rollout.brlan", "G_BtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnA_On.brlan", "G_BtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnB_Rollover.brlan", "G_BtnB", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnB_Rollout.brlan", "G_BtnB", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnB_On.brlan", "G_BtnB", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnC_Rollover.brlan", "G_BtnC", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnC_Rollout.brlan", "G_BtnC", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnC_On.brlan", "G_BtnC", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnD_Rollover.brlan", "G_BtnD", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnD_Rollout.brlan", "G_BtnD", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnD_On.brlan", "G_BtnD", false, true); + mpTitleLayout->finishBinding(); + mpTitleLayout->getAnim(0)->initAnmFrame(); + mpTitleLayout->getAnim(2)->initAnmFrame(); + mpTitleLayout->getAnim(5)->initAnmFrame(); + mpTitleLayout->getAnim(8)->initAnmFrame(); + mpTitleLayout->getAnim(11)->initAnmFrame(); + mpTitleLayout->getAnim(14)->initAnmFrame(); + + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog"))->SetString(System::getMessage(0xB6)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_00"))->SetString(System::getMessage(0xB7)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_01"))->SetString(System::getMessage(0xB8)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_02"))->SetString(System::getMessage(0xB9)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_03"))->SetString(System::getMessage(0xBA)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog_00"))->SetString(System::getMessage(0xB6)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_05"))->SetString(System::getMessage(0xB8)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_06"))->SetString(System::getMessage(0xB9)); + nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_07"))->SetString(System::getMessage(0xBA)); + + mpDialogLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_c.brlyt"); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Dialog_FadeIn.brlan", "G_Fede", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Dialog_FadeOut.brlan", "G_Fede", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_RollOver.brlan", "G_Back_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_Rollout.brlan", "G_Back_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_On.brlan", "G_Back_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Move_RollOver.brlan", "G_Move_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Move_Rollout.brlan", "G_Move_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Move_On.brlan", "G_Move_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOn.brlan", "G_ArwL_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOff.brlan", "G_ArwL_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Select.brlan", "G_ArwL_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOn.brlan", "G_ArwR_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOff.brlan", "G_ArwR_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Select.brlan", "G_ArwR_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Appear.brlan", "G_ArwL_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Lost.brlan", "G_ArwL_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Appear.brlan", "G_ArwR_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Lost.brlan", "G_ArwR_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Loop.brlan", "G_ArwRoop", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionStart.brlan", "G_ArwL_HDAc", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionEnd.brlan", "G_ArwL_HDAc", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionStart.brlan", "G_ArwR_HDAc", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionEnd.brlan", "G_ArwR_HDAc", false, true); + mpDialogLayout->finishBinding(); + mpDialogLayout->getAnim(0)->initAnmFrame(); + mpDialogLayout->getAnim(2)->initAnmFrame(); + mpDialogLayout->getAnim(5)->initAnmFrame(); + mpDialogLayout->getAnim(11)->initAnmFrame(); + mpDialogLayout->getAnim(8)->initAnmFrame(); + mpDialogLayout->getAnim(18)->initAnmFrame(); + mpDialogLayout->getAnim(18)->initFrame(); + mpDialogLayout->getAnim(18)->restart(); + + nw4r::lyt::TextBox* exitText = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit")); + exitText->SetString(System::getMessage(0xA5)); + nw4r::lyt::TextBox* exitTextAlt = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit_00")); + exitTextAlt->SetString(System::getMessage(0xC4)); + + mpProgressLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_Background.brlyt"); + mpProgressLayout->bindToGroup("mn_DialogWindow_Background_DialogIn.brlan", "G_InOut", false, true); + mpProgressLayout->bindToGroup("mn_DialogWindow_Background_DialogOut.brlan", "G_InOut", false, true); + mpProgressLayout->finishBinding(); + mpProgressLayout->getAnim(0)->initAnmFrame(); + + } + + void SDMemory::setTitleLists(const TitleRange& nandTitles, const TitleRange& sdTitles) { + mNandTitleRange = nandTitles; + mSDTitleRange = sdTitles; + mTransferFlags[0] = 1; + mDialogState = 0; + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(0)->play(); + mpProgressLayout->getAnim(0)->initAnmFrame(); + mpProgressLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_INFO_WINDOW"); + mTransferFlags[1] = 1; + mErrorCode = 0; + } + + void SDMemory::setScrollLimit() { + nw4r::lyt::Pane* headerPane = mpDialogLayout->FindPaneByName("N_Header"); + nw4r::lyt::Pane* buttonPane = mpDialogLayout->FindPaneByName("T_BtnA"); + nw4r::lyt::Pane* footerPane = mpDialogLayout->FindPaneByName("N_Footer"); + + nw4r::ut::Rect projection; + System::getProjectionRect(&projection); + + f32 itemCount = static_cast(mButtonState); + f32 buttonHeight = buttonPane->GetSize().height; + f32 headerHeight = headerPane->GetSize().height; + f32 footerHeight = footerPane->GetSize().height; + f32 contentHeight = headerHeight + footerHeight; + f32 itemHeight = itemCount * buttonHeight; + f32 contentHeightWithItems = itemHeight + contentHeight; + f32 downLimit = contentHeightWithItems - projection.GetHeight() + 1.0f; + if (downLimit < 0.0f) { + downLimit = 0.0f; + } + + mScroller.init(); + mScroller.setDownLimit(downLimit); + } + + void SDMemory::updateSideArrows() { + controller::Interface* masterController = System::getMasterController(); + + if (mScroller.getBInst().isActive() ? false : true) { + if (masterController->down(controller::BTN_UP)) { + showLeftArrow(); + } + if (!masterController->down(controller::BTN_UP)) { + hideLeftArrow(); + } + if (masterController->down(controller::BTN_DOWN)) { + showRightArrow(); + } + if (!masterController->down(controller::BTN_DOWN)) { + hideRightArrow(); + } + } else { + if (mScroller.getBInst().isUp()) { + showLeftArrow(); + } + if (!mScroller.getBInst().isUp()) { + hideLeftArrow(); + } + if (mScroller.getBInst().isDown()) { + showRightArrow(); + } + if (!mScroller.getBInst().isDown()) { + hideRightArrow(); + } + } + } + void SDMemory::resetScrollArrows() { mControllerFlags[0] = 0; mControllerFlags[1] = 0; -- 2.49.1 From 27bbf4d1ce5818b2ea89a76eeaa6a6cce9f31e73 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:46:27 +0000 Subject: [PATCH 05/11] decompile sd memory dialog reset --- config/43U/symbols.txt | 2 +- include/scene/sdChannelMemory/iplSDMemory.h | 2 ++ src/scene/sdChannelMemory/iplSDMemory.cpp | 33 +++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index d0aca24d..2fcbd8d1 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4852,7 +4852,7 @@ showLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECDC0; // type:function size showRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE20; // type:function size:0x60 hideLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE80; // type:function size:0x64 hideRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECEE4; // type:function size:0x64 -iplSDMemory_813ECF48 = .text:0x813ECF48; // type:function size:0x13C +resetDialogPaneAnimations__Q33ipl5scene8SDMemoryFv = .text:0x813ECF48; // type:function size:0x13C iplSDMemory_813ED084 = .text:0x813ED084; // type:function size:0x268 iplSDMemory_813ED2EC = .text:0x813ED2EC; // type:function size:0x4CC iplSDMemory_813ED7B8 = .text:0x813ED7B8; // type:function size:0xA4 diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h index 68042dd1..2e25c421 100644 --- a/include/scene/sdChannelMemory/iplSDMemory.h +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -36,6 +36,8 @@ namespace ipl { void hideRightArrow(); private: + void resetDialogPaneAnimations(); + layout::Object* mpMainLayout; layout::Object* mpTitleLayout; layout::Object* mpDialogLayout; diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index 24cf3da3..6472f569 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -90,6 +90,7 @@ namespace ipl { nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_07"))->SetString(System::getMessage(0xBA)); mpDialogLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_c.brlyt"); + static_cast(mpDialogLayout->FindPaneByName("T_Letter"))->AllocStringBuffer(0x840); mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Dialog_FadeIn.brlan", "G_Fede", false, true); mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Dialog_FadeOut.brlan", "G_Fede", false, true); mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_RollOver.brlan", "G_Back_Focus", false, true); @@ -312,5 +313,37 @@ namespace ipl { mControllerFlags[3] = 0; } } + + void SDMemory::resetDialogPaneAnimations() { + for (int i = 0; i < 4; i++) { + if (mPanelAnimationStates[i] != 0) { + mPanelAnimationStates[i] = 0; + nw4r::lyt::Pane* pane = mpDialogLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sDialogPaneNames[i]); + mpPaneManagers[2]->initPane(pane); + + layout::Animator* animation = NULL; + switch (i) { + case 2: + animation = mpDialogLayout->getAnim(3); + break; + case 3: + animation = mpDialogLayout->getAnim(6); + break; + case 0: + animation = mpDialogLayout->getAnim(12); + break; + case 1: + animation = mpDialogLayout->getAnim(9); + break; + } + + if (animation != NULL) { + animation->initAnmFrame(); + animation->initFrame(); + animation->restart(); + } + } + } + } } } -- 2.49.1 From 460eeb07c9b44748b9c8a54251605d54b053c188 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:54:45 +0000 Subject: [PATCH 06/11] order sd memory text pane updates --- src/scene/sdChannelMemory/iplSDMemory.cpp | 49 ++++++++++++++--------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index 6472f569..f3b362fc 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -48,10 +48,14 @@ namespace ipl { mpMainLayout->getAnim(5)->initAnmFrame(); mpMainLayout->getAnim(8)->initAnmFrame(); - nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_Dialog_00"))->SetString(System::getMessage(0xB0)); - nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_05"))->SetString(System::getMessage(0xBB)); - nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_06"))->SetString(System::getMessage(0xBC)); - nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_BtnA"))->SetString(System::getMessage(0x25)); + nw4r::lyt::TextBox* textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_Dialog_00")); + textBox->SetString(System::getMessage(0xB0)); + textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_05")); + textBox->SetString(System::getMessage(0xBB)); + textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_06")); + textBox->SetString(System::getMessage(0xBC)); + textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_BtnA")); + textBox->SetString(System::getMessage(0x25)); mpTitleLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_b.brlyt"); mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_DialogIn.brlan", "G_InOut", false, true); @@ -79,15 +83,24 @@ namespace ipl { mpTitleLayout->getAnim(11)->initAnmFrame(); mpTitleLayout->getAnim(14)->initAnmFrame(); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog"))->SetString(System::getMessage(0xB6)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_00"))->SetString(System::getMessage(0xB7)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_01"))->SetString(System::getMessage(0xB8)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_02"))->SetString(System::getMessage(0xB9)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_03"))->SetString(System::getMessage(0xBA)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog_00"))->SetString(System::getMessage(0xB6)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_05"))->SetString(System::getMessage(0xB8)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_06"))->SetString(System::getMessage(0xB9)); - nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_07"))->SetString(System::getMessage(0xBA)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog")); + textBox->SetString(System::getMessage(0xB6)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_00")); + textBox->SetString(System::getMessage(0xB7)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_01")); + textBox->SetString(System::getMessage(0xB8)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_02")); + textBox->SetString(System::getMessage(0xB9)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_03")); + textBox->SetString(System::getMessage(0xBA)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog_00")); + textBox->SetString(System::getMessage(0xB6)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_05")); + textBox->SetString(System::getMessage(0xB8)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_06")); + textBox->SetString(System::getMessage(0xB9)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_07")); + textBox->SetString(System::getMessage(0xBA)); mpDialogLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_c.brlyt"); static_cast(mpDialogLayout->FindPaneByName("T_Letter"))->AllocStringBuffer(0x840); @@ -124,10 +137,10 @@ namespace ipl { mpDialogLayout->getAnim(18)->initFrame(); mpDialogLayout->getAnim(18)->restart(); - nw4r::lyt::TextBox* exitText = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit")); - exitText->SetString(System::getMessage(0xA5)); - nw4r::lyt::TextBox* exitTextAlt = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit_00")); - exitTextAlt->SetString(System::getMessage(0xC4)); + textBox = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit")); + textBox->SetString(System::getMessage(0xA5)); + textBox = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit_00")); + textBox->SetString(System::getMessage(0xC4)); mpProgressLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_Background.brlyt"); mpProgressLayout->bindToGroup("mn_DialogWindow_Background_DialogIn.brlan", "G_InOut", false, true); @@ -318,7 +331,7 @@ namespace ipl { for (int i = 0; i < 4; i++) { if (mPanelAnimationStates[i] != 0) { mPanelAnimationStates[i] = 0; - nw4r::lyt::Pane* pane = mpDialogLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sDialogPaneNames[i]); + nw4r::lyt::Pane* pane = mpDialogLayout->FindPaneByName(sDialogPaneNames[i]); mpPaneManagers[2]->initPane(pane); layout::Animator* animation = NULL; -- 2.49.1 From 8a2743f3c7fa529190a0ebee5736640511ab987b Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:01:45 +0000 Subject: [PATCH 07/11] match sd memory calculation --- config/43U/symbols.txt | 50 +++++----- include/scene/sdChannelMemory/iplSDMemory.h | 25 +++++ libs/NW4R/include/nw4r/lyt/pane.h | 4 + src/scene/sdChannelMemory/iplSDMemory.cpp | 105 ++++++++++++++++++++ 4 files changed, 159 insertions(+), 25 deletions(-) diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 2fcbd8d1..ac0c840e 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4853,32 +4853,32 @@ showRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE20; // type:function siz hideLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE80; // type:function size:0x64 hideRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECEE4; // type:function size:0x64 resetDialogPaneAnimations__Q33ipl5scene8SDMemoryFv = .text:0x813ECF48; // type:function size:0x13C -iplSDMemory_813ED084 = .text:0x813ED084; // type:function size:0x268 -iplSDMemory_813ED2EC = .text:0x813ED2EC; // type:function size:0x4CC -iplSDMemory_813ED7B8 = .text:0x813ED7B8; // type:function size:0xA4 -iplSDMemory_813ED85C = .text:0x813ED85C; // type:function size:0xC4 -iplSDMemory_813ED920 = .text:0x813ED920; // type:function size:0x124 -iplSDMemory_813EDA44 = .text:0x813EDA44; // type:function size:0x110 -iplSDMemory_813EDB54 = .text:0x813EDB54; // type:function size:0x78 -iplSDMemory_813EDBCC = .text:0x813EDBCC; // type:function size:0xC0 -iplSDMemory_813EDC8C = .text:0x813EDC8C; // type:function size:0x278 -iplSDMemory_813EDF04 = .text:0x813EDF04; // type:function size:0xA4 -iplSDMemory_813EDFA8 = .text:0x813EDFA8; // type:function size:0x130 -iplSDMemory_813EE0D8 = .text:0x813EE0D8; // type:function size:0xE0 -iplSDMemory_813EE1B8 = .text:0x813EE1B8; // type:function size:0x1A0 +calc__Q33ipl5scene8SDMemoryFv = .text:0x813ED084; // type:function size:0x268 +updateState__Q33ipl5scene8SDMemoryFv = .text:0x813ED2EC; // type:function size:0x4CC +onDialogState0__Q33ipl5scene8SDMemoryFv = .text:0x813ED7B8; // type:function size:0xA4 +onDialogState2__Q33ipl5scene8SDMemoryFv = .text:0x813ED85C; // type:function size:0xC4 +onDialogState3__Q33ipl5scene8SDMemoryFv = .text:0x813ED920; // type:function size:0x124 +onDialogState4__Q33ipl5scene8SDMemoryFv = .text:0x813EDA44; // type:function size:0x110 +onDialogState6__Q33ipl5scene8SDMemoryFv = .text:0x813EDB54; // type:function size:0x78 +onDialogState7__Q33ipl5scene8SDMemoryFv = .text:0x813EDBCC; // type:function size:0xC0 +onDialogState8__Q33ipl5scene8SDMemoryFv = .text:0x813EDC8C; // type:function size:0x278 +onDialogState9__Q33ipl5scene8SDMemoryFv = .text:0x813EDF04; // type:function size:0xA4 +onDialogState10__Q33ipl5scene8SDMemoryFv = .text:0x813EDFA8; // type:function size:0x130 +onDialogState11__Q33ipl5scene8SDMemoryFv = .text:0x813EE0D8; // type:function size:0xE0 +onDialogState12__Q33ipl5scene8SDMemoryFv = .text:0x813EE1B8; // type:function size:0x1A0 iplSDMemory_813EE358 = .text:0x813EE358; // type:function size:0x44 -iplSDMemory_813EE39C = .text:0x813EE39C; // type:function size:0xEC -iplSDMemory_813EE488 = .text:0x813EE488; // type:function size:0x1C4 -iplSDMemory_813EE64C = .text:0x813EE64C; // type:function size:0x12C -iplSDMemory_813EE778 = .text:0x813EE778; // type:function size:0xA0 -iplSDMemory_813EE818 = .text:0x813EE818; // type:function size:0x128 -iplSDMemory_813EE940 = .text:0x813EE940; // type:function size:0xE8 -iplSDMemory_813EEA28 = .text:0x813EEA28; // type:function size:0x84 -iplSDMemory_813EEAAC = .text:0x813EEAAC; // type:function size:0xE8 -iplSDMemory_813EEB94 = .text:0x813EEB94; // type:function size:0x148 -iplSDMemory_813EECDC = .text:0x813EECDC; // type:function size:0x11C -iplSDMemory_813EEDF8 = .text:0x813EEDF8; // type:function size:0x78 -iplSDMemory_813EEE70 = .text:0x813EEE70; // type:function size:0xC0 +onDialogState13__Q33ipl5scene8SDMemoryFv = .text:0x813EE39C; // type:function size:0xEC +onDialogState14__Q33ipl5scene8SDMemoryFv = .text:0x813EE488; // type:function size:0x1C4 +onDialogState15__Q33ipl5scene8SDMemoryFv = .text:0x813EE64C; // type:function size:0x12C +onDialogState16__Q33ipl5scene8SDMemoryFv = .text:0x813EE778; // type:function size:0xA0 +onDialogState17__Q33ipl5scene8SDMemoryFv = .text:0x813EE818; // type:function size:0x128 +onDialogState18__Q33ipl5scene8SDMemoryFv = .text:0x813EE940; // type:function size:0xE8 +onDialogState19__Q33ipl5scene8SDMemoryFv = .text:0x813EEA28; // type:function size:0x84 +onDialogState20__Q33ipl5scene8SDMemoryFv = .text:0x813EEAAC; // type:function size:0xE8 +onDialogState21__Q33ipl5scene8SDMemoryFv = .text:0x813EEB94; // type:function size:0x148 +onDialogState22__Q33ipl5scene8SDMemoryFv = .text:0x813EECDC; // type:function size:0x11C +onDialogState23__Q33ipl5scene8SDMemoryFv = .text:0x813EEDF8; // type:function size:0x78 +onDialogState24__Q33ipl5scene8SDMemoryFv = .text:0x813EEE70; // type:function size:0xC0 iplSDMemory_813EEF30 = .text:0x813EEF30; // type:function size:0x88 iplSDMemory_813EEFB8 = .text:0x813EEFB8; // type:function size:0x70C iplSDMemory_813EF6C4 = .text:0x813EF6C4; // type:function size:0x14 diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h index 2e25c421..296a5a5c 100644 --- a/include/scene/sdChannelMemory/iplSDMemory.h +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -22,6 +22,7 @@ namespace ipl { void create(EGG::Heap* heap, nand::LayoutFile* layoutFile, NandSDCardManager* manager); void setTitleLists(const TitleRange& nandTitles, const TitleRange& sdTitles); + bool calc(); void setScrollLimit(); void updateSideArrows(); void resetScrollArrows(); @@ -36,6 +37,30 @@ namespace ipl { void hideRightArrow(); private: + s32 updateState(); + void onDialogState0(); + void onDialogState2(); + bool onDialogState3(); + void onDialogState4(); + void onDialogState6(); + void onDialogState7(); + void onDialogState8(); + void onDialogState9(); + void onDialogState10(); + void onDialogState11(); + void onDialogState12(); + void onDialogState13(); + void onDialogState14(); + void onDialogState15(); + void onDialogState16(); + void onDialogState17(); + void onDialogState18(); + void onDialogState19(); + bool onDialogState20(); + void onDialogState21(); + bool onDialogState22(); + void onDialogState23(); + bool onDialogState24(); void resetDialogPaneAnimations(); layout::Object* mpMainLayout; diff --git a/libs/NW4R/include/nw4r/lyt/pane.h b/libs/NW4R/include/nw4r/lyt/pane.h index 4f0519af..3bff5dc5 100644 --- a/libs/NW4R/include/nw4r/lyt/pane.h +++ b/libs/NW4R/include/nw4r/lyt/pane.h @@ -88,7 +88,11 @@ namespace nw4r { PaneList& GetChildList() { return mChildList; } const math::VEC3& GetTranslate() { return mTranslate; } +#ifdef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE + void SetTranslate(const math::VEC3& translate); +#else void SetTranslate(const math::VEC3& translate) { mTranslate = translate; } +#endif void SetTranslate(const math::VEC2& translate) { SetTranslate(math::VEC3(translate.x, translate.y, 0.0f)); } const math::VEC3& GetRotate() const { return mRotate; } diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index f3b362fc..5b503f55 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -1,5 +1,7 @@ #define IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE +#define IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE #include "scene/sdChannelMemory/iplSDMemory.h" +#undef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE #undef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE #include "system/iplSystem.h" @@ -358,5 +360,108 @@ namespace ipl { } } } + + bool SDMemory::calc() { + bool result = false; + s32 stateResult = updateState(); + if (stateResult == 0) { + if (mScroller.calc(mDialogState == 10) == TRUE) { + resetDialogPaneAnimations(); + } + + nw4r::math::VEC3 translation(0.0f, mScroller.get(), 0.0f); + mpDialogLayout->FindPaneByName("N_Memo")->SetTranslate(translation); + + switch (mDialogState) { + case 0: + onDialogState0(); + break; + case 1: + mpPaneManagers[0]->update(); + mpPaneManagers[0]->calc(); + break; + case 2: + onDialogState2(); + break; + case 3: + result = onDialogState3(); + break; + case 4: + onDialogState4(); + break; + case 5: + mpPaneManagers[1]->update(); + mpPaneManagers[1]->calc(); + break; + case 6: + onDialogState6(); + break; + case 7: + onDialogState7(); + break; + case 8: + onDialogState8(); + break; + case 9: + onDialogState9(); + break; + case 10: + onDialogState10(); + break; + case 11: + onDialogState11(); + break; + case 12: + onDialogState12(); + break; + case 13: + onDialogState13(); + break; + case 14: + onDialogState14(); + break; + case 15: + onDialogState15(); + break; + case 16: + onDialogState16(); + break; + case 17: + onDialogState17(); + break; + case 18: + onDialogState18(); + break; + case 19: + onDialogState19(); + break; + case 20: + result = onDialogState20(); + break; + case 21: + onDialogState21(); + break; + case 22: + result = onDialogState22(); + break; + case 23: + onDialogState23(); + break; + case 24: + result = onDialogState24(); + break; + case 25: + result = true; + break; + } + } + + mpMainLayout->calc(); + mpTitleLayout->calc(); + mpDialogLayout->calc(); + mpProgressLayout->calc(); + + return stateResult == 2 ? true : result; + } } } -- 2.49.1 From 90cf1715c4dfd313532c0d20d823a7824297d2fb Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:43:39 +0000 Subject: [PATCH 08/11] decompile sd memory dialog states --- include/scene/sdChannelMemory/iplSDMemory.h | 18 +- include/system/iplDialogWindow.h | 4 + src/scene/sdChannelMemory/iplSDMemory.cpp | 214 ++++++++++++++++++++ 3 files changed, 224 insertions(+), 12 deletions(-) diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h index 296a5a5c..6352f88c 100644 --- a/include/scene/sdChannelMemory/iplSDMemory.h +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -68,19 +68,13 @@ namespace ipl { layout::Object* mpDialogLayout; layout::Object* mpProgressLayout; gui::PaneManager* mpPaneManagers[3]; - u32 mDialogState; - u32 mProcessState; - u32 mDisplayMode; - u32 mMessageId; + s32 mDialogState; + s32 mProcessState; + s32 mDisplayMode; + s32 mMessageId; u32 mErrorCode; - u32 mCommandState; - u32 mSelectionState; - u32 mDisplayState; - u32 mCurrentOperation; - u32 mCurrentResult; - u32 mDialogFlags; - u32 mLayoutFlags; - u32 mPanelFlags; + u32 mPanelStates[3]; + u32 mTitlePanelStates[5]; u32 mPanelAnimationStates[4]; NandSDCardManager* mpNandSDCardManager; TitleRange mNandTitleRange; diff --git a/include/system/iplDialogWindow.h b/include/system/iplDialogWindow.h index 4a2498df..5fe75217 100644 --- a/include/system/iplDialogWindow.h +++ b/include/system/iplDialogWindow.h @@ -118,6 +118,10 @@ namespace ipl { int getLastResult() { return mLastResult; } /** @return If the dialog is moving onto the next state. */ bool doingNextState() { return mbNextState; } +#ifdef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR + int getStateForSDMemory() const { return mState; } + int getResultForSDMemory() const { return mResult; } +#endif /*=================*/ /* DIALOG BUTTON 0 */ diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index 5b503f55..eb7cd7d3 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -1,6 +1,8 @@ #define IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE #define IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE +#define IPL_SDMEMORY_DIALOG_STATE_ACCESSOR #include "scene/sdChannelMemory/iplSDMemory.h" +#undef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR #undef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE #undef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE @@ -463,5 +465,217 @@ namespace ipl { return stateResult == 2 ? true : result; } + + void SDMemory::onDialogState0() { + if (!mpMainLayout->isPlaying(-1)) { + for (int i = 0; i < 3; i++) { + mPanelStates[i] = 0; + mpPaneManagers[0]->initPane(mpMainLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sControlPaneNames[i], true)); + } + + mDialogState = 1; + } + } + + void SDMemory::onDialogState2() { + if (!mpMainLayout->isPlaying(-1)) { + mpMainLayout->getAnim(1)->initAnmFrame(); + mpMainLayout->getAnim(1)->play(); + + if (mProcessState == 2) { + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + mTransferFlags[1] = 0; + } + + mDialogState = 3; + } + } + + void SDMemory::onDialogState4() { + if (!mpTitleLayout->isPlaying(-1)) { + if (mDisplayMode == 4) { + for (int i = 0; i < 5; i++) { + mTitlePanelStates[i] = 0; + mpPaneManagers[1]->initPane(mpTitleLayout->FindPaneByName(sControlPaneNames[i + 3])); + } + } else { + for (int i = 1; i < 5; i++) { + mTitlePanelStates[i] = 0; + mpPaneManagers[1]->initPane(mpTitleLayout->FindPaneByName(sControlPaneNames[i + 7])); + } + } + + mDialogState = 5; + } + } + + void SDMemory::onDialogState6() { + if (!mpTitleLayout->isPlaying(-1)) { + mDialogState = 7; + mpTitleLayout->getAnim(1)->initAnmFrame(); + mpTitleLayout->getAnim(1)->play(); + } + } + + void SDMemory::onDialogState7() { + if (!mpTitleLayout->isPlaying(-1)) { + switch (mProcessState) { + case 4: + mDialogState = 0; + mpMainLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_BT_TARGETTING"); + break; + default: + mTransferStartTime = 0; + mTransferFrame = 0; + System::getDialog()->callBtn0NoShade(0xCC, 0, true); + mDialogState = 8; + break; + } + } + } + + void SDMemory::onDialogState9() { + if (!mpDialogLayout->isPlaying(0)) { + for (int i = 0; i < 4; i++) { + mPanelAnimationStates[i] = 0; + mpPaneManagers[2]->initPane(mpDialogLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sDialogPaneNames[i], true)); + } + + mDialogState = 10; + } + } + + void SDMemory::onDialogState10() { + controller::Interface* masterController = System::getMasterController(); + if (mScroller.isActive()) { + updateSideArrows(); + if (mScroller.getBInst().isActive() ? false : true) { + if (masterController->down(controller::BTN_UP)) { + mScroller.scrollUpByCon(); + } else if (masterController->down(controller::BTN_DOWN)) { + mScroller.scrollDownByCon(); + } + } + } + + bool previousDownEnd = !!mControllerFlags[0]; + bool previousUpEnd = !!mControllerFlags[1]; + updateScrollArrows(previousDownEnd, previousUpEnd, mScroller.isUpEnd(), mScroller.isDownEnd()); + + if (mScroller.getBInst().isActive() ? false : true) { + mpPaneManagers[2]->update(); + } + mpPaneManagers[2]->calc(); + } + + void SDMemory::onDialogState11() { + if (!mpDialogLayout->isPlaying(4) && !mpDialogLayout->isPlaying(7)) { + if (mProcessState < 4 && mProcessState >= 2) { + mDialogState = 12; + mpDialogLayout->getAnim(1)->initAnmFrame(); + mpDialogLayout->getAnim(1)->play(); + + if (mControllerFlags[0] != 0) { + hideDownArrow(); + } + if (mControllerFlags[1] != 0) { + hideUpArrow(); + } + } else { + mDialogState = 10; + } + } + } + + void SDMemory::onDialogState19() { + if (!mpNandSDCardManager->getWorker()->is_working()) { + if (mpNandSDCardManager->getWorker()->get_async_result() == 0) { + mDialogState = 13; + } else { + System::getDialog()->terminate(); + mDialogState = 20; + mErrorCode = 1; + mMessageId = 0xAE; + } + } + } + + bool SDMemory::onDialogState20() { + DialogWindow* dialog = System::getDialog(); + if (dialog->getStateForSDMemory() == 4 && mTransferFlags[1] && mErrorCode == 0) { + mTransferFlags[1] = 0; + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + } + + if (System::getDialog()->getLastResult() != -1) { + if (mErrorCode == 0) { + mTransferFlags[0] = 1; + mDialogState = 25; + return true; + } + + mDialogState = 23; + } + + return false; + } + + bool SDMemory::onDialogState22() { + DialogWindow* dialog = System::getDialog(); + if (dialog->getStateForSDMemory() == 3 && dialog->getResultForSDMemory() == 1) { + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + mTransferFlags[1] = 0; + } + + if (System::getDialog()->getLastResult() != -1) { + if (System::getDialog()->getLastResult() == 1) { + mErrorCode = 4; + mDialogState = 25; + return true; + } + + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_CANCEL"); + mDialogState = 0; + } + + return false; + } + + void SDMemory::onDialogState23() { + switch (mMessageId) { + case 0xBF: + case 0xB5: + System::getDialog()->callBtn1NoShade(mMessageId, 0xA5); + break; + default: + System::getDialog()->callBtn1NoShade(mMessageId, 0x2E); + break; + } + + mDialogState = 24; + } + + bool SDMemory::onDialogState24() { + if (System::getDialog()->getStateForSDMemory() == 3) { + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + mTransferFlags[1] = 0; + } + + if (System::getDialog()->getLastResult() != -1) { + mTransferFlags[0] = 1; + System::getHomeButtonMenu()->enable(); + mDialogState = 25; + return true; + } + + return false; + } } } -- 2.49.1 From a4e784149899a4d036c0229c3d6849efe3b0fbea Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:49:34 -0500 Subject: [PATCH 09/11] Decompile RVL SDK wad to 16/40 functions (#246) * decompile wad import check * decompile wad stream helpers * match wad unpack routines * match wad termination scan * decompile backup WAD header * decompile WAD unpack formats * decompile wad export worker * refine content index scan * decompile WAD signature verification * decompile wad hash path * match savedata validation * match wad title metadata query * match BroadOn unpack offsets * tune WAD export chunk comparison * reuse WAD content index offsets * tune WAD hash chunk comparison * tune WAD content index lookup * match WAD transfer metadata helpers * refine WAD allocator dispatch * refine WAD stream dispatch * decompile WAD import dispatch * decompile WAD backup helpers * refine WAD savedata verification * decompile WAD DVD boot import * decompile WAD DVD title import * refine WAD DVD stream parsing * match WAD memory free * match WAD allocator and content checks --- libs/RVL_SDK/src/wad/wad.c | 3479 ++++++++++++++++++++++++++++++++++++ 1 file changed, 3479 insertions(+) create mode 100644 libs/RVL_SDK/src/wad/wad.c diff --git a/libs/RVL_SDK/src/wad/wad.c b/libs/RVL_SDK/src/wad/wad.c new file mode 100644 index 00000000..0f2c89e1 --- /dev/null +++ b/libs/RVL_SDK/src/wad/wad.c @@ -0,0 +1,3479 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef union WADStreamHandle { + DVDFileInfo dvd; + NANDFileInfo nand; + CNTFileInfoDVD contentDvd; + CNTFileInfoNAND contentNand; + FAFILE* fa; + void* memoryBase; +} WADStreamHandle; + +typedef struct __attribute__((aligned(32))) WADStream { + WADLocation location; + WADStreamHandle handle; +} WADStream; + +typedef union WADTitleMetadata { + ESTitleMetaHeader tmd; + ESTitleId backupTitleId; + u8 bytes[0x80]; +} WADTitleMetadata; + +typedef struct WADBroadOnHeader { + u32 headerSize; + u32 contentOffset; + u32 certSize; + u32 crlSize; + u32 ticketSize; + u32 titleMetaSize; + u32 contentSize; + u32 fileListSize; +} WADBroadOnHeader; + +typedef struct WADUnpackInfo { + s32 type; + s32 headerInfo; + u16 cidxMode; + u8 reserved_0x0a[2]; + u32 size_0x0c; + u32 offset_0x10; + void* buffer_0x14; + u32 size_0x18; + u32 size_0x1c; + u32 offset_0x20; + void* buffer_0x24; + u32 size_0x28; + u32 size_0x2c; + u32 offset_0x30; + void* buffer_0x34; + u32 size_0x38; + u32 sectionSize; + u32 sectionOffset; + ESTitleMeta* titleMeta; + u32 titleMetaSize; + u32 contentSize; + u32 contentOffset; + u32 metaSize; + u32 metaOffset; + u32 fileListSize; + u32 fileOffset; + u32 fileCount; + void* contentIndex; + void* fileNames; +} WADUnpackInfo; + +typedef struct WADFileHeader { + u32 magic; + u32 fileSize; + u8 flags[3]; + char name[0x40]; + u8 reserved_0x4b[5]; + u8 iv[0x10]; + u8 reserved_0x60[0x20]; +} WADFileHeader; + +typedef struct WADBootImportParts { + s32 headerInfo[2]; + u32 certificateSize; + void* certificates; + u32 crlSize; + void* crls; + u32 ticketSize; + void* ticket; + u32 titleMetaSize; + void* titleMeta; +} WADBootImportParts; + +typedef struct WADBackupFileHeader { + u32 magic; + u32 fileSize; + u8 flags[3]; + char path[0x75]; +} WADBackupFileHeader; + +typedef struct WADSaveDataHeader { + u32 format; + u32 flags; + u32 reserved_0x08; + u32 saveType; + u8 reserved_0x10[0x50]; + u32 fileSize; + u32 magic; + u8 reserved_0x68[0x18]; +} WADSaveDataHeader; + +typedef struct WADThreadStack { + u8 bytes[0x1000]; +} WADThreadStack; + +typedef struct WADFileEntry { + u32 fileSize; + u8 flags[4]; + char name[0x40]; +} WADFileEntry; + +typedef union WADBackupHeaderBlock { + WADBackupHeader header; + u8 bytes[0x80]; +} WADBackupHeaderBlock; + +typedef union WADBackupTitleMetaBuffer { + ESTmdView view; + u8 data[0x4A00]; +} WADBackupTitleMetaBuffer; + +typedef struct WADBackupSignature { + u8 header[0x40]; + u8 firstCertificate[0x180]; + u8 secondCertificate[0x180]; +} WADBackupSignature; + +typedef struct WADVerificationCertificateBundle { + u8 caProduction[0x400]; + u8 msProduction[0x240]; + u8 caDevelopment[0x400]; + u8 msDevelopment[0x240]; + u8 firstCertificate[0x180]; + u8 secondCertificate[0x180]; +} WADVerificationCertificateBundle; + +typedef struct WADVerificationWorkspace { + void* readBuffer[16]; + u8 digest[0x40]; + u8 hashContext[0xC0]; +} WADVerificationWorkspace; + +#pragma pack(push, 4) +typedef struct WADFileMetadataView { + u8 reserved_0x00[0x18C]; + ESTitleId titleId; + u8 reserved_0x194[0x48]; + u16 titleVersion; +} WADFileMetadataView; +#pragma pack(pop) + +typedef struct __attribute__((aligned(32))) WADImportWorkspace { + u8 transferId[0x20]; + WADFileHeader fileHeader; + u8 wadHeader[0x80]; + WADUnpackInfo unpackInfo; + WADStream stream; +} WADImportWorkspace; + +typedef struct WADImportTransfer { + s32 error; + u32 chunkSize; + BOOL ready[2]; + void* buffers[2]; + OSMutex mutex[2]; + OSCond waitCond[2]; + OSCond signalCond[2]; +} WADImportTransfer; + +typedef struct WADImportLoopArgs { + s32 fd; + u32 size; + WADImportTransfer* transfer; +} WADImportLoopArgs; + +typedef WADImportLoopArgs WADExportLoopArgs; + +typedef struct WADHashThreadArgs { + void* context; + u32 size; + WADImportTransfer* transfer; +} WADHashThreadArgs; + +#define WAD_STREAM_ALIGNMENT 0x40 +#define WAD_READ_ALIGNMENT 0x20 +#define WAD_ALIGN32(value) (((value) + WAD_READ_ALIGNMENT - 1) & ~(WAD_READ_ALIGNMENT - 1)) + +s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32, u32); +size_t WADReadStream(WADStream* stream, void** buffer, size_t size, s32 offset); +void WADCloseStream(WADStream* stream); +s32 WADWriteStream(WADStream* stream, void* buffer, u32 size); +s32 WADSeekStream(WADStream* stream, u32 offset, s32 origin); +static s32 WAD_815C2F44(WADHeader* header, s32* headerInfo); +static s32 _WADGetTitleVer(WADHeader* header, ESTitleId* titleId, u16* titleVersion, s32 type, + s32 headerInfo); +static s32 _WADUnpackIRD(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode); +static s32 _WADUnpackBroadOn(WADBroadOnHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode); +static s32 _WADUnpackBackup(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 flags); +static s32 _WADUnpack(void* header, WADStream* stream, WADUnpackInfo* info, MEMAllocator* allocator, + u32 offset, u32 flags, u32 mode); +static s32 _WADHash(WADStream* stream, u32 offset, u32 size, void* context, void* buffer, + u32 chunkSize, void* secondBuffer, void* threadStack, u32 threadStackSize); +void WAD_815C4A2C(WADImportTransfer* transfer, void* firstBuffer, void* secondBuffer, + u32 chunkSize); +s32 WADVerify(WADStream* stream, MEMAllocator* allocator, u32 offset, u32 size); +s32 _WADGetCidxCount(const ESContentMask* contentMask); +static s32 _WADGetCidx(const ESContentMask* contentMask, u32 contentNumber); +static s32 _WADGetTransferId(void* transferId); +static void* _WADMemAlloc(MEMAllocator* allocator, u32 size); +static void _WADMemFree(MEMAllocator* allocator, void* buffer); +static s32 _WADCanImportFile(const WADFileHeader* fileHeader, u32 transferId, const void* fileNames, + const void* transferIdBuffer); +static void _WADFreeMemory(WADUnpackInfo* info, MEMAllocator* allocator); +static s32 WAD_815BFFA8(WADImportLoopArgs* args); +static s32 _WADBackupGetFiles(const char* path, u32 flags, MEMAllocator* allocator, + u32* fileCount, WADBackupFileHeader* files); +static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* contentMask, + u32 fileCount, WADBackupFileHeader* files, u32* titleMetaSize, + u32* contentDataSize, u32* totalSize); +static s32 _WADCheckContents(ESTmdView* titleMeta, ESContentMask* contentMask); +static void _WADRandPad(void* buffer, u32 size); +static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, + MEMAllocator* allocator, u32 offset); +static void _WADCleanTmpDir(MEMAllocator* allocator); +u32 _WADIsTerminated(const char* text, u32 maxLength); + +extern s32 ES_GetBoot2Version(u32* version); +extern s32 SHA1Reset(void* context); +extern s32 SHA1Input(void* context, const void* data, u32 size); +extern s32 SHA1Result(void* context, void* digest); +extern char* strrchr(const char* string, int character); + +s32 WADGetTitleVersionEx(char* path, ESTitleId* titleId, u16* titleVersion, WADLocation location, u32 offset) { + BOOL streamOpened; + WADStream stream ALIGN32; + u8 headerBytes[0x20] ALIGN32; + WADTitleMetadata metadata ALIGN32; + s32 headerInfo; + WADTitleMetadata* metadataBuffer = &metadata; + WADHeader* headerBuffer = (WADHeader*)headerBytes; + s32 result; + u32 titleDataOffset; + s32 type; + + streamOpened = FALSE; + titleDataOffset = 0; + if (path == 0) { + result = -3000; + } else if ((offset & 0x3F) != 0) { + result = -3007; + } else { + result = WADOpenStream(location, path, &stream, 0, 0); + streamOpened = TRUE; + if (result == 0) { + result = WADReadStream(&stream, (void**)&headerBuffer, 0x20, offset); + if (result != 0x20) { + result = -3005; + goto done; + } + type = WAD_815C2F44(headerBuffer, &headerInfo); + if (type == 0) { + result = -3001; + goto done; + } + if (((type == 2) && (headerBuffer->tmdSize == 0)) || + ((type == 1) && (headerBuffer->ticketSize == 0))) { + result = -3002; + if (headerInfo == 2) { + titleDataOffset = 0x60; + } else { + goto done; + } + } + + if (titleDataOffset == 0) { + result = _WADGetTitleVer(headerBuffer, 0, 0, type, headerInfo); + if (result == 0) { + result = -3002; + goto done; + } + titleDataOffset = result + 0x180; + result = WADReadStream(&stream, (void**)&metadataBuffer, 0x80, + offset + titleDataOffset); + if ((u32)result != 0x80) { + result = -3005; + goto done; + } + result = 0; + if (titleId != 0) { + titleId[0] = metadataBuffer->tmd.titleId; + } + if (titleVersion != 0) { + *titleVersion = metadataBuffer->tmd.titleVersion; + } + } else { + result = WADReadStream(&stream, (void**)&metadataBuffer, 0x20, + offset + titleDataOffset); + if (result != 0x20) { + result = -3005; + goto done; + } + result = 0; + if (titleId != 0) { + *titleId = metadataBuffer->backupTitleId; + } + } + } + } + +done: + if (streamOpened) { + WADCloseStream(&stream); + } + return result; +} + +s32 WADCheckImport(ESTitleId titleId, u32 titleVersion) { + u16 installedVersion; + s32 result; + + if (__OSInIPL && (titleId == 0x0001000248414141ULL) && (titleVersion == 0xFF00)) { + return 0; + } + + result = WADGetInstalledVersion(titleId, &installedVersion); + if (result == -3002) { + return 1; + } + if (result == 0) { + if (__OSInIPL) { + if (titleVersion > installedVersion) { + return 1; + } + } else if (titleVersion >= installedVersion) { + return 1; + } + } + return 0; +} + +s32 WADGetInstalledVersion(ESTitleId titleId, u16* version) { + u32 tmdSize; + u32 installedVersion; + ESTmdView tmdView __attribute__((aligned(32))); + ESTmdView* viewBuffer = &tmdView; + s32 result; + + if (version == 0) { + return -3000; + } + if (titleId == 0x0000000100000001ULL) { + result = ES_GetBoot2Version(&installedVersion); + if (result == 0) { + *version = installedVersion; + } + return result; + } + + result = ES_GetTmdView(titleId, 0, &tmdSize); + if (result == -106) { + return -3002; + } + if (result != 0) { + return result; + } + if (tmdSize > sizeof(ESTmdView)) { + return -3000; + } + result = ES_GetTmdView(titleId, viewBuffer, &tmdSize); + if (result == 0) { + *version = viewBuffer->head.titleVersion; + } + return result; +} + +s32 WADImportGetBlocks(char* path, MEMAllocator* allocator, WADLocation location, u32 offset, u32 flags, + WADBlocks* blocks, u32* fileListOut) { + WADImportWorkspace workspace ALIGN32; + void* wadHeader = workspace.wadHeader; + s32 result; + u32 fileOffset; + void* allocatedFiles; + BOOL streamOpened; + u32 transferId; + u32 contentCount; + ESTitleMeta* titleMeta; + ESContentMeta* contentMeta; + u32 index; + + streamOpened = FALSE; + fileOffset = 0; + allocatedFiles = 0; + memset(&workspace.unpackInfo, 0, sizeof(WADUnpackInfo)); + if (fileListOut != 0) { + *fileListOut = 0; + } + if ((allocator == 0) || (allocator->heap == 0) || (path == 0) || (blocks == 0)) { + result = -3000; + } else if ((offset & 0x3F) != 0) { + result = -3007; + } else { + result = WADOpenStream(location, path, &workspace.stream, 0, 0); + streamOpened = TRUE; + if (result == 0) { + result = WADReadStream(&workspace.stream, &wadHeader, 0x80, offset); + if (result != 0x80) { + result = -3005; + } else { + result = _WADUnpack(wadHeader, &workspace.stream, &workspace.unpackInfo, allocator, + offset, flags & ~4, 1); + if (result == 0) { + memset(blocks, 0, sizeof(WADBlocks)); + titleMeta = workspace.unpackInfo.titleMeta; + if (titleMeta != 0) { + if ((flags & 4) == 0) { + blocks->unkBlocks += (workspace.unpackInfo.sectionSize + 0x3FFF) >> 14; + blocks->unkInodes = 1; + } + if (workspace.unpackInfo.cidxMode < 1) { + contentCount = titleMeta->head.numContents; + } else { + contentCount = _WADGetCidxCount(workspace.unpackInfo.contentIndex); + if (contentCount > titleMeta->head.numContents) { + result = -3001; + goto cleanup; + } + } + contentMeta = titleMeta->contents; + for (index = 0; index < contentCount; index++) { + if (workspace.unpackInfo.cidxMode >= 1) { + s32 selectedIndex = _WADGetCidx(workspace.unpackInfo.contentIndex, index); + if ((selectedIndex < 0) || + (titleMeta->head.numContents <= selectedIndex)) { + result = -3001; + goto cleanup; + } + contentMeta = titleMeta->contents + selectedIndex; + result = 0; + } + if ((contentMeta->type & 0x8000) == 0) { + blocks->privateInodes++; + blocks->privateBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; + } else { + blocks->sharedInodes++; + blocks->sharedBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; + } + contentMeta++; + } + } + if ((workspace.unpackInfo.fileListSize != 0) && + (workspace.unpackInfo.fileCount != 0)) { + transferId = _WADGetTransferId(workspace.transferId); + if ((fileListOut == 0) || + ((allocatedFiles = _WADMemAlloc(allocator, + workspace.unpackInfo.fileCount * 0x48)) != 0)) { + fileOffset = workspace.unpackInfo.fileOffset; + for (index = 0; index < workspace.unpackInfo.fileCount; index++) { + WADFileHeader* fileHeader = &workspace.fileHeader; + result = WADReadStream(&workspace.stream, (void**)&fileHeader, 0x80, + offset + fileOffset); + if (result != 0x80) { + result = -3005; + goto cleanup; + } + result = 0; + if (_WADCanImportFile(fileHeader, transferId, + workspace.unpackInfo.fileNames, + workspace.transferId) != 0) { + blocks->fileBlocks += (fileHeader->fileSize + 0x3FFF) >> 14; + if (fileListOut != 0) { + WADFileEntry* fileEntries = allocatedFiles; + fileEntries += blocks->fileInodes; + fileEntries->fileSize = fileHeader->fileSize; + fileEntries->flags[0] = fileHeader->flags[0]; + fileEntries->flags[1] = fileHeader->flags[1]; + fileEntries->flags[2] = fileHeader->flags[2]; + fileEntries->flags[3] = 0; + strncpy(fileEntries->name, fileHeader->name, 0x40); + } + blocks->fileInodes++; + } + fileOffset = ((fileOffset + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1)) + fileHeader->fileSize; + fileOffset = (fileOffset + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + } + if (fileListOut != 0) { + *fileListOut = (u32)allocatedFiles; + } + } else { + result = -3003; + } + } + } + } + } + } + +cleanup: + _WADFreeMemory(&workspace.unpackInfo, allocator); + if ((fileListOut != 0) && (result != 0)) { + if (allocatedFiles != 0) { + _WADMemFree(allocator, allocatedFiles); + } + *fileListOut = 0; + } + if (streamOpened) { + WADCloseStream(&workspace.stream); + } + return result; +} + +static s32 WAD_815BFFA8(WADImportLoopArgs* args) { + s32 fd = args->fd; + s32 result = 0; + u32 remaining = args->size; + u32 bufferIndex = 0; + WADImportTransfer* transfer = args->transfer; + + while ((remaining != 0) && (result == 0)) { + u32 size = remaining; + OSMutex* mutex; + + if (remaining > transfer->chunkSize) { + size = transfer->chunkSize; + } + mutex = &transfer->mutex[bufferIndex]; + OSLockMutex(mutex); + while (transfer->ready[bufferIndex] == 0) { + OSWaitCond(&transfer->signalCond[bufferIndex], mutex); + } + result = ES_ImportContentData(fd, transfer->buffers[bufferIndex], size); + transfer->ready[bufferIndex] = 0; + if (result != 0) { + transfer->error = 1; + } + OSUnlockMutex(mutex); + OSSignalCond(&transfer->waitCond[bufferIndex]); + remaining -= size; + bufferIndex ^= 1; + } + return result; +} + +s32 WADImportEx(char* path, MEMAllocator* allocator, WADLocation location, u32 offset, u32 flags, + WADProcessCallback processCallback) { + WADImportWorkspace workspace ALIGN32; + WADSaveDataHeader wadHeader ALIGN32; + WADFileHeader backupHeader ALIGN32; + WADImportTransfer transfer; + WADImportLoopArgs threadArgs; + OSThread importThread; + NANDFileInfo backupFile; + NANDStatus fileStatus; + NANDStatus updatedFileStatus; + ESContentId* installedContentIds = 0; + ESTitleMeta* installedTitleMeta = 0; + ESContentMeta* matchingContents = 0; + ESHash* sharedContentHashes = 0; + void* firstBuffer = 0; + void* secondBuffer = 0; + WADThreadStack* threadStack = 0; + void* wadHeaderBuffer = &wadHeader; + void* fileHeaderBuffer = &backupHeader; + u8 transferId[0x20] ALIGN32; + u32 fileOffset = 0; + u32 importedBytes = 0; + u32 installedContentCount = 0; + u32 installedTmdSize = 0; + u32 sharedContentCount = 0; + u32 contentCount = 0; + u32 contentIndex; + u32 listIndex; + u32 sizeRemaining; + u32 transferIdValue; + s32 result = 0; + s32 streamOpened = FALSE; + s32 backupFileOpened = FALSE; + s32 titleImportStarted = FALSE; + s32 contentImportStarted = FALSE; + s32 threadCreated = FALSE; + s32 contentFd = 0; + s32 importExistingTitle = TRUE; + s32 existingTmdAvailable = FALSE; + s32 fileReadResult; + u32 importedContentCount = 0; + u32 bufferIndex = 0; + u32 callbackTotal = 0; + u32 installedContentIndex = 0; + u32 sharedContentIndex; + u32 contentFileOffset; + u32 pathFileIndex; + s32 matchFound; + s32 listResult; + s32 titleVersion; + u32 contentSize; + u32 chunkSize; + u32 readSize; + u32 bootSize; + u32 alignedSize; + u32 callbackDone; + u32 currentTitleId; + u32 currentTitleVersion; + u32 currentContentId; + u32 importedFileCount; + u32 savedataFileIndex; + s32 importResult; + u32 threadPriority; + const char* functionName = "WADImportEx"; + + memset(&workspace.unpackInfo, 0, sizeof(WADUnpackInfo)); + memset(&transfer, 0, sizeof(transfer)); + if ((path == 0) || (allocator == 0) || (allocator->heap == 0)) { + result = -3000; + goto cleanup; + } + if ((offset & 0x3F) != 0) { + result = -3007; + goto cleanup; + } + if (processCallback != 0) { + processCallback(0, 0, FALSE); + } + result = WADOpenStream(location, path, &workspace.stream, 0, 0); + streamOpened = TRUE; + if (result != 0) { + goto cleanup; + } + result = WADReadStream(&workspace.stream, &wadHeaderBuffer, sizeof(wadHeader), offset); + if (result != sizeof(wadHeader)) { + result = -3005; + goto cleanup; + } + result = _WADUnpack(&wadHeader, &workspace.stream, &workspace.unpackInfo, allocator, offset, + flags, 0); + if (result != 0) { + goto cleanup; + } + importedBytes = workspace.unpackInfo.contentOffset; + callbackTotal = workspace.unpackInfo.contentSize + workspace.unpackInfo.fileListSize; + if (((flags & 8) != 0) && (workspace.unpackInfo.titleMeta != 0)) { + if (workspace.unpackInfo.headerInfo != 2) { + result = -3001; + goto cleanup; + } + result = ES_GetTicketViews(workspace.unpackInfo.titleMeta->head.titleId, 0, + &installedContentCount); + if (result != 0) { + goto cleanup; + } + if (installedContentCount == 0) { + result = -1028; + goto cleanup; + } + } + if ((workspace.unpackInfo.titleMeta != 0) && + (((workspace.unpackInfo.size_0x18 == 1) && + (workspace.unpackInfo.size_0x0c == 1)) || + (workspace.unpackInfo.headerInfo == 3))) { + bootSize = (workspace.unpackInfo.titleMetaSize + 0x0F) & ~0x0F; + alignedSize = (bootSize + 0x1F) & ~0x1F; + firstBuffer = _WADMemAlloc(allocator, alignedSize); + if (firstBuffer == 0) { + result = -3003; + goto cleanup; + } + result = WADReadStream(&workspace.stream, &firstBuffer, alignedSize, + offset + importedBytes); + if ((u32)result != alignedSize) { + result = -3005; + goto cleanup; + } + result = ES_ImportBoot(workspace.unpackInfo.buffer_0x34, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.buffer_0x24, + workspace.unpackInfo.size_0x1c, firstBuffer, + workspace.unpackInfo.titleMetaSize); + goto cleanup; + } + if ((workspace.unpackInfo.titleMeta != 0) && + (workspace.unpackInfo.buffer_0x34 != 0)) { + result = ES_ImportTicket(workspace.unpackInfo.buffer_0x34, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.buffer_0x24, + workspace.unpackInfo.size_0x1c, 0); + if (result != 0) { + goto cleanup; + } + } + if (processCallback != 0) { + processCallback(0, callbackTotal, FALSE); + } + if (workspace.unpackInfo.titleMeta != 0) { + if (workspace.unpackInfo.cidxMode == 0) { + contentCount = workspace.unpackInfo.titleMeta->head.numContents; + } else { + contentCount = _WADGetCidxCount(workspace.unpackInfo.contentIndex); + if (workspace.unpackInfo.titleMeta->head.numContents < contentCount) { + result = -3001; + goto cleanup; + } + } + result = ES_ListTmdContentsOnCard(workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, 0, + &installedContentCount); + if ((result == 0) && (installedContentCount != 0)) { + installedContentIds = _WADMemAlloc(allocator, installedContentCount * sizeof(ESContentId)); + if (installedContentIds == 0) { + result = -3003; + goto cleanup; + } + result = ES_ListTmdContentsOnCard(workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, + installedContentIds, &installedContentCount); + if ((result == 0) && + (ES_GetTmd(workspace.unpackInfo.titleMeta->head.titleId, 0, + &installedTmdSize) == 0)) { + alignedSize = (installedTmdSize + 0x1F) & ~0x1F; + installedTitleMeta = _WADMemAlloc(allocator, alignedSize); + if (installedTitleMeta == 0) { + result = -3003; + goto cleanup; + } + result = ES_GetTmd(workspace.unpackInfo.titleMeta->head.titleId, + installedTitleMeta, &installedTmdSize); + if (result == 0) { + importExistingTitle = FALSE; + } + } + } + if (!importExistingTitle && (installedContentCount != 0)) { + matchingContents = _WADMemAlloc(allocator, installedContentCount * sizeof(ESContentMeta)); + if (matchingContents == 0) { + result = -3003; + goto cleanup; + } + installedContentIndex = 0; + for (listIndex = 0; listIndex < installedContentCount; listIndex++) { + for (contentIndex = 0; + contentIndex < installedTitleMeta->head.numContents; contentIndex++) { + if (installedContentIds[listIndex] == + installedTitleMeta->contents[contentIndex].cid) { + memcpy(&matchingContents[installedContentIndex], + &installedTitleMeta->contents[contentIndex], sizeof(ESContentMeta)); + installedContentIndex++; + } + } + } + } + result = ES_ListSharedContents(&sharedContentCount, 0); + if (result == 0) { + alignedSize = (sharedContentCount * sizeof(ESHash) + 0x1F) & ~0x1F; + sharedContentHashes = _WADMemAlloc(allocator, alignedSize); + if ((sharedContentHashes == 0) && (sharedContentCount != 0)) { + result = -3003; + goto cleanup; + } + result = ES_ListSharedContents(&sharedContentCount, sharedContentHashes); + if ((result != 0) && (sharedContentHashes != 0)) { + _WADMemFree(allocator, sharedContentHashes); + sharedContentHashes = 0; + } + } + result = ES_ImportTitleInit(workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.buffer_0x24, + workspace.unpackInfo.size_0x1c, + workspace.unpackInfo.headerInfo, 1); + if (result != 0) { + goto cleanup; + } + titleImportStarted = TRUE; + if ((flags & 2) == 0) { + for (contentIndex = 0; contentIndex < contentCount; contentIndex++) { + ESContentMeta* content; + s32 titleMetaIndex = contentIndex; + matchFound = FALSE; + if (workspace.unpackInfo.cidxMode != 0) { + titleMetaIndex = _WADGetCidx(workspace.unpackInfo.contentIndex, contentIndex); + if ((titleMetaIndex < 0) || + ((s32)workspace.unpackInfo.titleMeta->head.numContents <= titleMetaIndex)) { + result = -3001; + goto cleanup; + } + } + content = &workspace.unpackInfo.titleMeta->contents[titleMetaIndex]; + if (!importExistingTitle) { + for (listIndex = 0; listIndex < installedContentCount; listIndex++) { + ESContentMeta* installedContent = &matchingContents[listIndex]; + if ((content->cid == installedContent->cid) && + (memcmp(content->hash, installedContent->hash, sizeof(ESHash)) == 0) && + (content->type == installedContent->type)) { + matchFound = TRUE; + } + } + } + if (((content->type & 0x8000) != 0) && + (sharedContentHashes != 0) && !matchFound) { + for (sharedContentIndex = 0; sharedContentIndex < sharedContentCount; + sharedContentIndex++) { + if (memcmp(content->hash, sharedContentHashes[sharedContentIndex], + sizeof(ESHash)) == 0) { + matchFound = TRUE; + } + } + } + if (matchFound) { + importedBytes += (content->size + 0x0F) & ~0x0F; + if (processCallback != 0) { + processCallback(importedBytes - workspace.unpackInfo.contentOffset, + callbackTotal, FALSE); + } + } else { + if (firstBuffer == 0) { + firstBuffer = _WADMemAlloc(allocator, 0x10000); + if (firstBuffer == 0) { + result = -3003; + goto cleanup; + } + } + if (secondBuffer == 0) { + secondBuffer = _WADMemAlloc(allocator, 0x10000); + if (secondBuffer == 0) { + result = -3003; + goto cleanup; + } + } + if (threadStack == 0) { + threadStack = _WADMemAlloc(allocator, sizeof(WADThreadStack)); + if (threadStack == 0) { + result = -3003; + goto cleanup; + } + } + if ((firstBuffer == 0) || (secondBuffer == 0) || (threadStack == 0)) { + result = -3003; + goto cleanup; + } + contentFd = ES_ImportContentBegin( + workspace.unpackInfo.titleMeta->head.titleId, content->cid); + result = contentFd; + if (contentFd < 0) { + goto cleanup; + } + contentImportStarted = TRUE; + sizeRemaining = (content->size + 0x0F) & ~0x0F; + WAD_815C4A2C(&transfer, firstBuffer, secondBuffer, 0x10000); + threadArgs.fd = contentFd; + threadArgs.transfer = &transfer; + threadArgs.size = sizeRemaining; + threadPriority = OSGetThreadPriority(OSGetCurrentThread()); + threadCreated = OSCreateThread(&importThread, + (void* (*)(void*))WAD_815BFFA8, + &threadArgs, + &threadStack->bytes[sizeof(threadStack->bytes)], + sizeof(threadStack->bytes), + threadPriority, 0); + if (!threadCreated) { + result = -3009; + goto cleanup; + } + OSResumeThread(&importThread); + transfer.error = 0; + bufferIndex = 0; + while ((sizeRemaining != 0) && (transfer.error == 0)) { + chunkSize = sizeRemaining; + if (transfer.chunkSize < chunkSize) { + chunkSize = transfer.chunkSize; + } + OSLockMutex(&transfer.mutex[bufferIndex]); + while ((transfer.ready[bufferIndex] != 0) && + (transfer.error == 0)) { + OSWaitCond(&transfer.waitCond[bufferIndex], + &transfer.mutex[bufferIndex]); + } + if (transfer.error != 0) { + break; + } + readSize = (chunkSize + 0x1F) & ~0x1F; + result = WADReadStream(&workspace.stream, + &transfer.buffers[bufferIndex], readSize, + offset + importedBytes); + if ((u32)result != readSize) { + OSLockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSCancelThread(&importThread); + OSJoinThread(&importThread, 0); + OSUnlockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSUnlockMutex(&transfer.mutex[bufferIndex]); + result = -3005; + goto cleanup; + } + transfer.ready[bufferIndex] = chunkSize; + OSUnlockMutex(&transfer.mutex[bufferIndex]); + OSSignalCond(&transfer.signalCond[bufferIndex]); + importedBytes += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(importedBytes - workspace.unpackInfo.contentOffset, + callbackTotal, FALSE); + } + bufferIndex ^= 1; + } + if (threadCreated) { + importResult = OSJoinThread(&importThread, (void**)&result); + if (!importResult) { + result = -3009; + goto cleanup; + } + threadCreated = FALSE; + } + if ((result != 0) || (transfer.error != 0)) { + goto cleanup; + } + result = ES_ImportContentEnd(contentFd); + if (result != 0) { + goto cleanup; + } + contentImportStarted = FALSE; + } + if (workspace.unpackInfo.type == 2) { + importedBytes = (importedBytes + 0x3F) & ~0x3F; + } + } + } + result = ES_ImportTitleDone(); + if (result != 0) { + goto cleanup; + } + titleImportStarted = FALSE; + } + if (((flags & 2) != 0) || (workspace.unpackInfo.fileListSize == 0) || + (workspace.unpackInfo.fileCount == 0)) { + goto cleanup; + } + if (firstBuffer == 0) { + firstBuffer = _WADMemAlloc(allocator, 0x10000); + if (firstBuffer == 0) { + result = -3003; + goto cleanup; + } + } + if (secondBuffer == 0) { + secondBuffer = _WADMemAlloc(allocator, 0x10000); + if (secondBuffer == 0) { + result = -3003; + goto cleanup; + } + } + transferIdValue = _WADGetTransferId(transferId); + fileOffset = workspace.unpackInfo.fileOffset; + if (((wadHeader.magic & 0xFFFFFF00) == 0x525A4400) && + (wadHeader.fileSize == 0x10000)) { + result = _WADVerifySavedataZD(&wadHeader, &workspace.stream, allocator, + offset + workspace.unpackInfo.fileOffset); + goto cleanup; + } + for (pathFileIndex = 0; pathFileIndex < workspace.unpackInfo.fileCount; pathFileIndex++) { + result = WADReadStream(&workspace.stream, &fileHeaderBuffer, sizeof(backupHeader), + offset + fileOffset); + if (result != sizeof(backupHeader)) { + result = -3005; + goto cleanup; + } + fileOffset = (fileOffset + 0xBF) & ~0x3F; + if (backupHeader.magic != 0x3ADF17E) { + result = -3000; + goto cleanup; + } + result = 0; + if (_WADCanImportFile(&backupHeader, transferIdValue, + workspace.unpackInfo.fileNames, transferId) == 0) { + if ((backupHeader.flags[2] == 1) && (backupHeader.fileSize != 0)) { + fileOffset = (fileOffset + backupHeader.fileSize + 0x3F) & + ~0x3F; + } + continue; + } + if (backupHeader.flags[2] == 1) { + result = NANDPrivateCreate(backupHeader.name, backupHeader.flags[0] | 0x20, + backupHeader.flags[1]); + if (result != 0) { + goto cleanup; + } + if (backupHeader.fileSize != 0) { + result = NANDPrivateOpen(backupHeader.name, &backupFile, 2); + if (result != 0) { + goto cleanup; + } + backupFileOpened = TRUE; + sizeRemaining = backupHeader.fileSize; + while (sizeRemaining != 0) { + chunkSize = sizeRemaining; + if (chunkSize > 0x10000) { + chunkSize = 0x10000; + } + result = WADReadStream(&workspace.stream, &firstBuffer, + (chunkSize + 0x1F) & ~0x1F, + offset + fileOffset); + readSize = (chunkSize + 0x1F) & ~0x1F; + if ((u32)result != readSize) { + result = -3005; + goto cleanup; + } + result = ES_Decrypt(6, backupHeader.iv, + firstBuffer, readSize, secondBuffer); + if (result != 0) { + goto cleanup; + } + result = NANDWrite(&backupFile, secondBuffer, chunkSize); + if ((u32)result != chunkSize) { + result = -3006; + goto cleanup; + } + importedBytes += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(workspace.unpackInfo.fileListSize + + importedBytes - workspace.unpackInfo.fileOffset, + callbackTotal, FALSE); + } + fileOffset += chunkSize; + } + result = NANDClose(&backupFile); + if (result != 0) { + goto cleanup; + } + backupFileOpened = FALSE; + } + if ((backupHeader.flags[0] & 0x20) == 0) { + result = NANDPrivateGetStatus(backupHeader.name, &fileStatus); + if (result != 0) { + goto cleanup; + } + updatedFileStatus = fileStatus; + updatedFileStatus.permission = backupHeader.flags[0]; + updatedFileStatus.attribute = backupHeader.flags[1]; + result = NANDPrivateSetStatus(backupHeader.name, &updatedFileStatus); + if (result != 0) { + goto cleanup; + } + } + } else if (backupHeader.flags[2] == 2) { + result = NANDPrivateCreateDir(backupHeader.name, + backupHeader.flags[0] | 0x20, + backupHeader.flags[1]); + if (result != -6) { + if (result != 0) { + goto cleanup; + } + } else { + result = NANDPrivateGetStatus(backupHeader.name, &fileStatus); + if (result != 0) { + goto cleanup; + } + if ((fileStatus.permission & 0x20) == 0) { + fileStatus.permission = backupHeader.flags[0] | 0x20; + fileStatus.attribute = backupHeader.flags[1]; + result = NANDPrivateSetStatus(backupHeader.name, &fileStatus); + if (result != 0) { + goto cleanup; + } + } + } + } + fileOffset = (fileOffset + 0x3F) & ~0x3F; + if ((backupHeader.fileSize == 0) && (processCallback != 0)) { + processCallback(workspace.unpackInfo.fileListSize + + importedBytes - workspace.unpackInfo.fileOffset, + callbackTotal, FALSE); + } + fileOffset += backupHeader.fileSize; + fileOffset = (fileOffset + 0x3F) & ~0x3F; + } + fileOffset = workspace.unpackInfo.fileOffset; + for (savedataFileIndex = 0; savedataFileIndex < workspace.unpackInfo.fileCount; + savedataFileIndex++) { + fileReadResult = WADReadStream(&workspace.stream, &fileHeaderBuffer, + sizeof(backupHeader), + offset + fileOffset); + if (fileReadResult != sizeof(backupHeader)) { + result = -3005; + break; + } + result = 0; + fileOffset = (fileOffset + 0xBF) & ~0x3F; + if ((_WADCanImportFile(&backupHeader, transferIdValue, + workspace.unpackInfo.fileNames, transferId) != 0) && + (((result = NANDPrivateGetStatus(backupHeader.name, &fileStatus)) != + 0) || + ((backupHeader.flags[0] & 0x20) == 0 && + ((fileStatus.permission = backupHeader.flags[0]), + (result = NANDPrivateSetStatus(backupHeader.name, &fileStatus)) != + 0)))) { + break; + } + fileOffset = (fileOffset + backupHeader.fileSize + 0x3F) & ~0x3F; + } + +cleanup: + _WADFreeMemory(&workspace.unpackInfo, allocator); + if (firstBuffer != 0) { + _WADMemFree(allocator, firstBuffer); + } + if (secondBuffer != 0) { + _WADMemFree(allocator, secondBuffer); + } + if (installedTitleMeta != 0) { + _WADMemFree(allocator, installedTitleMeta); + } + if (installedContentIds != 0) { + _WADMemFree(allocator, installedContentIds); + } + if (matchingContents != 0) { + _WADMemFree(allocator, matchingContents); + } + if (sharedContentHashes != 0) { + _WADMemFree(allocator, sharedContentHashes); + } + if (threadStack != 0) { + _WADMemFree(allocator, threadStack); + } + if (backupFileOpened) { + NANDClose(&backupFile); + } + if (streamOpened) { + WADCloseStream(&workspace.stream); + } + if (contentImportStarted) { + ES_ImportContentEnd(contentFd); + OSReport("%s:%d Cancel importing the content.\n", functionName, 0x8DF); + } + if (titleImportStarted) { + ES_ImportTitleCancel(); + _WADCleanTmpDir(allocator); + OSReport("%s:%d Cancel importing the title.\n", functionName, 0x8E6); + } + if (processCallback != 0) { + if (importedBytes == 0) { + processCallback(0, 0, TRUE); + } else if ((callbackTotal == 0) || (workspace.unpackInfo.fileCount == 0)) { + processCallback(importedBytes - workspace.unpackInfo.contentOffset, callbackTotal, + TRUE); + } else { + processCallback(workspace.unpackInfo.fileListSize + + importedBytes - workspace.unpackInfo.fileOffset, + callbackTotal, TRUE); + } + } + return result; +} + +static s32 WAD_815C1288(WADExportLoopArgs* args) { + s32 result; + u32 remaining; + u32 bufferIndex; + ESFd fd; + WADImportTransfer* transfer; + u32 size; + OSMutex* mutex; + + fd = args->fd; + result = 0; + remaining = args->size; + bufferIndex = 0; + transfer = args->transfer; + + while ((remaining != 0) && (result == 0)) { + size = remaining; + + if (remaining > transfer->chunkSize) { + size = transfer->chunkSize; + } + mutex = &transfer->mutex[bufferIndex]; + OSLockMutex(mutex); + while (transfer->ready[bufferIndex] != 0) { + OSWaitCond(&transfer->waitCond[bufferIndex], mutex); + } + result = ES_ExportContentData(fd, transfer->buffers[bufferIndex], size); + transfer->ready[bufferIndex] = size; + if (result != 0) { + transfer->error = 1; + } + OSUnlockMutex(mutex); + OSSignalCond(&transfer->signalCond[bufferIndex]); + remaining -= size; + bufferIndex ^= 1; + } + return result; +} + +s32 WADBackupEx(u64 titleId, u32 ticketId, MEMAllocator* allocator, char* path, u32* sizeOut, + WADLocation location, u32 offset, WADProcessCallback processCallback) { + WADBackupTitleMetaBuffer* titleMetaBuffer = 0; + ESTmdView* titleMeta = 0; + WADBackupFileHeader* files = 0; + WADStream stream ALIGN32; + WADImportTransfer transfer; + WADExportLoopArgs threadArgs; + OSThread exportThread; + NANDFileInfo savedFile ALIGN32; + WADBackupHeaderBlock headerBlock ALIGN32; + ESContentMask existingContentMask ALIGN32; + ESContentId installedContentIds[520] ALIGN32; + u8 hashContext[0xC0] ALIGN32; + u8 digest[0x40] ALIGN32; + u8 signature[0x40] ALIGN32; + u8 deviceCertificate[0x180] ALIGN32; + ESCertSignature signerCertificate ALIGN32; + u8 encryptionIv[0x10] ALIGN32; + void* outputBuffer = 0; + void* encryptionBuffer = 0; + WADThreadStack* threadStack = 0; + u32 flags = ticketId; + u32 titleMetaSize = 0; + u32 contentDataSize = 0; + u32 fileDataSize = 0; + u32 fileCount = 0; + u32 installedContentCount = 0; + u32 currentContentCount = 0; + u32 fileIndex; + u32 contentIndex; + u32 importedSize = 0; + u32 paddedSize; + u32 transferId = 0; + u32 totalSize; + u32 priority; + u32 sizeRemaining; + u32 bufferIndex; + u32 chunkSize; + u32 readSize; + s32 result = 0; + s32 streamOpened = FALSE; + s32 titleExportStarted = FALSE; + s32 contentExportStarted = FALSE; + s32 threadCreated = FALSE; + s32 fileOpened = FALSE; + s32 fileFd; + u32 callbackDone = 0; + + if (flags == 0) { + flags = 0x0F; + } + memset(&transfer, 0, sizeof(transfer)); + memset(&headerBlock, 0, sizeof(headerBlock)); + memset(&existingContentMask, 0, sizeof(existingContentMask)); + memset(encryptionIv, 0, sizeof(encryptionIv)); + if (((flags & 3) == 0) || ((u32)(titleId >> 32) == 1) || + (allocator == 0) || (sizeOut == 0)) { + result = -3000; + goto cleanup; + } + if ((offset & 0x3F) != 0) { + result = -3007; + goto cleanup; + } + if (processCallback != 0) { + processCallback(0, 0, FALSE); + } + if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_GetTmdView(titleId, 0, &titleMetaSize); + if (result != 0) { + goto cleanup; + } + titleMetaBuffer = _WADMemAlloc(allocator, sizeof(WADBackupTitleMetaBuffer)); + if (titleMetaBuffer == 0) { + result = -3003; + goto cleanup; + } + titleMeta = &titleMetaBuffer->view; + result = ES_GetTmdView(titleId, titleMeta, &titleMetaSize); + if (result != 0) { + goto cleanup; + } + } + if ((flags & 1) != 0) { + result = ES_ListTitleContentsOnCard(titleId, 0, &installedContentCount); + if (result == -106) { + result = -3002; + goto cleanup; + } + if ((result != 0) || (installedContentCount == 0)) { + result = -3002; + goto cleanup; + } + result = ES_ListTitleContentsOnCard(titleId, installedContentIds, + &installedContentCount); + if (result != 0) { + goto cleanup; + } + result = _WADCheckContents(titleMeta, &existingContentMask); + if (result != 0) { + goto cleanup; + } + } + if ((flags & 2) != 0) { + char currentDirectory[NAND_MAX_PATH] ALIGN32; + result = NANDGetCurrentDir(currentDirectory); + if (result != 0) { + goto cleanup; + } + result = _WADBackupGetFiles(0, flags, allocator, &fileCount, 0); + if (result != 0) { + goto cleanup; + } + if (fileCount != 0) { + files = _WADMemAlloc(allocator, fileCount * sizeof(WADBackupFileHeader)); + if (files == 0) { + result = -3003; + goto cleanup; + } + result = _WADBackupGetFiles(0, flags, allocator, &fileCount, files); + if (result != 0) { + goto cleanup; + } + } + } + result = _WADBackupGetSize(flags, titleMeta, &existingContentMask, fileCount, files, + &titleMetaSize, &contentDataSize, &fileDataSize); + if (result != 0) { + goto cleanup; + } + if ((contentDataSize == 0) && (fileDataSize == 0)) { + result = -3002; + goto cleanup; + } + totalSize = titleMetaSize + contentDataSize + fileDataSize + 0x340; + if (path == 0) { + *sizeOut = totalSize; + result = 0; + goto cleanup; + } + outputBuffer = _WADMemAlloc(allocator, 0x10000); + if (outputBuffer == 0) { + result = -3003; + goto cleanup; + } + if (processCallback != 0) { + processCallback(0, contentDataSize + fileDataSize, FALSE); + } + result = WADOpenStream(location, path, &stream, 1, offset); + streamOpened = TRUE; + if (result != 0) { + goto cleanup; + } + headerBlock.header.hdrSize = sizeof(WADBackupHeader); + headerBlock.header.wadType[0] = 'B'; + headerBlock.header.wadType[1] = 'k'; + headerBlock.header.wadVersion = 1; + headerBlock.header.numFiles = fileCount; + headerBlock.header.fileSize = fileDataSize; + headerBlock.header.tmdSize = titleMetaSize; + headerBlock.header.contentSize = contentDataSize; + headerBlock.header.backupAreaLen = titleMetaSize + contentDataSize + fileDataSize; + headerBlock.header.titleId = titleId; + result = ES_GetDeviceId(&headerBlock.header.deviceId); + if (result != 0) { + goto cleanup; + } + if ((flags & 1) != 0) { + headerBlock.header.cidx = existingContentMask; + } + result = WADWriteStream(&stream, &headerBlock, sizeof(headerBlock)); + if (result != sizeof(headerBlock)) { + result = -3006; + goto cleanup; + } + importedSize = sizeof(headerBlock); + result = SHA1Reset(hashContext); + if (result != 0) { + goto cleanup; + } + result = SHA1Input(hashContext, &headerBlock, sizeof(headerBlock)); + if (result != 0) { + goto cleanup; + } + srand(ticketId); + if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_ExportTitleInit(titleId, headerBlock.header.deviceId, 0, (void*)2, 0, 0, 0, + 0, 0, 0, 0); + if (result != 0) { + goto cleanup; + } + titleExportStarted = TRUE; + paddedSize = (titleMetaSize + 0x3F) & ~0x3F; + _WADRandPad(&titleMetaBuffer->data[titleMetaSize], + paddedSize - titleMetaSize); + result = SHA1Input(hashContext, titleMeta, paddedSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, titleMeta, paddedSize); + if ((u32)result != paddedSize) { + result = -3006; + goto cleanup; + } + importedSize += paddedSize; + } + if ((flags & 1) != 0) { + encryptionBuffer = _WADMemAlloc(allocator, 0x10000); + if (encryptionBuffer == 0) { + result = -3003; + goto cleanup; + } + threadStack = _WADMemAlloc(allocator, sizeof(WADThreadStack)); + if (threadStack == 0) { + result = -3003; + goto cleanup; + } + currentContentCount = _WADGetCidxCount(&existingContentMask); + for (contentIndex = 0; contentIndex < currentContentCount; contentIndex++) { + s32 tmdIndex = _WADGetCidx(&existingContentMask, contentIndex); + ESContentMeta* content; + if ((tmdIndex < 0) || (titleMeta->head.numContents <= tmdIndex)) { + result = -3009; + goto cleanup; + } + content = (ESContentMeta*)&titleMeta->contents[tmdIndex]; + fileFd = ES_ExportContentBegin(titleId, content->cid); + result = fileFd; + if (fileFd < 0) { + goto cleanup; + } + contentExportStarted = TRUE; + sizeRemaining = (content->size + 0x0F) & ~0x0F; + WAD_815C4A2C(&transfer, outputBuffer, encryptionBuffer, 0x10000); + threadArgs.fd = fileFd; + threadArgs.size = sizeRemaining; + threadArgs.transfer = &transfer; + priority = OSGetThreadPriority(OSGetCurrentThread()); + threadCreated = OSCreateThread(&exportThread, (void* (*)(void*))WAD_815C1288, + &threadArgs, + &threadStack->bytes[sizeof(threadStack->bytes)], + sizeof(threadStack->bytes), + priority, 0); + if (!threadCreated) { + result = -3009; + goto cleanup; + } + OSResumeThread(&exportThread); + sizeRemaining = (sizeRemaining + 0x3F) & ~0x3F; + bufferIndex = 0; + while ((sizeRemaining != 0) && (transfer.error == 0)) { + chunkSize = sizeRemaining; + if (transfer.chunkSize < chunkSize) { + chunkSize = transfer.chunkSize; + } + OSLockMutex(&transfer.mutex[bufferIndex]); + while ((transfer.ready[bufferIndex] == 0) && (transfer.error == 0)) { + OSWaitCond(&transfer.waitCond[bufferIndex], &transfer.mutex[bufferIndex]); + } + if (transfer.error != 0) { + break; + } + readSize = (chunkSize + 0x3F) & ~0x3F; + if (readSize > chunkSize) { + _WADRandPad((u8*)transfer.buffers[bufferIndex] + chunkSize, + readSize - chunkSize); + } + result = SHA1Input(hashContext, transfer.buffers[bufferIndex], chunkSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, transfer.buffers[bufferIndex], chunkSize); + if ((u32)result != chunkSize) { + OSLockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSCancelThread(&exportThread); + OSJoinThread(&exportThread, 0); + OSUnlockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSUnlockMutex(&transfer.mutex[bufferIndex]); + result = -3006; + goto cleanup; + } + transfer.ready[bufferIndex] = 0; + OSUnlockMutex(&transfer.mutex[bufferIndex]); + OSSignalCond(&transfer.signalCond[bufferIndex]); + importedSize += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(importedSize, contentDataSize + fileDataSize, FALSE); + } + bufferIndex ^= 1; + } + if (threadCreated) { + result = OSJoinThread(&exportThread, (void**)&fileFd); + threadCreated = FALSE; + if (result == 0) { + result = -3009; + goto cleanup; + } + } + if (fileFd < 0) { + result = fileFd; + goto cleanup; + } + result = ES_ExportContentEnd(fileFd); + contentExportStarted = FALSE; + if (result != 0) { + goto cleanup; + } + } + } + if (titleExportStarted) { + result = ES_ExportTitleDone(); + titleExportStarted = FALSE; + if (result != 0) { + goto cleanup; + } + } + if ((flags & 2) != 0) { + for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { + WADBackupFileHeader* file = &files[fileIndex]; + s32 filePosition = WADSeekStream(&stream, 0, 1); + size_t nameLength = strlen(file->path); + _WADRandPad(file->path + nameLength + 1, + 0x75 - (nameLength + 1)); + result = SHA1Input(hashContext, file, sizeof(WADBackupHeaderBlock)); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, file, sizeof(WADBackupHeaderBlock)); + if (result != sizeof(WADBackupHeaderBlock)) { + result = -3006; + goto cleanup; + } + importedSize += sizeof(WADBackupHeaderBlock); + if (processCallback != 0) { + processCallback(importedSize, contentDataSize + fileDataSize, FALSE); + } + if ((file->flags[2] == 1) && (file->fileSize != 0)) { + result = NANDPrivateOpen(file->path, &savedFile, 1); + if (result != 0) { + goto cleanup; + } + fileOpened = TRUE; + sizeRemaining = (file->fileSize + 0x1F) & ~0x1F; + while (sizeRemaining != 0) { + chunkSize = sizeRemaining; + if (chunkSize > 0x10000) { + chunkSize = 0x10000; + } + readSize = NANDRead(&savedFile, outputBuffer, chunkSize); + if (((readSize + 0x1F) & ~0x1F) != chunkSize) { + result = -3005; + goto cleanup; + } + result = ES_Encrypt(6, encryptionIv, outputBuffer, chunkSize, + encryptionBuffer); + if (result != 0) { + goto cleanup; + } + result = SHA1Input(hashContext, encryptionBuffer, chunkSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, encryptionBuffer, chunkSize); + if ((u32)result != chunkSize) { + result = -3006; + goto cleanup; + } + importedSize += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(importedSize, contentDataSize + fileDataSize, FALSE); + } + } + result = NANDClose(&savedFile); + fileOpened = FALSE; + if (result != 0) { + goto cleanup; + } + paddedSize = (file->fileSize + 0x3F) & ~0x3F; + if (paddedSize > file->fileSize) { + _WADRandPad(encryptionBuffer, paddedSize - file->fileSize); + result = SHA1Input(hashContext, encryptionBuffer, + paddedSize - file->fileSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, encryptionBuffer, + paddedSize - file->fileSize); + if ((u32)result != paddedSize - file->fileSize) { + result = -3006; + goto cleanup; + } + importedSize += paddedSize - file->fileSize; + } + } + if (filePosition < 0) { + result = filePosition; + goto cleanup; + } + } + } + result = WADSeekStream(&stream, 0, 1); + if (result < 0) { + goto cleanup; + } + if ((u32)result != offset + totalSize - 0x340) { + result = -3006; + goto cleanup; + } + result = SHA1Result(hashContext, digest); + if (result != 0) { + goto cleanup; + } + result = ES_Sign(digest, 0x14, signature, &signerCertificate); + if (result != 0) { + goto cleanup; + } + result = ES_GetDeviceCert(deviceCertificate); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, signature, sizeof(signature)); + if (result != sizeof(signature)) { + result = -3006; + goto cleanup; + } + result = WADWriteStream(&stream, deviceCertificate, sizeof(deviceCertificate)); + if (result != sizeof(deviceCertificate)) { + result = -3006; + goto cleanup; + } + result = WADWriteStream(&stream, &signerCertificate, sizeof(signerCertificate)); + if (result != sizeof(signerCertificate)) { + result = -3006; + goto cleanup; + } + if (WADSeekStream(&stream, offset, 0) != (s32)offset) { + result = -3006; + goto cleanup; + } + result = WADWriteStream(&stream, &headerBlock, sizeof(headerBlock)); + if (result != sizeof(headerBlock)) { + result = -3006; + goto cleanup; + } + *sizeOut = totalSize; + result = 0; + +cleanup: + if (titleMetaBuffer != 0) { + _WADMemFree(allocator, titleMetaBuffer); + } + if (outputBuffer != 0) { + _WADMemFree(allocator, outputBuffer); + } + if (encryptionBuffer != 0) { + _WADMemFree(allocator, encryptionBuffer); + } + if (threadStack != 0) { + _WADMemFree(allocator, threadStack); + } + if (files != 0) { + _WADMemFree(allocator, files); + } + if (fileOpened) { + NANDClose(&savedFile); + } + if (streamOpened) { + WADCloseStream(&stream); + } + if (contentExportStarted) { + ES_ExportContentEnd(fileFd); + } + if (titleExportStarted) { + ES_ExportTitleDone(); + } + if ((processCallback != 0) && (sizeOut != 0)) { + processCallback(importedSize, contentDataSize + fileDataSize, TRUE); + } + return result; +} + +static s32 _WADCheckContents(ESTmdView* titleMeta, ESContentMask* contentMask) { + ESContentId installedContentIds[512] ALIGN32; + u32 installedContentCount; + u32 contentIndex; + s32 result; + + if (ES_ListTitleContentsOnCard(titleMeta->head.titleId, 0, &installedContentCount) == -106) { + result = -3002; + } else { + result = ES_ListTitleContentsOnCard(titleMeta->head.titleId, installedContentIds, + &installedContentCount); + if (result == 0) { + memset(contentMask, 0, sizeof(*contentMask)); + for (contentIndex = 0; contentIndex < titleMeta->head.numContents; contentIndex++) { + u32 installedIndex; + + if ((titleMeta->contents[contentIndex].type & 0x8000) == 0) { + for (installedIndex = 0; installedIndex < installedContentCount; + installedIndex++) { + if (installedContentIds[installedIndex] == + titleMeta->contents[contentIndex].cid) { + contentMask->data[contentIndex >> 3] |= 1 << (contentIndex & 7); + break; + } + } + if ((installedIndex == installedContentCount) && + ((titleMeta->contents[contentIndex].type & 0x4000) == 0)) { + result = -3002; + goto done; + } + result = 0; + } + } + } + } +done: + return result; +} + +s32 _WADGetCidxCount(const ESContentMask* contentMask) { + s32 count = 0; + u32 bitIndex = 0; + u32 groupIndex; + + for (groupIndex = 0; groupIndex < 0x80; groupIndex++) { + if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { + count++; + } + if ((contentMask->data[(bitIndex + 1) >> 3] & (1 << ((bitIndex + 1) & 7))) != 0) { + count++; + } + if ((contentMask->data[(bitIndex + 2) >> 3] & (1 << ((bitIndex + 2) & 7))) != 0) { + count++; + } + if ((contentMask->data[(bitIndex + 3) >> 3] & (1 << ((bitIndex + 3) & 7))) != 0) { + count++; + } + bitIndex += 4; + } + return count; +} + +static s32 _WADGetCidx(const ESContentMask* contentMask, u32 contentNumber) { + u32 remaining = contentNumber + 1; + u32 bitIndex = 0; + u32 nextIndex; + + for (bitIndex = 0; bitIndex < 0x200; bitIndex += 4) { + if ((contentMask->data[(s32)bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return bitIndex; + } + nextIndex = bitIndex + 1; + if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return nextIndex; + } + nextIndex = bitIndex + 2; + if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return nextIndex; + } + nextIndex = bitIndex + 3; + if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return nextIndex; + } + } + return -1; +} + +#pragma dont_inline on +static s32 _WADGetTransferId(void* transferId) { + NANDFileInfo fileInfo; + BOOL valid; + s32 result; + + valid = FALSE; + result = NANDPrivateOpen("/shared2/succession/transfer.id", &fileInfo, 1); + if (result == 0) { + valid = TRUE; + result = NANDRead(&fileInfo, transferId, 0x20); + if (result != 0x20) { + valid = FALSE; + } + NANDClose(&fileInfo); + } + return valid; +} + +static s32 _WADCanImportFile(const WADFileHeader* fileHeader, u32 transferId, const void* fileNames, + const void* transferIdBuffer) { + s32 result; + + result = strncmp(fileHeader->name, "nocopy", 6); + if (result == 0) { + return FALSE; + } + result = strncmp(fileHeader->name, "notransfer", 10); + if (result == 0) { + if ((transferId == 0) || (fileNames == 0) || (transferIdBuffer == 0)) { + return FALSE; + } + result = memcmp(fileNames, transferIdBuffer, 6); + return result == 0; + } + return TRUE; +} + +static s32 _WADBackupGetFiles(const char* directoryPath, u32 flags, MEMAllocator* allocator, + u32* fileCount, WADBackupFileHeader* files) { + char currentDirectory[NAND_MAX_PATH] ALIGN32; + char fullDirectoryPath[NAND_MAX_PATH] ALIGN32; + char fullFilePath[NAND_MAX_PATH] ALIGN32; + char* names = 0; + char* nameList = 0; + u32 nameCount = 0; + u32 nameIndex; + u32 totalFiles = 0; + u32 childFileCount; + u8 fileType; + NANDFileInfo fileInfo; + NANDStatus status; + s32 result; + + if ((allocator == 0) || (fileCount == 0)) { + return -3000; + } + result = NANDGetCurrentDir(currentDirectory); + if (result != 0) { + return result; + } + if (directoryPath == 0) { + directoryPath = ""; + } + if (directoryPath[0] == '\0') { + strncpy(fullDirectoryPath, currentDirectory, sizeof(fullDirectoryPath)); + } else if (directoryPath[0] == '/') { + strncpy(fullDirectoryPath, directoryPath, sizeof(fullDirectoryPath)); + } else { + snprintf(fullDirectoryPath, sizeof(fullDirectoryPath), "%s/%s", currentDirectory, + directoryPath); + } + result = NANDPrivateReadDir(fullDirectoryPath, 0, &nameCount); + if (result == -1) { + *fileCount = 0; + return 0; + } + if (result != 0) { + return result; + } + if (nameCount != 0) { + nameList = _WADMemAlloc(allocator, nameCount * 0x40); + if (nameList == 0) { + return -3003; + } + names = nameList; + result = NANDPrivateReadDir(fullDirectoryPath, nameList, &nameCount); + if (result != 0) { + goto cleanup; + } + for (nameIndex = 0; nameIndex < nameCount; nameIndex++) { + char* name = names; + WADBackupFileHeader* file = 0; + u32 fileSize = 0; + BOOL closeFile = FALSE; + + if ((flags & 4) != 0) { + if (directoryPath[0] == '\0') { + snprintf(fullFilePath, sizeof(fullFilePath), "/%s", name); + } else { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s", directoryPath, name); + } + } else if (directoryPath[0] == '\0') { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s", currentDirectory, name); + } else if (directoryPath[0] == '/') { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s", directoryPath, name); + } else { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s/%s", currentDirectory, + directoryPath, name); + } + result = NANDPrivateGetType(fullFilePath, &fileType); + if (result != 0) { + break; + } + if ((fileType == 2) && ((flags & 8) == 0)) { + goto nextName; + } + if (fileType == 1) { + result = NANDPrivateOpen(fullFilePath, &fileInfo, 1); + if (result != 0) { + break; + } + closeFile = TRUE; + result = NANDGetLength(&fileInfo, &fileSize); + if (result != 0) { + NANDClose(&fileInfo); + break; + } + result = NANDClose(&fileInfo); + closeFile = FALSE; + if (result != 0) { + break; + } + } else if (fileType != 2) { + goto nextName; + } + result = NANDPrivateGetStatus(fullFilePath, &status); + if (result != 0) { + break; + } + if (files != 0) { + file = &files[totalFiles]; + file->magic = 0x3ADF17E; + file->fileSize = fileSize; + file->flags[0] = status.permission; + file->flags[1] = status.attribute; + file->flags[2] = fileType; + strncpy(file->path, fullFilePath, 0x40); + } + totalFiles++; + if (fileType == 2) { + childFileCount = 0; + result = _WADBackupGetFiles(fullFilePath, flags, allocator, &childFileCount, + files == 0 ? 0 : &files[totalFiles]); + if (result != 0) { + break; + } + totalFiles += childFileCount; + } + +nextName: + names += strlen(names) + 1; + if (closeFile) { + NANDClose(&fileInfo); + } + } + } + if (result == 0) { + *fileCount = totalFiles; + } + +cleanup: + if (nameList != 0) { + _WADMemFree(allocator, nameList); + } + return result; +} + +static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* contentMask, + u32 fileCount, WADBackupFileHeader* files, u32* titleMetaSize, + u32* contentDataSize, u32* fileDataSize) { + u32 titleSize = 0; + u32 contentSize = 0; + u32 filesSize = 0; + u32 selectedCount; + u32 contentIndex; + u32 fileIndex; + s32 result = 0; + + if (titleMeta == 0) { + if (titleMetaSize != 0) { + *titleMetaSize = 0; + } + } else if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_GetTmdSizeFromView(titleMeta, &titleSize); + if (result != 0) { + return result; + } + titleSize = (titleSize + 0x3F) & ~0x3F; + } + if (((flags & 1) != 0) && (titleMeta != 0)) { + selectedCount = _WADGetCidxCount(contentMask); + for (contentIndex = 0; contentIndex < selectedCount; contentIndex++) { + s32 tmdIndex = _WADGetCidx(contentMask, contentIndex); + if ((tmdIndex < 0) || (titleMeta->head.numContents <= tmdIndex)) { + return -3009; + } + contentSize += (titleMeta->contents[tmdIndex].size + 0x3F) & ~0x3F; + } + } + if ((fileCount != 0) && (files != 0)) { + for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { + filesSize += 0x80 + ((files[fileIndex].fileSize + 0x3F) & ~0x3F); + } + } + if (titleMetaSize != 0) { + *titleMetaSize = titleSize; + } + if (contentDataSize != 0) { + *contentDataSize = contentSize; + } + if (fileDataSize != 0) { + *fileDataSize = filesSize; + } + return result; +} +#pragma dont_inline reset + +#pragma dont_inline on +static void* _WADMemAlloc(MEMAllocator* allocator, u32 size) { + s32 allocationKind; + u32 heapType; + void* buffer = 0; + + if ((allocator != 0) && (allocator->heap != 0)) { + heapType = ((MEMiHeapHead*)allocator->heap)->magic; + switch (heapType) { + case 0x45585048: + allocationKind = 0; + break; + case 0x46524D48: + allocationKind = 1; + break; + case 0x554E5448: + allocationKind = 2; + break; + default: + allocationKind = 3; + break; + } + + switch (allocationKind) { + case 0: + buffer = MEMAllocFromExpHeapEx(allocator->heap, size, 0x40); + break; + case 1: + buffer = MEMAllocFromFrmHeapEx(allocator->heap, size, 0x40); + break; + case 2: + default: + buffer = MEMAllocFromAllocator(allocator, size); + if (((u32)buffer & 0x3F) != 0) { + OSReport("%s: Memory Allocator must return 64B aligned memBlocks\n", "_WADMemAlloc"); + MEMFreeToAllocator(allocator, buffer); + buffer = 0; + } + break; + } + } + return buffer; +} + +static void _WADMemFree(MEMAllocator* allocator, void* buffer) { + if ((allocator == 0) || (allocator->heap == 0) || (buffer == 0)) { + return; + } + MEMFreeToAllocator(allocator, buffer); +} +#pragma dont_inline reset + +static void _WADFreeMemory(WADUnpackInfo* info, MEMAllocator* allocator) { + if ((info->size_0x18 != 0) && (info->buffer_0x14 != 0)) { + _WADMemFree(allocator, info->buffer_0x14); + info->buffer_0x14 = 0; + } + if ((info->size_0x28 != 0) && (info->buffer_0x24 != 0)) { + _WADMemFree(allocator, info->buffer_0x24); + info->buffer_0x24 = 0; + } + if ((info->size_0x38 != 0) && (info->buffer_0x34 != 0)) { + _WADMemFree(allocator, info->buffer_0x34); + info->buffer_0x34 = 0; + } + if ((info->titleMetaSize != 0) && (info->titleMeta != 0)) { + _WADMemFree(allocator, info->titleMeta); + info->titleMeta = 0; + } +} + +static void _WADRandPad(void* buffer, u32 size) { + u32* words = buffer; + u32 wordCount = size >> 2; + u32 remainder = size & 3; + u32 wordIndex; + + for (wordIndex = 0; wordIndex < wordCount; wordIndex++) { + u32 first = rand(); + u32 second = rand(); + u32 third = rand(); + words[wordIndex] = (third & 3) | (second << 17) | (first << 2); + } + if (remainder != 0) { + u32 first = rand(); + u32 second = rand(); + u32 third = rand(); + u32 randomWord = (third & 3) | (second << 17) | (first << 2); + u8* tail = (u8*)&words[wordCount]; + u8* randomBytes = (u8*)&randomWord; + u32 byteIndex; + + for (byteIndex = 0; byteIndex < remainder; byteIndex++) { + tail[byteIndex] = randomBytes[byteIndex]; + } + } +} + +typedef struct WADContentPath { + const char* name; + void* handle; +} WADContentPath; + +typedef union WADFileInfoView { + FAFileInfo info; + struct { + u32 unknown; + u32 fileSize; + u8 reserved[0x18]; + } fields; +} WADFileInfoView; + +s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32 write, + u32 offset) { + s32 result; + + stream->location = location; + if (location == WAD_LOCATION_SD_CARD) { + if (write == 0) { + stream->handle.fa = FAFopen(path, "r"); + } else { + stream->handle.fa = FAFopen(path, "r+"); + if (stream->handle.fa == 0) { + stream->handle.fa = FACreate(path, 0); + } + if (stream->handle.fa == 0) { + return -3004; + } + if ((offset != 0) && (WADSeekStream(stream, offset, 0) != offset)) { + return -3004; + } + } + return stream->handle.fa == 0 ? -3004 : 0; + } + if (location < WAD_LOCATION_SD_CARD) { + if (location == WAD_LOCATION_DVD) { + if (write != 0) { + return -3004; + } + return DVDOpen(path, &stream->handle.dvd) ? 0 : -3004; + } + if (location == WAD_LOCATION_NAND) { + if (write == 0) { + return NANDPrivateOpen(path, &stream->handle.nand, 1) == 0 ? 0 : -3004; + } + result = NANDPrivateOpen(path, &stream->handle.nand, 3); + if (result == -12) { + result = NANDPrivateCreate(path, 0x3F, 0); + if (result != 0) { + return -3004; + } + result = NANDPrivateOpen(path, &stream->handle.nand, 3); + } + if (result != 0) { + return -3004; + } + result = NANDSeek(&stream->handle.nand, offset, 0); + if (result == -8) { + u8 zeroes[0x4000] ALIGN32; + u32 fileSize; + + fileSize = NANDSeek(&stream->handle.nand, 0, 2); + if (offset <= fileSize) { + return -3004; + } + memset(zeroes, 0, sizeof(zeroes)); + fileSize = offset - fileSize; + while (fileSize != 0) { + u32 writeSize = fileSize; + if (writeSize > sizeof(zeroes)) { + writeSize = sizeof(zeroes); + } + if (NANDWrite(&stream->handle.nand, zeroes, writeSize) != writeSize) { + return -3004; + } + fileSize -= writeSize; + } + result = NANDSeek(&stream->handle.nand, offset, 0); + } + return result == offset ? 0 : -3004; + } + if ((s32)location >= 0) { + if ((((u32)path + offset) & 0x3F) != 0) { + return -3007; + } + stream->handle.memoryBase = (void*)((u32)path + offset); + return 0; + } + } else if (location == WAD_LOCATION_CNT_NAND) { + WADContentPath* contentPath = (WADContentPath*)path; + if (write != 0) { + return -3004; + } + return contentOpenNAND(contentPath->handle, contentPath->name, + &stream->handle.contentNand) == 0 + ? 0 + : -3004; + } else if (location < WAD_LOCATION_CNT_NAND) { + WADContentPath* contentPath = (WADContentPath*)path; + if (write != 0) { + return -3004; + } + return contentOpenDVD(contentPath->handle, contentPath->name, + &stream->handle.contentDvd) == 0 + ? 0 + : -3004; + } + return -3000; +} + +size_t WADReadStream(WADStream* stream, void** buffer, size_t size, s32 offset) { + size_t result; + u32 alignedSize; + s32 location; + + if ((s32)size <= 0) { + result = 0; + } else if ((stream == 0) || (buffer == 0)) { + result = -3000; + } else { + alignedSize = (size + WAD_READ_ALIGNMENT - 1) & ~(WAD_READ_ALIGNMENT - 1); + if (size == alignedSize) { + location = stream->location; + if (location != WAD_LOCATION_SD_CARD) { + if (location < WAD_LOCATION_SD_CARD) { + if (location != WAD_LOCATION_DVD) { + if (location > 0) { + result = NANDSeek(&stream->handle.nand, offset, 0); + if ((s32)result < 0) { + return result; + } + return NANDRead(&stream->handle.nand, *buffer, alignedSize); + } + if (location >= 0) { + memcpy(*buffer, (u8*)stream->handle.memoryBase + offset, size); + return size; + } + } else { + return DVDReadPrio(&stream->handle.dvd, *buffer, alignedSize, offset, 2); + } + } else { + if (location != WAD_LOCATION_CNT_NAND) { + if (location < WAD_LOCATION_CNT_NAND) { + return contentReadDVD(&stream->handle.contentDvd, *buffer, alignedSize, + offset); + } + } else { + return contentReadNAND(&stream->handle.contentNand, *buffer, alignedSize, + offset); + } + } + result = -3000; + } else if (stream->handle.fa == 0) { + result = -3000; + } else { + result = FAFseek(stream->handle.fa, offset, 0); + if (result == 0) { + result = FAFread(*buffer, 1, size, stream->handle.fa); + } + } + } else { + result = -3000; + } + } + return result; +} + +void WADCloseStream(WADStream* stream) { + if (stream == 0) { + return; + } + if (stream->location != WAD_LOCATION_SD_CARD) { + if (stream->location < WAD_LOCATION_SD_CARD) { + if (stream->location != WAD_LOCATION_DVD) { + if (stream->location < WAD_LOCATION_DVD) { + return; + } + NANDClose(&stream->handle.nand); + return; + } + DVDClose(&stream->handle.dvd); + return; + } + if (stream->location != WAD_LOCATION_CNT_NAND) { + if (stream->location > WAD_LOCATION_CNT_NAND) { + return; + } + contentCloseDVD(&stream->handle.contentDvd); + return; + } + contentCloseNAND(&stream->handle.contentNand); + return; + } + if (stream->handle.fa != 0) { + FAFclose(stream->handle.fa); + } +} + +s32 WADWriteStream(WADStream* stream, void* buffer, u32 size) { + if ((stream == 0) || (buffer == 0)) { + return -3000; + } + if (stream->location == WAD_LOCATION_NAND) { + return NANDWrite(&stream->handle.nand, buffer, size); + } + if (stream->location == WAD_LOCATION_DVD - 1) { + memcpy(stream->handle.memoryBase, buffer, size); + return size; + } + if ((stream->location > WAD_LOCATION_NAND) && + (stream->location < WAD_LOCATION_CNT_DVD)) { + if (stream->handle.fa == 0) { + return -3000; + } + return FAFwrite(buffer, 1, size, stream->handle.fa); + } + return -3000; +} + +s32 WADSeekStream(WADStream* stream, u32 offset, s32 origin) { + s32 result; + + if ((stream == 0) || (origin < 0) || (origin > 2)) { + return -3000; + } + if (stream->location == WAD_LOCATION_SD_CARD) { + WADFileInfoView info; + if (stream->handle.fa == 0) { + return -3000; + } + result = FAFseek(stream->handle.fa, offset, origin); + if ((result == 0) && (FAFinfo(stream->handle.fa, &info.info) == 0)) { + result = info.fields.fileSize; + } + return result; + } + if (stream->location < WAD_LOCATION_SD_CARD) { + if (stream->location > WAD_LOCATION_DVD) { + return NANDSeek(&stream->handle.nand, offset, origin); + } + } else if (stream->location == WAD_LOCATION_CNT_NAND) { + return contentSeekNAND(&stream->handle.contentNand, offset, origin); + } else if (stream->location < WAD_LOCATION_CNT_NAND) { + return contentSeekDVD(&stream->handle.contentDvd, offset, origin); + } + return -3000; +} + +static s32 _WADGetTitleVer(WADHeader* header, ESTitleId* titleId, u16* titleVersion, s32 type, + s32 headerInfo) { + s32 titleDataOffset = 0; + + if (type == 2) { + if (header->tmdSize == 0) { + return 0; + } + if ((headerInfo == 0) || (headerInfo == 1) || (headerInfo == 3)) { + titleDataOffset = header->wadVersion == 1 ? 0x80 : 0x40; + titleDataOffset += (header->certSize + 0x3F) & ~0x3F; + titleDataOffset += (header->crlSize + 0x3F) & ~0x3F; + titleDataOffset += (header->ticketSize + 0x3F) & ~0x3F; + } else if (headerInfo == 2) { + titleDataOffset = 0x80; + } + } else if (type == 1) { + if (header->ticketSize == 0) { + return 0; + } + titleDataOffset = header->certSize + 0x20; + titleDataOffset += header->crlSize; + } + + { + WADFileMetadataView* metadata = (WADFileMetadataView*)((u8*)header + titleDataOffset); + if (titleId != 0) { + *titleId = metadata->titleId; + } + if (titleVersion != 0) { + *titleVersion = metadata->titleVersion; + } + } + return titleDataOffset; +} + +static s32 WAD_815C2F44(WADHeader* header, s32* headerInfo) { + u8 firstTypeByte; + u8 secondTypeByte; + + if (header == 0) { + return 0; + } + firstTypeByte = header->wadType[0]; + secondTypeByte = header->wadType[1]; + if ((firstTypeByte == 'I') && (secondTypeByte == 's')) { + if (headerInfo != 0) { + *headerInfo = 0; + } + return 2; + } + if ((firstTypeByte == 'X') && (secondTypeByte == 'p')) { + if (headerInfo != 0) { + *headerInfo = 1; + } + return 2; + } + if ((firstTypeByte == 'B') && (secondTypeByte == 'k')) { + if (headerInfo != 0) { + *headerInfo = 2; + } + return 2; + } + if ((firstTypeByte == 'i') && (secondTypeByte == 'b')) { + if (headerInfo != 0) { + *headerInfo = 3; + } + return 2; + } + if (header->hdrSize == 0x20) { + if (headerInfo != 0) { + *headerInfo = 0; + } + return 1; + } + return 0; +} + +#pragma dont_inline on +static s32 _WADUnpack(void* header, WADStream* stream, WADUnpackInfo* info, MEMAllocator* allocator, + u32 offset, u32 flags, u32 mode) { + s32 result; + s32 type; + + if ((header == 0) || (info == 0)) { + result = -3000; + } else { + memset(info, 0, 0x70); + type = WAD_815C2F44(header, &info->headerInfo); + info->type = type; + if (type == 2) { + if (info->headerInfo != 2) { + result = _WADUnpackIRD(header, stream, info, allocator, offset, mode); + } else { + result = _WADUnpackBackup(header, stream, info, allocator, offset, flags); + } + } else if (type == 1) { + result = _WADUnpackBroadOn((WADBroadOnHeader*)header, stream, info, allocator, offset, + mode); + } else { + result = -3001; + } + } + return result; +} +#pragma dont_inline reset + +static s32 _WADUnpackIRD(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode) { + u16 wadVersion = header->wadVersion; + s32 sectionSize; + u32 sectionOffset; + s32 alignedSize; + s32 bytesRead; + + if ((wadVersion != 0) && (wadVersion != 1)) { + return -3001; + } + if ((header->ticketSize == 0) && (header->tmdSize == 0)) { + return -3001; + } + if ((wadVersion == 0) && (header->hdrSize != 0x20)) { + return -3001; + } + if ((wadVersion == 1) && (header->hdrSize != 0x60)) { + return -3001; + } + + info->cidxMode = wadVersion; + if (wadVersion >= 1) { + info->contentIndex = &((WADBackupHeader*)header)->cidx; + } + sectionOffset = (header->hdrSize + 0x3F) & ~0x3F; + + sectionSize = header->certSize; + if (sectionSize != 0) { + info->size_0x0c = sectionSize; + info->offset_0x10 = sectionOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x14 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x14 == 0) { + return -3003; + } + info->size_0x18 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x14, alignedSize, + offset + info->offset_0x10); + if (bytesRead != alignedSize) { + return -3005; + } + } + sectionOffset += (header->certSize + 0x3F) & ~0x3F; + } + sectionSize = header->crlSize; + if (sectionSize != 0) { + info->size_0x1c = sectionSize; + info->offset_0x20 = sectionOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x24 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x24 == 0) { + return -3003; + } + info->size_0x28 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x24, alignedSize, + offset + info->offset_0x20); + if (bytesRead != alignedSize) { + return -3005; + } + } + sectionOffset += (header->crlSize + 0x3F) & ~0x3F; + } + sectionSize = header->ticketSize; + if (sectionSize != 0) { + info->size_0x2c = sectionSize; + info->offset_0x30 = sectionOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x34 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x34 == 0) { + return -3003; + } + info->size_0x38 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x34, alignedSize, + offset + info->offset_0x30); + if (bytesRead != alignedSize) { + return -3005; + } + } + sectionOffset += (header->ticketSize + 0x3F) & ~0x3F; + } + sectionSize = header->tmdSize; + if (sectionSize != 0) { + info->sectionSize = sectionSize; + info->sectionOffset = sectionOffset; + alignedSize = WAD_ALIGN32(sectionSize); + info->titleMeta = _WADMemAlloc(allocator, alignedSize); + if (info->titleMeta == 0) { + return -3003; + } + info->titleMetaSize = 1; + bytesRead = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, + offset + info->sectionOffset); + if (bytesRead != alignedSize) { + return -3005; + } + sectionOffset += (header->tmdSize + 0x3F) & ~0x3F; + } + if (header->contentSize != 0) { + info->contentSize = header->contentSize; + info->contentOffset = sectionOffset; + sectionOffset += (header->contentSize + 0x3F) & ~0x3F; + } + if (header->metaSize != 0) { + info->metaSize = header->metaSize; + info->metaOffset = sectionOffset; + } + return 0; +} + +static s32 _WADUnpackBroadOn(WADBroadOnHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode) { + u32 currentOffset; + s32 sectionSize; + s32 alignedSize; + s32 bytesRead; + + if ((header->crlSize == 0) && (header->ticketSize == 0)) { + return -3001; + } + + currentOffset = header->headerSize; + sectionSize = header->certSize; + if (sectionSize != 0) { + info->size_0x0c = sectionSize; + info->offset_0x10 = currentOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x14 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x14 == 0) { + return -3003; + } + info->size_0x18 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x14, alignedSize, + offset + info->offset_0x10); + if (bytesRead != alignedSize) { + return -3005; + } + } + currentOffset += header->certSize; + } + + sectionSize = header->crlSize; + if (sectionSize != 0) { + info->size_0x2c = sectionSize; + info->offset_0x30 = currentOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x34 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x34 == 0) { + return -3003; + } + info->size_0x38 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x34, alignedSize, + offset + info->offset_0x30); + if (bytesRead != alignedSize) { + return -3005; + } + } + currentOffset += header->crlSize; + } + + sectionSize = header->ticketSize; + if (sectionSize != 0) { + info->sectionSize = sectionSize; + info->sectionOffset = currentOffset; + alignedSize = WAD_ALIGN32(sectionSize); + info->titleMeta = _WADMemAlloc(allocator, alignedSize); + if (info->titleMeta == 0) { + return -3003; + } + info->titleMetaSize = 1; + bytesRead = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, + offset + info->sectionOffset); + if (bytesRead != alignedSize) { + return -3005; + } + currentOffset += header->ticketSize; + } + + sectionSize = header->titleMetaSize; + if (sectionSize != 0) { + info->metaSize = sectionSize; + info->metaOffset = currentOffset; + currentOffset += header->titleMetaSize; + } + + sectionSize = header->fileListSize; + if (sectionSize != 0) { + info->size_0x1c = sectionSize; + info->offset_0x20 = currentOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x24 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x24 == 0) { + return -3003; + } + info->size_0x28 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x24, alignedSize, + offset + info->offset_0x20); + if (bytesRead != alignedSize) { + return -3005; + } + } + } + + info->contentOffset = header->contentOffset; + return 0; +} + +static s32 _WADUnpackBackup(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 flags) { + WADBackupHeader* backupHeader = (WADBackupHeader*)header; + ESDeviceId currentDeviceId; + s32 result; + u32 sectionOffset; + u32 alignedSize; + + if (backupHeader->wadVersion != 1) { + return -3001; + } + if (backupHeader->hdrSize != sizeof(WADBackupHeader)) { + return -3001; + } + if (backupHeader->contentSize != 0) { + result = ES_GetDeviceId(¤tDeviceId); + if (result != 0) { + return result; + } + if (currentDeviceId != backupHeader->deviceId) { + return -3008; + } + } + + info->cidxMode = backupHeader->wadVersion; + if (backupHeader->wadVersion >= 1) { + info->contentIndex = &backupHeader->cidx; + } + info->fileNames = backupHeader->deviceMac; + sectionOffset = (backupHeader->hdrSize + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + + if (backupHeader->tmdSize != 0) { + if ((flags & 4) == 0) { + info->sectionSize = backupHeader->tmdSize; + info->sectionOffset = sectionOffset; + alignedSize = WAD_ALIGN32(backupHeader->tmdSize); + info->titleMeta = _WADMemAlloc(allocator, alignedSize); + if (info->titleMeta == 0) { + return -3003; + } + info->titleMetaSize = 1; + result = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, + offset + info->sectionOffset); + if (result != alignedSize) { + return -3005; + } + result = 0; + } + sectionOffset += (backupHeader->tmdSize + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + if ((flags & 2) != 0) { + return 0; + } + } + + if (backupHeader->contentSize != 0) { + info->contentSize = backupHeader->contentSize; + info->contentOffset = sectionOffset; + sectionOffset += (backupHeader->contentSize + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + } + if (backupHeader->fileSize != 0) { + info->fileListSize = backupHeader->fileSize; + info->fileOffset = sectionOffset; + info->fileCount = backupHeader->numFiles; + if ((flags & 1) == 0) { + result = WADVerify(stream, allocator, offset, backupHeader->backupAreaLen); + if (result != 0) { + return result; + } + } + } + return 0; +} + +typedef struct WADSaveDataRecord { + u8 reserved_0x00[0x4E]; + char fileName[8]; + u8 reserved_0x56[2]; + char bannerName[8]; + u8 reserved_0x60[0x12]; + char saveName[8]; + u8 reserved_0x7A[0x14]; + char titleName[8]; + u8 reserved_0x96[0x11E]; + char description[0x11]; + char subtitle[0x11]; + u8 reserved_0x1D6[0x8BE]; +} WADSaveDataRecord; + +typedef struct WADSaveDataFile { + u8 reserved_0x00[8]; + WADSaveDataRecord primary[3]; + u8 reserved_0x1FC4[0x44]; + WADSaveDataRecord secondary[3]; +} WADSaveDataFile; + +s32 WADCheckSavedataZD(const WADSaveDataFile* saveData) { + s32 result = FALSE; + u32 index; + const WADSaveDataRecord* record; + + record = saveData->primary; + index = 0; + do { + if (!_WADIsTerminated(record->fileName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->bannerName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->saveName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->titleName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->description, 0x11)) { + goto done; + } + if (!_WADIsTerminated(record->subtitle, 0x11)) { + goto done; + } + index++; + record++; + } while (index < 3); + record = saveData->secondary; + for (index = 0; index < 3; index++, record++) { + if (!_WADIsTerminated(record->fileName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->bannerName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->saveName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->titleName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->description, 0x11)) { + goto done; + } + if (!_WADIsTerminated(record->subtitle, 0x11)) { + goto done; + } + } + result = TRUE; +done: + return result; +} + +static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, + MEMAllocator* allocator, u32 offset) { + WADFileHeader* fileHeader = 0; + void* encryptedData = 0; + void* decryptedData = 0; + NANDFileInfo fileInfo; + s32 fileOpened = FALSE; + s32 result; + + if (header->saveType != 1) { + return -3009; + } + fileHeader = MEMAllocFromAllocator(allocator, sizeof(WADFileHeader)); + if (fileHeader == 0) { + result = -3003; + goto cleanup; + } + result = WADReadStream(stream, (void**)&fileHeader, sizeof(WADFileHeader), offset); + if (result != sizeof(WADFileHeader)) { + result = -3005; + goto cleanup; + } + if (fileHeader->fileSize < 0x4000) { + result = -3009; + goto cleanup; + } + encryptedData = MEMAllocFromAllocator(allocator, 0x4000); + decryptedData = MEMAllocFromAllocator(allocator, 0x4000); + if ((encryptedData == 0) || (decryptedData == 0)) { + result = -3003; + goto cleanup; + } + memset(encryptedData, 0, 0x4000); + memset(decryptedData, 0, 0x4000); + if (strcmp(fileHeader->name, "zeldaTp.dat") != 0) { + result = -3009; + goto cleanup; + } + result = WADReadStream(stream, &encryptedData, 0x4000, offset + 0x80); + if (result != 0x4000) { + result = -3005; + goto cleanup; + } + result = ES_Decrypt(6, fileHeader->iv, encryptedData, 0x4000, decryptedData); + if (result != 0) { + result = -3005; + goto cleanup; + } + if (WADCheckSavedataZD(decryptedData) == 0) { + result = -3009; + goto cleanup; + } + result = NANDPrivateCreate(fileHeader->name, 0x34, 0); + if ((result == 0) && (NANDPrivateOpen(fileHeader->name, &fileInfo, 2) == 0)) { + fileOpened = TRUE; + result = NANDWrite(&fileInfo, decryptedData, 0x4000); + if (result != 0x4000) { + result = -3006; + } else { + result = NANDClose(&fileInfo); + if (result == 0) { + fileOpened = FALSE; + } + } + } + +cleanup: + if (fileHeader != 0) { + MEMFreeToAllocator(allocator, fileHeader); + } + if (encryptedData != 0) { + MEMFreeToAllocator(allocator, encryptedData); + } + if (decryptedData != 0) { + MEMFreeToAllocator(allocator, decryptedData); + } + if (fileOpened) { + NANDClose(&fileInfo); + } + return result; +} + +static void _WADCleanTmpDir(MEMAllocator* allocator) { + char* names = 0; + char* name; + char filePath[NAND_MAX_PATH] ALIGN32; + u32 fileCount = 0; + u32 fileIndex; + s32 result; + + result = NANDPrivateReadDir("/tmp", 0, &fileCount); + if ((result == 0) && (fileCount != 0)) { + names = MEMAllocFromAllocator(allocator, fileCount * 0x41); + if ((names != 0) && (NANDPrivateReadDir("/tmp", names, &fileCount) == 0)) { + name = names; + for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { + char* extension = strrchr(name, '.'); + if ((extension != 0) && (strncmp(extension + 1, "tmp", 3) == 0)) { + snprintf(filePath, sizeof(filePath), "/tmp/%s", name); + NANDPrivateDelete(filePath); + OSReport("%s:%d remove %s", "WADImportEx", 0x1777, filePath); + } + name += strlen(name) + 1; + } + } + } + if (names != 0) { + MEMFreeToAllocator(allocator, names); + } +} + +s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { + DVDFileInfo fileInfo; + WADBootImportParts parts; + WADHeader* header; + ESTitleMeta* titleMeta; + u8* readBuffer = buffer; + void* applicationData; + u32 paddedFileSize; + u32 sectionOffset; + u32 applicationSize; + BOOL fileOpened = FALSE; + s32 result; + + if ((path == 0) || (buffer == 0)) { + result = -3000; + goto cleanup; + } + if (!DVDOpen(path, &fileInfo)) { + return -3004; + } + fileOpened = TRUE; + paddedFileSize = (fileInfo.length + 0x1F) & ~0x1F; + if (paddedFileSize > bufferSize) { + result = -3003; + goto cleanup; + } + if (((s32)readBuffer % 0x40) != 0) { + readBuffer += 0x20; + } + result = DVDReadPrio(&fileInfo, readBuffer, paddedFileSize, 0, 2); + if ((u32)result != paddedFileSize) { + result = -3005; + goto cleanup; + } + + memset(&parts, 0, sizeof(parts)); + header = (WADHeader*)readBuffer; + result = WAD_815C2F44(header, parts.headerInfo); + if (result != 2) { + OSReport("%s:%d Format should be iRD format: %s\n", "WADImportDVDForBS", 0x17D2, + path); + result = -3000; + goto cleanup; + } + if (parts.headerInfo[0] == 3) { + sectionOffset = (header->hdrSize + 0x3F) & ~0x3F; + if (header->certSize != 0) { + parts.certificateSize = header->certSize; + parts.certificates = readBuffer + sectionOffset; + sectionOffset += (header->certSize + 0x3F) & ~0x3F; + } + if (header->crlSize != 0) { + parts.crlSize = header->crlSize; + parts.crls = readBuffer + sectionOffset; + sectionOffset += (header->crlSize + 0x3F) & ~0x3F; + } + if (header->ticketSize != 0) { + parts.ticketSize = header->ticketSize; + parts.ticket = readBuffer + sectionOffset; + sectionOffset += (header->ticketSize + 0x3F) & ~0x3F; + } + if (header->tmdSize != 0) { + parts.titleMetaSize = header->tmdSize; + parts.titleMeta = readBuffer + sectionOffset; + sectionOffset += (header->tmdSize + 0x3F) & ~0x3F; + } + titleMeta = parts.titleMeta; + applicationSize = ((u32)titleMeta->contents[0].size + 0xF) & ~0xF; + applicationData = readBuffer + sectionOffset; + if ((titleMeta == 0) || (titleMeta->head.titleId != ES_TITLE_ID(1, 1))) { + OSReport("%s:%d This function only works for boot2 import.\n", "WADImportDVDForBS", + 0x180D); + result = -3000; + } else { + result = ES_ImportBoot(parts.ticket, parts.certificates, parts.certificateSize, + parts.titleMeta, parts.titleMetaSize, parts.certificates, + parts.certificateSize, parts.crls, parts.crlSize, applicationData, + applicationSize); + if (result != 0) { + OSReport("%s: Import Boot Failed: %d\n", "WADImportDVDForBS", result); + } else { + OSReport("%s: Import Boot Successful\n", "WADImportDVDForBS"); + } + } + } else { + OSReport("%s:%d This function only works for boot2 import.\n", "WADImportDVDForBS", + 0x1814); + result = -3000; + } + +cleanup: + if (fileOpened) { + DVDClose(&fileInfo); + } + return result; +} + +s32 WADImportDVDExForBS(const char* path, void* buffer, u32 bufferSize) { + WADHeader header ALIGN32; + WADBootImportParts parts; + DVDFileInfo fileInfo; + u8* readBuffer = buffer; + u8* contentBuffer; + ESTitleMeta* titleMeta; + ESContentMeta* contentMeta; + u32 sectionOffset; + u32 remainingBufferSize; + u32 contentCount; + u32 contentIndex; + s32 contentFd; + s32 result = 0; + s32 readResult; + BOOL fileOpened = FALSE; + + if ((path == 0) || (buffer == 0)) { + result = -3000; + goto cleanup; + } + if (!DVDOpen(path, &fileInfo)) { + return -3004; + } + fileOpened = TRUE; + if (buffer == 0) { + result = -3003; + goto cleanup; + } + if (((s32)readBuffer % 0x40) != 0) { + readBuffer += 0x20; + bufferSize -= 0x20; + } + readResult = DVDReadPrio(&fileInfo, &header, sizeof(header), 0, 2); + if (readResult != sizeof(header)) { + result = -3005; + goto cleanup; + } + + memset(&parts, 0, sizeof(parts)); + result = WAD_815C2F44(&header, parts.headerInfo); + if (result != 2) { + result = -3000; + goto cleanup; + } + + sectionOffset = (header.hdrSize + 0x3F) & ~0x3F; + if (header.certSize != 0) { + parts.certificateSize = header.certSize; + parts.certificates = readBuffer + sectionOffset; + sectionOffset += (header.certSize + 0x3F) & ~0x3F; + } + if (header.crlSize != 0) { + parts.crlSize = header.crlSize; + parts.crls = readBuffer + sectionOffset; + sectionOffset += (header.crlSize + 0x3F) & ~0x3F; + } + if (header.ticketSize != 0) { + parts.ticketSize = header.ticketSize; + parts.ticket = readBuffer + sectionOffset; + sectionOffset += (header.ticketSize + 0x3F) & ~0x3F; + } + if (header.tmdSize != 0) { + parts.titleMetaSize = header.tmdSize; + parts.titleMeta = readBuffer + sectionOffset; + sectionOffset += (header.tmdSize + 0x3F) & ~0x3F; + } + titleMeta = parts.titleMeta; + remainingBufferSize = bufferSize - sectionOffset; + contentBuffer = readBuffer + sectionOffset; + if (sectionOffset > bufferSize) { + result = -3003; + goto cleanup; + } + readResult = DVDReadPrio(&fileInfo, readBuffer, sectionOffset, 0, 2); + if (readResult != sectionOffset) { + result = -3005; + goto cleanup; + } + if (parts.headerInfo[0] == 3) { + result = -3001; + goto cleanup; + } + if (parts.ticket != 0) { + result = ES_ImportTicket(parts.ticket, parts.certificates, + parts.certificateSize, parts.crls, + parts.crlSize, 1); + if (result != 0) { + goto cleanup; + } + } + if (titleMeta == 0) { + goto cleanup; + } + if (parts.headerInfo[1] >= 1) { + contentCount = _WADGetCidxCount((ESContentMask*)parts.headerInfo); + if (contentCount > titleMeta->head.numContents) { + goto cleanup; + } + } else { + contentCount = titleMeta->head.numContents; + } + + result = ES_ImportTitleInit(parts.titleMeta, parts.titleMetaSize, + parts.certificates, parts.certificateSize, + parts.crls, parts.crlSize, + parts.headerInfo[0], 1); + if (result != 0) { + ES_ImportTitleCancel(); + goto cleanup; + } + + contentIndex = 0; + while (contentIndex < contentCount) { + s32 titleContentIndex; + u32 remainingContentSize; + + if (parts.headerInfo[1] >= 1) { + titleContentIndex = _WADGetCidx((ESContentMask*)parts.headerInfo, + contentIndex); + if ((titleContentIndex < 0) || + (titleContentIndex >= titleMeta->head.numContents)) { + ES_ImportTitleCancel(); + goto cleanup; + } + contentMeta = &titleMeta->contents[titleContentIndex]; + } else { + contentMeta = &titleMeta->contents[contentIndex]; + } + contentFd = ES_ImportContentBegin(titleMeta->head.titleId, contentMeta->cid); + if (contentFd < 0) { + result = contentFd; + ES_ImportContentEnd(contentFd); + ES_ImportTitleCancel(); + goto cleanup; + } + + remainingContentSize = ((u32)contentMeta->size + 0xF) & ~0xF; + while (remainingContentSize != 0) { + u32 chunkSize = remainingContentSize; + u32 readSize; + + if (chunkSize > remainingBufferSize) { + chunkSize = remainingBufferSize; + } + readSize = (chunkSize + 0x1F) & ~0x1F; + readResult = DVDReadPrio(&fileInfo, contentBuffer, readSize, sectionOffset, 2); + if ((u32)readResult != readSize) { + result = -3005; + ES_ImportContentEnd(contentFd); + ES_ImportTitleCancel(); + goto cleanup; + } + sectionOffset += readResult; + result = ES_ImportContentData(contentFd, contentBuffer, chunkSize); + if (result < 0) { + ES_ImportContentEnd(contentFd); + ES_ImportTitleCancel(); + goto cleanup; + } + remainingContentSize -= chunkSize; + } + sectionOffset = (sectionOffset + 0x3F) & ~0x3F; + result = ES_ImportContentEnd(contentFd); + if (result != 0) { + ES_ImportTitleCancel(); + goto cleanup; + } + contentIndex++; + } + + result = ES_ImportTitleDone(); + if (result != 0) { + ES_ImportTitleCancel(); + } + +cleanup: + if (fileOpened) { + DVDClose(&fileInfo); + } + return result; +} + +extern const u8 ca_ppki[]; +extern const u8 ms_ppki[]; +extern const u8 ca_dpki[]; +extern const u8 ms_dpki[]; +extern s32 SHA1Reset(void* context); +extern s32 SHA1Result(void* context, void* digest); + +static s32 WAD_815C43E0(WADHashThreadArgs* args) { + void* context; + s32 result; + u32 remaining; + u32 bufferIndex; + WADImportTransfer* transfer; + + context = args->context; + result = 0; + remaining = args->size; + bufferIndex = 0; + transfer = args->transfer; + + while ((remaining != 0) && (result == 0)) { + u32 size = remaining; + OSMutex* mutex; + + if (remaining > transfer->chunkSize) { + size = transfer->chunkSize; + } + mutex = &transfer->mutex[bufferIndex]; + OSLockMutex(mutex); + while (transfer->ready[bufferIndex] == 0) { + OSWaitCond(&transfer->signalCond[bufferIndex], mutex); + } + result = SHA1Input(context, transfer->buffers[bufferIndex], size); + transfer->ready[bufferIndex] = 0; + if (result != 0) { + transfer->error = 1; + } + OSUnlockMutex(mutex); + OSSignalCond(&transfer->waitCond[bufferIndex]); + remaining -= size; + bufferIndex ^= 1; + } + return result; +} + +static s32 _WADHash(WADStream* stream, u32 offset, u32 size, void* context, void* buffer, + u32 chunkSize, void* secondBuffer, void* threadStack, u32 threadStackSize) { + s32 result = 0; + + if ((stream == 0) || (context == 0) || (buffer == 0)) { + return -3000; + } + if (size != WAD_ALIGN32(size)) { + return -3000; + } + if (((u32)buffer & 0x1F) != 0) { + return -3007; + } + if (chunkSize != WAD_ALIGN32(chunkSize)) { + return -3000; + } + if ((secondBuffer == 0) || (threadStack == 0)) { + u32 completed = 0; + + while (size != 0) { + void* readBuffer = buffer; + u32 readSize = size; + + if (chunkSize < size) { + readSize = chunkSize; + } + result = WADReadStream(stream, &readBuffer, readSize, offset + completed); + if ((u32)result != readSize) { + result = -3005; + break; + } + result = SHA1Input(context, readBuffer, readSize); + if (result != 0) { + break; + } + completed += readSize; + size -= readSize; + } + } else { + WADImportTransfer transfer; + WADHashThreadArgs args; + OSThread thread; + s32 threadResult = 0; + u32 completed = 0; + u32 bufferIndex = 0; + BOOL readFailed = FALSE; + + WAD_815C4A2C(&transfer, buffer, secondBuffer, chunkSize); + args.context = context; + args.size = size; + args.transfer = &transfer; + if (!OSCreateThread(&thread, (void* (*)(void*))WAD_815C43E0, &args, + (u8*)threadStack + threadStackSize, threadStackSize, + OSGetThreadPriority(OSGetCurrentThread()), 0)) { + return -3009; + } + OSResumeThread(&thread); + while ((size != 0) && (transfer.error == 0)) { + void* readBuffer; + u32 readSize = size; + OSMutex* mutex = &transfer.mutex[bufferIndex]; + + if (chunkSize < size) { + readSize = chunkSize; + } + OSLockMutex(mutex); + while ((transfer.ready[bufferIndex] != 0) && (transfer.error == 0)) { + OSWaitCond(&transfer.waitCond[bufferIndex], mutex); + } + if (transfer.error != 0) { + OSUnlockMutex(mutex); + break; + } + readBuffer = transfer.buffers[bufferIndex]; + result = WADReadStream(stream, &readBuffer, readSize, offset + completed); + if ((u32)result != readSize) { + OSMutex* otherMutex = &transfer.mutex[bufferIndex ^ 1]; + + OSLockMutex(otherMutex); + OSCancelThread(&thread); + OSJoinThread(&thread, 0); + OSUnlockMutex(otherMutex); + OSUnlockMutex(mutex); + result = -3005; + readFailed = TRUE; + break; + } + transfer.ready[bufferIndex] = readSize; + OSUnlockMutex(mutex); + OSSignalCond(&transfer.signalCond[bufferIndex]); + completed += readSize; + size -= readSize; + bufferIndex ^= 1; + } + if (!readFailed) { + if (!OSJoinThread(&thread, &threadResult)) { + result = -3009; + } else { + result = threadResult; + } + } + } + return result; +} + +s32 WADVerify(WADStream* stream, MEMAllocator* allocator, u32 offset, u32 size) { + WADVerificationWorkspace workspace ALIGN64; + void* verificationBuffer = 0; + WADBackupSignature* backupSignature; + WADVerificationCertificateBundle* certificateBundle; + s32 result; + + workspace.readBuffer[0] = 0; + if (size != WAD_ALIGN32(size)) { + result = -3000; + } else if (size <= 0x340) { + result = -3000; + } else { + workspace.readBuffer[0] = _WADMemAlloc(allocator, 0x8000); + if (workspace.readBuffer[0] == 0) { + result = -3003; + } else if (((u32)workspace.readBuffer[0] & 0x3F) != 0) { + result = -3007; + } else { + u32 hashSize = size - 0x340; + + SHA1Reset(workspace.hashContext); + result = _WADHash(stream, offset, hashSize, workspace.hashContext, + workspace.readBuffer[0], 0x8000, 0, 0, 0x1000); + if (result == 0) { + result = SHA1Result(workspace.hashContext, workspace.digest); + if (result == 0) { + result = WADReadStream(stream, workspace.readBuffer, 0x340, + offset + hashSize); + if (result == 0x340) { + verificationBuffer = _WADMemAlloc(allocator, 0xF80); + if (verificationBuffer == 0) { + result = -3003; + } else { + backupSignature = workspace.readBuffer[0]; + certificateBundle = verificationBuffer; + memcpy(certificateBundle->caProduction, ca_ppki, 0x400); + memcpy(certificateBundle->msProduction, ms_ppki, 0x240); + memcpy(certificateBundle->caDevelopment, ca_dpki, 0x400); + memcpy(certificateBundle->msDevelopment, ms_dpki, 0x240); + memcpy(certificateBundle->firstCertificate, + backupSignature->firstCertificate, 0x180); + memcpy(certificateBundle->secondCertificate, + backupSignature->secondCertificate, 0x180); + result = ES_VerifySign(workspace.digest, 0x14, + workspace.readBuffer[0], verificationBuffer, + 0xF80); + } + } else { + result = -3005; + } + } + } + } + } + + if (workspace.readBuffer[0] != 0) { + _WADMemFree(allocator, workspace.readBuffer[0]); + } + if (verificationBuffer != 0) { + _WADMemFree(allocator, verificationBuffer); + } + return result; +} + +void WAD_815C4A2C(WADImportTransfer* transfer, void* firstBuffer, void* secondBuffer, + u32 chunkSize) { + transfer->chunkSize = chunkSize; + transfer->error = 0; + transfer->ready[1] = 0; + transfer->ready[0] = 0; + transfer->buffers[0] = firstBuffer; + transfer->buffers[1] = secondBuffer; + OSInitMutex(&transfer->mutex[0]); + OSInitMutex(&transfer->mutex[1]); + OSInitCond(&transfer->waitCond[0]); + OSInitCond(&transfer->waitCond[1]); + OSInitCond(&transfer->signalCond[0]); + OSInitCond(&transfer->signalCond[1]); +} + +#pragma dont_inline on +static u32 _WADIsTerminated(const char* text, u32 maxLength) { + u32 index; + + for (index = 0; index < maxLength; index++) { + if (text[index] == '\0') { + return TRUE; + } + } + return FALSE; +} +#pragma dont_inline reset -- 2.49.1 From 53be96c012c6d99075b1443962d909d1ae9fc57d Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:51:32 -0500 Subject: [PATCH 10/11] Decompile PrFILE2 pf_dir to 20/38 functions (#247) * decompile pf_dir empty check * decompile pf_dir path handling * decompile pf_dir attribute and remove paths * decompile pf_dir fstat lookup * align pf dir metadata layouts * match pf dir wrappers * decompile pf dir fsexec paths * tune pf dir open scan * match pf dir slot scan * match pf dir handler close * match pf dir finalization loop * track free directory slot separately * align directory position error paths * align pf dir open path cases * match pf dir fsexec name helpers * match pf dir readdir loop --- libs/RVL_SDK/src/fa/pf_dir.c | 1526 ++++++++++++++++++++++++++++++++++ 1 file changed, 1526 insertions(+) create mode 100644 libs/RVL_SDK/src/fa/pf_dir.c diff --git a/libs/RVL_SDK/src/fa/pf_dir.c b/libs/RVL_SDK/src/fa/pf_dir.c new file mode 100644 index 00000000..734232f2 --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_dir.c @@ -0,0 +1,1526 @@ +#include + +#include +#include +#include +#include +#include +#include + +typedef struct PFDIR_FFD { + pf_u32 start_cluster; + pf_u32 flags; + pf_u32* p_start_cluster; + PF_LAST_CLUSTER last_cluster; + PF_FAT_LAST_ACCESS last_access_cluster; + PF_CLUSTER_LINK cluster_link; + struct PFDIR_FAT_HINT* p_hint; + PF_VOLUME* p_vol; +} PFDIR_FFD; + +typedef struct PFDIR_FAT_HINT { + pf_u32 chain_index; + pf_u32 cluster; + pf_u32 previous_cluster; +} PFDIR_FAT_HINT; + +typedef struct PFDIR_STR { + const pf_s8* p_head; + const pf_s8* p_tail; + const pf_s8* p_current; + pf_u32 code_mode; +} PFDIR_STR; + +struct PF_ENT_ITER { + pf_u32 index; + PF_VOLUME* p_vol; + PFDIR_FFD ffd; + pf_u32 file_sector_index; + pf_u32 sector; + pf_u16 offset; + pf_u16 offset_mask; + pf_u8 buf[32]; + pf_u8 log2_entries_per_sector; +}; + +typedef struct PFDIR_SDD { + pf_u32 stat; + pf_u16 num_handlers; + pf_u16 alignment; + PFDIR_FFD ffd; + PF_DIR_ENT dir_entry; +} PFDIR_SDD; + +typedef struct PFDIR_SFD { + pf_u32 stat; + pf_u16 num_handlers; + pf_u16 alignment; + PF_FFD ffd; + PF_DIR_ENT dir_entry; + pf_u8 lock_state[0x20]; +} PFDIR_SFD; + +typedef struct PFDIR_DIR { + pf_u32 stat; + PFDIR_SDD* p_sdd; + PFDIR_FAT_HINT hint; + pf_u32 current_position; + pf_u32 next_position; + pf_u32 end_position; +} PFDIR_DIR; + +typedef struct PFDIR_READ_RESULT { + pf_s8 name[0x200]; + pf_s8 short_name[0x200]; +} PFDIR_READ_RESULT; + +typedef struct PFDIR_FILE_STAT { + pf_u32 file_size; + pf_u16 access_date; + pf_u16 modify_time; + pf_u16 modify_date; + pf_u16 create_time; + pf_u16 create_date; + pf_u16 small_letter_flag; + pf_u8 attributes; +} PFDIR_FILE_STAT; + +typedef struct PFDIR_VOLUME_DIRS { + pf_u8 volume_prefix[0x40]; + PFDIR_SFD sfds[5]; + pf_u8 volume_state[0xF0]; + PFDIR_SDD sdds[3]; + PFDIR_DIR udds[3]; + pf_s32 num_opened_files; + pf_s32 num_opened_directories; + pf_u8 cache_state[0x20]; + void* cache_signature; + pf_u8 volume_tail[0x1F80 - 0x1648]; + pf_s32 last_error; +} PFDIR_VOLUME_DIRS; + +typedef struct PFDIR_GLOBAL_STATE { + pf_u8 state_prefix[0x40]; + pf_s32 last_error; +} PFDIR_GLOBAL_STATE; + +extern PFDIR_GLOBAL_STATE pf_vol_set; + +extern pf_s32 PFENT_ITER_MoveTo(PF_ENT_ITER* iter, pf_u32 index, pf_u32 may_allocate); +extern pf_s32 PFENT_ITER_Advance(PF_ENT_ITER* iter, pf_u32 may_allocate); +extern pf_s32 PFENT_ITER_IsAtLogicalEnd(PF_ENT_ITER* iter); +extern pf_s32 PFENT_ITER_GetEntryOfPath(PF_ENT_ITER* iter, PF_DIR_ENT* entry, PF_VOLUME* volume, PFDIR_STR* path, + pf_u32 no_look_last_token); +extern pf_s32 PFENT_GetRootDir(PF_VOLUME* volume, PF_DIR_ENT* entry); +extern pf_s32 PFVOL_GetCurrentDir(PF_VOLUME* volume, PF_DIR_ENT* entry); +extern pf_s32 PFVOL_SetCurrentDir(PF_VOLUME* volume, PF_DIR_ENT* entry); +extern pf_s32 PFFAT_InitFFD(void* ffd, void* hint, PF_VOLUME* volume, pf_u32* start_cluster); +extern void PFFAT_InitHint(PFDIR_FAT_HINT* hint); +extern pf_s32 PFSTR_StrNCmp(PFDIR_STR* path, const pf_s8* text, pf_u32 target, pf_s16 offset, pf_u16 count); +extern pf_u16 PFSTR_StrNumChar(PFDIR_STR* path, pf_u32 code_mode); +extern void PFSTR_MoveStrPos(PFDIR_STR* path, pf_s16 count); +extern pf_s32 PFSTR_InitStr(PFDIR_STR* path, const pf_s8* text, pf_u32 code_mode); +extern void PFSTR_SetLocalStr(PFDIR_STR* path, pf_u32 is_local); +extern pf_s32 PFENT_findEntryPos(PFDIR_FFD* ffd, PF_DIR_ENT* entry, pf_u32 start, PFDIR_STR* pattern, + pf_u8 attr_required, pf_u32 skip, pf_u32* logical_position, + pf_u32* entry_position); +extern pf_s8* pf_strcpy(pf_s8* destination, const pf_s8* source); +extern pf_s32 PFPATH_transformFromUnicodeToNormal(pf_s8* destination, const pf_u16* source); +extern pf_s32 PFPATH_SplitPath(PFDIR_STR* path, PFDIR_STR* directory, PFDIR_STR* filename); +extern pf_u8 PFENT_getcurrentDateTimeForEnt(pf_u16* date, pf_u16* time); +extern pf_s32 PFENT_updateEntry(PF_DIR_ENT* entry, pf_u32 clear_archive); +extern pf_s32 PFFILE_IsOpened(PF_DIR_ENT* entry); +extern pf_s32 PFVOL_CheckCurrentDir(PF_VOLUME* volume, pf_u32 start_cluster); +extern pf_s32 PFENT_RemoveEntry(PF_DIR_ENT* entry, PF_ENT_ITER* iter); +extern pf_s32 PFFAT_FreeChain(PFDIR_FFD* ffd, pf_u32 start_cluster, pf_u32 chain_index, pf_u32 size); + +pf_s32 PFDIR_CheckDirIsEmpty(PF_ENT_ITER* iter, pf_u32* is_empty) { + pf_u32 start_cluster = *iter->ffd.p_start_cluster; + pf_s32 error; + + if (start_cluster == 1 || + (iter->ffd.p_vol->bpb.fat_type == FAT_32 && + start_cluster == iter->ffd.p_vol->bpb.root_dir_cluster)) { + error = 0; + } else { + error = 2; + } + *is_empty = 1; + error = PFENT_ITER_MoveTo(iter, error, 0); + while (!PFENT_ITER_IsAtLogicalEnd(iter)) { + if (error != 0) { + if (error == 13) { + return 0; + } + return error; + } + if (iter->buf[0] != 0xE5) { + pf_u8 attributes = iter->buf[0xB]; + if ((attributes & 0xF) != 0xF && (attributes & 8) == 0) { + if (iter->buf[0] == 0) { + *is_empty = 1; + } else { + *is_empty = 0; + } + break; + } + } + error = PFENT_ITER_Advance(iter, 0); + } + return 0; +} + +PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + PFDIR_SDD* first_free_sdd = 0; + PFDIR_SDD* free_candidate = volume_dirs->sdds; + pf_s32 i; + pf_s32 remaining = 3; + + for (i = 0; remaining != 0; i++, free_candidate++, remaining--) { + if ((volume_dirs->sdds[i].stat & 1) == 0) { + if (first_free_sdd == 0) { + first_free_sdd = free_candidate; + } + } else if (entry->p_vol == volume_dirs->sdds[i].dir_entry.p_vol && + entry->entry_sector == volume_dirs->sdds[i].dir_entry.entry_sector && + entry->entry_offset == volume_dirs->sdds[i].dir_entry.entry_offset) { + return &volume_dirs->sdds[i]; + } + } + if (first_free_sdd == 0) { + return 0; + } + first_free_sdd->stat = 3; + first_free_sdd->num_handlers = 0; + first_free_sdd->dir_entry = *entry; + PFFAT_InitFFD(&first_free_sdd->ffd, 0, entry->p_vol, &first_free_sdd->dir_entry.start_cluster); + return first_free_sdd; +} + +pf_s32 PFDIR_DoFsexecOpenDir(PF_DIR_ENT* entry, PF_ENT_ITER* iter, PFDIR_DIR** opened_dir) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; + PFDIR_SDD* sdd; + PFDIR_DIR* dir; + PFDIR_DIR* scan_dir; + pf_s32 i; + + *opened_dir = 0; + if ((entry->attr & 0x10) == 0) { + return 0x14; + } + sdd = PFDIR_GetSDD(entry->p_vol, entry); + if (sdd == 0) { + return 0x15; + } + dir = 0; + scan_dir = volume_dirs->udds; + for (i = 0; i < 3; i++, scan_dir++) { + if ((scan_dir->stat & 1) == 0) { + dir = &volume_dirs->udds[i]; + break; + } + } + if (dir == 0) { + return 0x16; + } + dir->p_sdd = sdd; + dir->stat = 1; + PFFAT_InitHint(&dir->hint); + dir->current_position = 0; + dir->next_position = 0; + dir->end_position = 0; + sdd->num_handlers++; + *opened_dir = dir; + return 0; +} + +pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_dir) { + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_SDD* sdd; + PFDIR_DIR* dir; + pf_s32 error; + pf_s32 i; + + if ((PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 0, 1) == 0 || + PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 0, 1) == 0) && + PFSTR_StrNCmp(path, (const pf_s8*)"", 1, 1, 1) == 0) { + error = PFENT_GetRootDir(volume, &entry); + if (error != 0) { + return error; + } + goto open_directory; + } else if (PFSTR_StrNumChar(path, 1) == 2 && + PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0) { + error = PFVOL_GetCurrentDir(volume, &entry); + if (error != 0) { + return error; + } + goto open_directory; + } else if (PFSTR_StrNumChar(path, 1) == 3 && + PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0 && + (PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 2, 1) == 0 || + PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 2, 1) == 0)) { + error = PFENT_GetRootDir(volume, &entry); + if (error != 0) { + return error; + } + goto open_directory; + } else { + if (PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0 && + (PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 2, 1) == 0 || + PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 2, 1) == 0)) { + PFSTR_MoveStrPos(path, 2); + } + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if ((entry.attr & 0x10) == 0) { + return 1; + } + } + +open_directory: + sdd = PFDIR_GetSDD(volume, &entry); + if (sdd == 0) { + return 0x15; + } + dir = ((PFDIR_VOLUME_DIRS*)volume)->udds; + i = 0; + do { + if ((dir->stat & 1) == 0) { + break; + } + i++; + dir++; + } while (i < 3); + if (i == 3) { + return 0x16; + } + dir->p_sdd = sdd; + dir->stat = 1; + PFFAT_InitHint(&dir->hint); + dir->current_position = 0; + dir->next_position = 0; + dir->end_position = 0; + sdd->num_handlers++; + *opened_dir = dir; + return 0; +} + +pf_s32 PFDIR_p_readdir(PFDIR_DIR* dir, PFDIR_READ_RESULT* result) { + PFDIR_FFD ffd; + PFDIR_FAT_HINT hint; + PF_DIR_ENT entry; + PFDIR_STR pattern; + pf_u32 remaining; + pf_u32 logical_position; + pf_u32 entry_position; + pf_s32 error; + + PFFAT_InitFFD(&ffd, &hint, dir->p_sdd->ffd.p_vol, &dir->p_sdd->dir_entry.start_cluster); + remaining = dir->end_position; + if (dir->next_position <= remaining) { + remaining -= dir->next_position; + } else if (dir->next_position > remaining) { + dir->current_position = 0; + dir->next_position = 0; + } + do { + PFSTR_InitStr(&pattern, (const pf_s8*)"*", 1); + PFSTR_SetLocalStr(&pattern, 0); + error = PFENT_findEntryPos(&ffd, &entry, dir->current_position, &pattern, 0x7F, 0, + &logical_position, &entry_position); + if (error != 0) { + return error; + } + dir->current_position = entry_position + 1; + dir->next_position++; + } while (remaining-- != 0); + dir->end_position = dir->next_position; + pf_strcpy(result->short_name, entry.short_name); + if (entry.long_name[0] != 0) { + PFPATH_transformFromUnicodeToNormal(result->name, entry.long_name); + } else { + result->name[0] = 0; + } + return 0; +} + +pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_dta) { + pf_s32 err; + PF_STR full_path; + PF_STR dirname; + pf_u16 dirname_len; + PF_DIR_ENT entry; + PF_DIR_ENT parent_entry; + PF_FFD ffd; + pf_u32 pos; + PF_FAT_HINT fat_hint; + pf_u32 prev_chain[2]; + pf_u32 new_sector; + + (void)option; + + err = 0; + new_sector = 0; + + err = VFiPFPATH_SplitPath(p_path, &full_path, &dirname); + if (err != 0) { + return err; + } + err = VFiPFENT_GetParentEntryOfPath(&parent_entry, p_vol, &full_path); + if (err != 0) { + return err; + } + if ((parent_entry.attr & 0x10) == 0) { + err = 0x14; + } + if (p_dta != PF_NULL) { + p_dta->parent_start_cluster = parent_entry.start_cluster; + } + VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster); + err = VFiPFENT_findEntry(&ffd, &entry, 0U, &dirname, 0x77U, PF_NULL, PF_NULL); + if (err == 0) { + return 8; + } + if (err != 3) { + return err; + } + dirname_len = VFiPFSTR_StrNumChar(&dirname, 1U); + if ((dirname_len > 0xFFU) || ((dirname_len + parent_entry.path_len) > 0x103U)) { + return 2; + } + err = VFiPFENT_InitENT(&entry, &dirname, 0x10U, 1U, &parent_entry, p_vol); + if (err == 0) { + VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster); + err = VFiPFENT_allocateEntry(&entry, (entry.num_entry_LFNs + 1), &ffd, prev_chain, PF_NULL, 0x77U, &pos); + if (err == 0) { + entry.start_cluster = 0; + VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &entry.start_cluster); + err = VFiPFFAT_GetSectorSpecified(&ffd, 0U, 1U, &new_sector); + if (new_sector == -1U) { + err = 6; + } + if (err == 0) { + err = VFiPFENT_FillVoidEntryToSectors(p_vol, new_sector, p_vol->bpb.sectors_per_cluster, 1U, &entry, &parent_entry); + if (err == 0) { + if ((entry.long_name[0] != 0) && ((VFipf_vol_set.setting & 2) == 2)) { + VFiPFPATH_AdjustExtShortName(&entry.short_name[0], pos); + entry.check_sum = VFiPFENT_CalcCheckSum(&entry); + } + err = VFiPFENT_UpdateEntry(&entry, prev_chain, 0U); + } + if (err != 0) { + VFiPFFAT_FreeChain(&ffd, entry.start_cluster, -1U, -1U); + } else if (p_dta != PF_NULL) { + p_dta->p_file = PF_NULL; + p_dta->p_dir = PF_NULL; + p_dta->p_vol = p_vol; + p_dta->parent_pos = pos + 1; + p_dta->num_entry_LFNs = entry.num_entry_LFNs; + p_dta->attr = entry.attr; + p_dta->Time = entry.modify_time; + p_dta->Date = entry.modify_date; + p_dta->FileSize = entry.file_size; + p_dta->Attribute = entry.attr; + if (VFiPFSTR_GetCodeMode(&dirname) == 1) { + VFiPFPATH_SetSearchPattern(p_dta->reg_exp, PF_NULL, &dirname); + p_dta->status |= 1; + } else { + VFiPFPATH_SetSearchPattern(p_dta->reg_exp, ((PF_DTAW*)p_dta)->reg_expW, &dirname); + p_dta->status |= 2; + } + VFipf_strcpy(p_dta->FileName, &entry.short_name[0]); + if ((p_dta->status & 2) == 2) { + VFiPFPATH_transformInUnicode(((PF_DTAW*)p_dta)->FileNameW, p_dta->FileName); + } + if (entry.long_name[0] == 0) { + p_dta->ordinal = 0; + p_dta->check_sum = 0; + p_dta->LongName[0] = 0; + if ((p_dta->status & 2) == 2) { + ((PF_DTAW*)p_dta)->LongNameW[0] = 0; + } + } else { + p_dta->ordinal = 1; + p_dta->check_sum = entry.check_sum; + if ((VFipf_vol_set.setting & 2) == 2) { + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 1; + VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 2; + } else { + VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); + } + if ((p_dta->status & 2) == 2) { + VFipf_w_strcpy(((PF_DTAW*)p_dta)->LongNameW, entry.long_name); + } + } + } + } + } + } + +exit: + return err; +} + +pf_s32 PFDIR_p_chdir(PF_VOLUME* p_vol, PFDIR_STR* p_path_str) { + pf_s32 err; + PF_ENT_ITER iter; + PF_DIR_ENT entry_dir; + + if (((PFSTR_StrNCmp(p_path_str, (pf_s8*)"\\", 1U, 0, 1U) == 0) || (PFSTR_StrNCmp(p_path_str, (pf_s8*)"/", 1U, 0, 1U) == 0)) && + (PFSTR_StrNCmp(p_path_str, (pf_s8*)"\0", 1U, 1, 1U) == 0)) { + err = PFENT_GetRootDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + err = PFVOL_SetCurrentDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + + return 0; + } + if ((PFSTR_StrNumChar(p_path_str, 1U) == 2) && (PFSTR_StrNCmp(p_path_str, (pf_s8*)":", 1U, 1, 1U) == 0)) { + return 0; + } + if ((PFSTR_StrNumChar(p_path_str, 1U) == 3) && (PFSTR_StrNCmp(p_path_str, (pf_s8*)":", 1U, 1, 1U) == 0) && + ((PFSTR_StrNCmp(p_path_str, (pf_s8*)"\\", 1U, 2, 1U) == 0) || (PFSTR_StrNCmp(p_path_str, (pf_s8*)"/", 1U, 2, 1U) == 0))) { + err = PFENT_GetRootDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + err = PFVOL_SetCurrentDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + + return 0; + } + if ((PFSTR_StrNCmp(p_path_str, (pf_s8*)":", 1U, 1, 1U) == 0) && + ((PFSTR_StrNCmp(p_path_str, (pf_s8*)"\\", 1U, 2, 1U) == 0) || (PFSTR_StrNCmp(p_path_str, (pf_s8*)"/", 1U, 2, 1U) == 0))) { + PFSTR_MoveStrPos(p_path_str, 2); + } + err = PFENT_ITER_GetEntryOfPath(&iter, &entry_dir, p_vol, p_path_str, 0); + if (err != 0) { + return err; + } + if ((entry_dir.attr & 0x10) == 0) { + return 0x14; + } + err = PFVOL_SetCurrentDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + + return 0; +} + +pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u8 attributes) { + PFDIR_STR directory_path; + PFDIR_STR filename; + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_VOLUME_DIRS* volume_dirs; + pf_u16 date; + pf_u16 time; + pf_u8 create_time_ms; + pf_u32 i; + pf_s32 error; + + error = PFPATH_SplitPath(path, &directory_path, &filename); + if (error != 0) { + return error; + } + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if (((entry.attr & 0x10) == 0 && (attributes & 0x10) != 0) || + ((entry.attr & 0x10) != 0 && (attributes & 0x10) == 0)) { + return 10; + } + if ((attributes & 0x40) != 0) { + attributes &= (pf_u8)~0x40; + } + if ((entry.attr & 0x10) == 0) { + if (PFFILE_IsOpened(&entry) != 0) { + return 0x13; + } + } else { + volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + for (i = 0; i < 3; i++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[i]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + entry.p_vol == sdd->dir_entry.p_vol && + entry.entry_sector == sdd->dir_entry.entry_sector && + entry.entry_offset == sdd->dir_entry.entry_offset) { + return 0x13; + } + } + if ((attributes & 4) != 0 && (attributes & 0xF) != 0xF) { + return 10; + } + attributes |= 0x10; + } + create_time_ms = PFENT_getcurrentDateTimeForEnt(&date, &time); + entry.modify_date = date; + entry.modify_time = time; + entry.create_time_ms = create_time_ms; + entry.attr = attributes; + return PFENT_updateEntry(&entry, 0); +} + +pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) { + PFDIR_VOLUME_DIRS* volume_dirs; + PFDIR_FAT_HINT hint; + PFDIR_FFD ffd; + PF_ENT_ITER iter; + PF_ENT_ITER directory_iter; + PF_DIR_ENT entry; + pf_u32 is_empty; + pf_u32 i; + pf_s32 error; + + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if ((entry.attr & 0x10) == 0 || (entry.attr & 1) != 0) { + return 0x14; + } + if (entry.start_cluster == 1 || + (volume->bpb.fat_type == FAT_32 && entry.start_cluster == volume->bpb.root_dir_cluster)) { + return 0x1C; + } + volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + for (i = 0; i < 3; i++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[i]; + if ((sdd->stat & 3) == 3 && entry.p_vol == sdd->dir_entry.p_vol && + entry.entry_sector == sdd->dir_entry.entry_sector && + entry.entry_offset == sdd->dir_entry.entry_offset) { + return 0x13; + } + } + error = PFVOL_CheckCurrentDir(volume, entry.start_cluster); + if (error != 0) { + return 0x1C; + } + PFFAT_InitFFD(&ffd, &hint, volume, &entry.start_cluster); + directory_iter.ffd = ffd; + error = PFENT_ITER_IteratorInitialize(&directory_iter, 0); + if (error != 0) { + return error; + } + is_empty = 0; + error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty); + if (error != 0) { + return error; + } + if (is_empty == 0) { + return 0x1D; + } + error = PFENT_RemoveEntry(&entry, &iter); + if (error != 0) { + return error; + } + return PFFAT_FreeChain(&iter.ffd, entry.start_cluster, -1U, -1U); +} + +pf_s32 PFDIR_p_fstat(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_FILE_STAT* file_stat) { + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_u32 index; + pf_s32 error; + + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if (volume_dirs->num_opened_files != 0) { + for (index = 0; index < 5; index++) { + PFDIR_SFD* sfd = &volume_dirs->sfds[index]; + if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 && + entry.p_vol == sfd->dir_entry.p_vol && + entry.entry_sector == sfd->dir_entry.entry_sector && + entry.entry_offset == sfd->dir_entry.entry_offset) { + file_stat->file_size = sfd->dir_entry.file_size; + file_stat->access_date = sfd->dir_entry.access_date; + file_stat->modify_time = sfd->dir_entry.modify_time; + file_stat->modify_date = sfd->dir_entry.modify_date; + file_stat->create_time = sfd->dir_entry.create_time; + file_stat->create_date = sfd->dir_entry.create_date; + file_stat->small_letter_flag = sfd->dir_entry.small_letter_flag; + file_stat->attributes = sfd->dir_entry.attr; + break; + } + } + } + if (volume_dirs->num_opened_files == 0 || index == 5) { + file_stat->file_size = (entry.attr & 0x10) == 0 ? entry.file_size : 0; + file_stat->access_date = entry.access_date; + file_stat->modify_time = entry.modify_time; + file_stat->modify_date = entry.modify_date; + file_stat->create_time = entry.create_time; + file_stat->create_date = entry.create_date; + file_stat->small_letter_flag = entry.small_letter_flag; + file_stat->attributes = entry.attr; + } + return 0; +} + +extern PF_VOLUME* PFPATH_GetVolumeFromPath(PF_STR* path); +extern pf_s32 PFCACHE_FlushDataCacheSpecific(PF_VOLUME* volume, void* entry); +extern pf_s32 PFCACHE_FlushFATCache(PF_VOLUME* volume); +extern pf_s32 PFDIR_p_fsfirst(PF_VOLUME* volume, PF_STR* path, pf_u8 attributes, PF_DTA* data); +extern pf_s32 PFDIR_p_fsnext(PF_DTA* data); +extern pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode); +extern pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path); +extern pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path); +extern pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode); +extern pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter); +extern pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags, + pf_u32 mode); +extern pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags); +extern void PFFAT_FinalizeFFD(PF_FFD* ffd); +extern pf_s32 PFENT_ITER_GetEntryOfPattern(PF_ENT_ITER* iter, PF_DIR_ENT* entry, PF_VOLUME* volume, + PFDIR_STR* directory); +extern pf_s32 PFENT_findEntry(PFDIR_FFD* ffd, PF_DIR_ENT* entry, pf_u32 start, PFDIR_STR* pattern, + pf_u8 attributes, pf_u32* logical_position, pf_u32* entry_position); +extern pf_u32 PFSTR_GetCodeMode(PFDIR_STR* path); +extern pf_s32 PFPATH_SplitPathPattern(PF_STR* path, PFDIR_STR* directory, PFDIR_STR* pattern); +extern void PFPATH_SetSearchPattern(pf_s8* ansi_pattern, pf_u16* unicode_pattern, PFDIR_STR* pattern); +extern pf_u16* pf_w_strcpy(pf_u16* destination, const pf_u16* source); +extern pf_s32 PFPATH_transformInUnicode(pf_u16* destination, const pf_s8* source); +extern pf_s32 PFPATH_parseShortName(PF_DIR_ENT* entry, const pf_s8* name); +extern pf_s32 PFENT_ITER_GetLFNEntryName(PF_ENT_ITER* iter); +extern void PFPATH_getLongNameformShortName(pf_s8* short_name, pf_s8* long_name, pf_u8 small_letter_flag); +extern pf_s32 PFFILE_FsexecOpenFile(PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 mode, PF_DTA* data); +extern pf_s32 PFPATH_cmpName(const pf_s8* short_name, PFDIR_STR* pattern, pf_u32 short_search); +extern pf_s32 PFPATH_cmpNameUni(const pf_u16* name, PFDIR_STR* pattern); + +pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; + PFDIR_FAT_HINT hint; + PF_ENT_ITER directory_iter; + pf_u32 is_empty; + pf_u32 index; + pf_u32 start_cluster = entry->start_cluster; + pf_s32 error; + + if ((entry->attr & 1) != 0) { + return 0x18; + } + if ((entry->attr & 0x10) != 0) { + if (PFVOL_CheckCurrentDir(entry->p_vol, entry->start_cluster) != 0 || entry->start_cluster == 1 || + (entry->p_vol->bpb.fat_type == FAT_32 && + entry->start_cluster == entry->p_vol->bpb.root_dir_cluster)) { + return 0x1C; + } + for (index = 0; index < 3; index++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[index]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + sdd->dir_entry.p_vol == entry->p_vol && + sdd->dir_entry.entry_sector == entry->entry_sector && + sdd->dir_entry.entry_offset == entry->entry_offset) { + return 0x13; + } + } + directory_iter = *iter; + PFFAT_InitFFD(&directory_iter.ffd, &hint, entry->p_vol, &entry->start_cluster); + error = PFENT_ITER_IteratorInitialize(&directory_iter, 0); + if (error != 0) { + return error; + } + is_empty = 0; + error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty); + if (error != 0) { + return error; + } + if (is_empty == 0) { + return 0x1D; + } + } else if (PFFILE_IsOpened(entry) != 0) { + return 0x13; + } + entry->num_entry_LFNs = data->num_entry_LFNs; + entry->ordinal = data->ordinal; + entry->check_sum = data->check_sum; + error = PFENT_RemoveEntry(entry, iter); + if (error != 0) { + return error; + } + return PFFAT_FreeChain(&iter->ffd, start_cluster, -1U, -1U); +} + +pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; + pf_u16 date; + pf_u16 time; + pf_u8 create_time_ms; + pf_u32 index; + pf_s32 error; + + if ((attributes & 0x40) != 0) { + attributes &= ~0x40; + } + if ((entry->attr & 0x10) == 0) { + if ((attributes & 0x10) != 0) { + return 10; + } + if (PFFILE_IsOpened(entry) != 0) { + return 0x13; + } + entry->attr = attributes; + } else { + if ((attributes & 4) != 0) { + return 10; + } + for (index = 0; index < 3; index++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[index]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + sdd->dir_entry.p_vol == entry->p_vol && + sdd->dir_entry.entry_sector == entry->entry_sector && + sdd->dir_entry.entry_offset == entry->entry_offset) { + return 0x13; + } + } + entry->attr = attributes | 0x10; + } + create_time_ms = PFENT_getcurrentDateTimeForEnt(&date, &time); + entry->modify_date = date; + entry->modify_time = time; + entry->create_time_ms = create_time_ms; + error = PFENT_updateEntry(entry, 0); + if (error != 0) { + return error; + } + if ((mode & 0x80000000) == 0) { + data->Attribute = entry->attr; + } + return PFCACHE_FlushDataCacheSpecific(entry->p_vol, 0); +} + +pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags, + pf_u32 mode) { + pf_s8 long_name[13]; + pf_s32 error; + + if ((flags & 0x80000000) != 0) { + entry->num_entry_LFNs = data->num_entry_LFNs; + entry->ordinal = data->ordinal; + entry->check_sum = data->check_sum; + if ((iter->buf[0xC] & 0x18) != 0) { + PFPATH_getLongNameformShortName(entry->short_name, long_name, iter->buf[0xC]); + PFPATH_transformInUnicode(entry->long_name, long_name); + } else { + error = PFENT_ITER_GetLFNEntryName(iter); + if (error != 0) { + return error; + } + } + } + error = PFFILE_FsexecOpenFile(entry, iter, mode, data); + if (error != 0) { + return error; + } + error = 0; + ((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files++; + return error; +} + +pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags) { + pf_s8 long_name[13]; + pf_s32 error; + + if ((flags & 0x80000000) != 0) { + entry->num_entry_LFNs = data->num_entry_LFNs; + entry->ordinal = data->ordinal; + entry->check_sum = data->check_sum; + if ((iter->buf[0xC] & 0x18) != 0) { + PFPATH_getLongNameformShortName(entry->short_name, long_name, iter->buf[0xC]); + PFPATH_transformInUnicode(entry->long_name, long_name); + } else { + error = PFENT_ITER_GetLFNEntryName(iter); + if (error != 0) { + return error; + } + } + } + error = PFDIR_DoFsexecOpenDir(entry, iter, (PFDIR_DIR**)&data->p_dir); + if (error != 0) { + return error; + } + error = 0; + ((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_directories++; + return error; +} + +pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { + PFDIR_FFD ffd; + PFDIR_FAT_HINT hint; + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_STR pattern; + pf_u32 logical_position; + pf_u32 entry_position; + pf_u32 start_position; + pf_u32 code_mode; + const pf_s8* name; + pf_s32 error; + + if ((flags & 0x26) == 0 && (flags & 1) == 0) { + return 10; + } + if ((flags & 0x26) != 0 || (flags & 1) != 0 || ((flags & 0x10) != 0 && mode != 2)) { + error = PFVOL_CheckForWrite(data->p_vol); + if (error != 0) { + return error; + } + } + start_position = data->parent_pos - 1; + if ((flags & 0x80000000) == 0) { + start_position -= data->num_entry_LFNs; + } + PFFAT_InitFFD(&ffd, &hint, data->p_vol, &data->parent_start_cluster); + iter.p_vol = data->p_vol; + iter.ffd = ffd; + error = PFENT_ITER_IteratorInitialize(&iter, start_position); + if (error != 0) { + return error; + } + if ((data->status & 1) != 0) { + code_mode = 1; + name = data->FileName; + } else { + code_mode = 2; + if ((VFipf_vol_set.setting & 2) != 0) { + name = (const pf_s8*)((PF_DTAW*)data)->LongNameW; + } else { + name = (const pf_s8*)((PF_DTAW*)data)->FileNameW; + } + } + error = PFSTR_InitStr(&pattern, name, code_mode); + if (error != 0) { + return error; + } + if ((VFipf_vol_set.setting & 2) != 0) { + PFSTR_SetLocalStr(&pattern, (pf_u32)data->LongName); + } else { + PFSTR_SetLocalStr(&pattern, (pf_u32)data->FileName); + } + error = PFENT_findEntryPos(&ffd, &entry, start_position, &pattern, 0x7F, 0, + &logical_position, &entry_position); + if (error != 0) { + return error; + } + if ((flags & 0x80000000) == 0) { + if ((data->status & 2) != 0) { + if (PFPATH_cmpNameUni(entry.long_name, &pattern) != 0) { + return 3; + } + } else if (PFPATH_cmpName(entry.short_name, &pattern, 1) != 0) { + return 3; + } + } + if (entry.short_name[0] == '.' && + ((entry.short_name[1] == ' ' && entry.short_name[2] == ' ') || entry.short_name[1] == '.')) { + return 0x1C; + } + error = PFENT_ITER_MoveTo(&iter, entry_position, 0); + if (error != 0) { + return error; + } + if ((flags & 6) != 0) { + return PFDIR_p_fsexec_chmod(data, &entry, flags, mode); + } + if ((flags & 1) != 0) { + return PFDIR_p_fsexec_remove(data, &entry, &iter); + } + if ((flags & 0x10) != 0) { + return PFDIR_p_fsexec_fopen(data, &entry, &iter, flags, mode); + } + if ((flags & 0x20) != 0) { + return PFDIR_p_fsexec_opendir(data, &entry, &iter, flags); + } + return 10; +} + +void PFDIR_FinalizeAllDirs(PF_VOLUME* volume) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_u16 index; + + for (index = 0; index < 3; index++) { + volume_dirs->sdds[index].stat = 0; + PFFAT_FinalizeFFD((PF_FFD*)&volume_dirs->sdds[index].ffd); + } + volume_dirs->udds[0].stat &= ~1; + volume_dirs->udds[1].stat &= ~1; + volume_dirs->udds[2].stat &= ~1; + volume_dirs->num_opened_directories = 0; +} + +void PFDIR_fsfirst(PF_STR* path, pf_u8 attributes, PF_DTA* data) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_fsfirst(volume, path, attributes, data); + if (error != 0) { + data->p_vol = 0; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } +} + +void PFDIR_fsnext(PF_DTA* data) { + PF_VOLUME* volume = data->p_vol; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_fsnext(data); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } +} + +void PFDIR_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { + PF_VOLUME* volume = data->p_vol; + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_fsexec(data, flags, mode); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_fstat(PF_STR* path, PFDIR_FILE_STAT* file_stat) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_fstat(volume, (PFDIR_STR*)path, file_stat); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } +} + +void PFDIR_rename(PF_STR* old_path, PF_STR* new_path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(old_path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_rename(volume, old_path, new_path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_move(PF_STR* old_path, PF_STR* new_path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(old_path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_move(volume, old_path, new_path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_opendir(PF_STR* path, PFDIR_DIR** dir) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_opendir(volume, (PFDIR_STR*)path, dir); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + volume_dirs->num_opened_directories++; + } +} + +pf_s32 PFDIR_closedir(PFDIR_DIR* dir) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if (--dir->p_sdd->num_handlers == 0) { + dir->p_sdd->stat &= ~1; + } + dir->stat &= ~1; + volume_dirs->num_opened_directories--; + return 0; +} + +pf_s32 PFDIR_readdir(PFDIR_DIR* dir, PFDIR_READ_RESULT* result) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + error = PFDIR_p_readdir(dir, result); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + return error; +} + +pf_s32 PFDIR_telldir(PFDIR_DIR* dir, pf_u32* position) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + PFDIR_SDD* sdd; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + sdd = dir->p_sdd; + if ((sdd->stat & 1) == 0 || (sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + *position = dir->end_position != 0 ? dir->end_position : dir->next_position; + } + } + return error; +} + +pf_s32 PFDIR_seekdir(PFDIR_DIR* dir, pf_u32 position) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + dir->end_position = position; + } + return error; +} + +void PFDIR_rmdir(PF_STR* path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_rmdir(volume, (PFDIR_STR*)path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_mkdir(PF_STR* path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_mkdir(volume, path, 0, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_createdir(PF_STR* path, pf_u32 option, PF_DTA* data) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_mkdir(volume, path, option, data); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +pf_s32 PFDIR_chdir(PF_STR* path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + error = PFDIR_p_chdir(volume, (PFDIR_STR*)path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + PFVOL_SetCurrentVolume(volume); + return 0; +} + +pf_s32 PFDIR_fchdir(PFDIR_DIR* dir) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + error = PFVOL_SetCurrentDir(volume, &dir->p_sdd->dir_entry); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + PFVOL_SetCurrentVolume(volume); + return 0; +} + +void PFDIR_chmod(PF_STR* path, pf_u8 attributes) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, attributes); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_chdmod(PF_STR* path, pf_u8 attributes) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, attributes | 0x10); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +pf_s32 PFDIR_p_fsnext(PF_DTA* data) { + PFDIR_FFD ffd; + PFDIR_FAT_HINT hint; + PF_DIR_ENT entry; + PFDIR_STR pattern; + pf_u32 logical_position = 0; + pf_u32 entry_position = 0; + pf_u32 code_mode; + pf_u32 index; + pf_s32 error; + + if ((data->status & 1) == 1) { + code_mode = 1; + error = PFSTR_InitStr(&pattern, data->reg_exp, code_mode); + } else { + code_mode = 2; + error = PFSTR_InitStr(&pattern, (const pf_s8*)((PF_DTAW*)data)->reg_expW, code_mode); + } + if (error != 0) { + return error; + } + PFSTR_SetLocalStr(&pattern, 0); + if (entry_position < 0xF423F) { + if (data->parent_pos > 0xF423E) { + return 10; + } + ffd.start_cluster = data->parent_start_cluster; + PFFAT_InitFFD(&ffd, &hint, data->p_vol, &ffd.start_cluster); + error = PFENT_findEntryPos(&ffd, &entry, data->parent_pos, &pattern, data->attr, 0, + &logical_position, &entry_position); + if (error != 0) { + return error; + } + data->parent_pos = entry_position + 1; + if (entry_position == 0xF423F) { + return 3; + } + } + pf_strcpy(data->FileName, entry.short_name); + if ((data->status & 2) == 2) { + PFPATH_transformInUnicode(((PF_DTAW*)data)->FileNameW, data->FileName); + } + if (entry.long_name[0] == 0) { + data->LongName[0] = 0; + if ((data->status & 2) == 2) { + ((PF_DTAW*)data)->LongNameW[0] = 0; + } + } else { + if ((VFipf_vol_set.setting & 2) == 2) { + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 1; + PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name); + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 2; + } else { + PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name); + } + if ((data->status & 2) == 2) { + pf_w_strcpy(((PF_DTAW*)data)->LongNameW, entry.long_name); + } + } + if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files != 0) { + PFDIR_SFD* sfd = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds; + for (index = 0; index < 5; index++) { + if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 && + sfd->dir_entry.p_vol == entry.p_vol && + sfd->dir_entry.entry_sector == entry.entry_sector && + sfd->dir_entry.entry_offset == entry.entry_offset) { + data->FileSize = sfd->dir_entry.file_size; + data->Time = sfd->dir_entry.modify_time; + data->Date = sfd->dir_entry.modify_date; + data->Attribute = sfd->dir_entry.attr; + data->num_entry_LFNs = sfd->dir_entry.num_entry_LFNs; + data->ordinal = sfd->dir_entry.ordinal; + data->check_sum = sfd->dir_entry.check_sum; + break; + } + sfd++; + } + } + if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files == 0 || index == 5) { + data->FileSize = entry.file_size; + data->Time = entry.modify_time; + data->Date = entry.modify_date; + data->Attribute = entry.attr; + data->num_entry_LFNs = entry.num_entry_LFNs; + data->ordinal = entry.ordinal; + data->check_sum = entry.check_sum; + } + return 0; +} + +pf_s32 PFDIR_p_fsfirst(PF_VOLUME* volume, PF_STR* path, pf_u8 attributes, PF_DTA* data) { + PFDIR_STR directory; + PFDIR_STR pattern; + PF_DIR_ENT entry; + PF_ENT_ITER iter; + pf_s32 error; + + error = PFPATH_SplitPathPattern(path, &directory, &pattern); + if (error != 0) { + return error; + } + error = PFENT_ITER_GetEntryOfPattern(&iter, &entry, volume, &directory); + if (error != 0) { + return error; + } + if ((entry.attr & 0x10) == 0) { + return 0x14; + } + data->parent_start_cluster = entry.start_cluster; + data->parent_pos = 0; + data->p_vol = entry.p_vol; + data->attr = attributes; + data->status = 0; + if (PFSTR_GetCodeMode(&pattern) == 1) { + PFPATH_SetSearchPattern(data->reg_exp, 0, &pattern); + data->status |= 1; + } else { + PFPATH_SetSearchPattern(data->reg_exp, ((PF_DTAW*)data)->reg_expW, &pattern); + data->status |= 2; + } + return PFDIR_p_fsnext(data); +} -- 2.49.1 From 341ce036f5320b8699ce75513a1a01c563fe8dee Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:53:07 -0500 Subject: [PATCH 11/11] Decompile iplSDChannelSelect to 42/129 functions (#248) * start sd channel select decompilation * add sd channel layouts and drawing * match sd worker state helpers * match nand title count handling * name sd channel scene helpers * match sd worker completion handlers * match channel visibility lookup * match channel queue helpers * fix sd command notice payloads * align sd worker state dispatch * match sd channel object destruction * match visible channel drawing passes * match sd channel layout updates * match sd channel pane helpers * match page animation calculation --- config/43U/symbols.txt | 104 +- include/math/iplMathTypes.h | 2 +- .../sdChannelSelect/iplSDChannelSelect.h | 255 ++- include/system/iplSaveDataManager.h | 6 + .../sdChannelSelect/iplSDChannelSelect.cpp | 1409 +++++++++++++++++ 5 files changed, 1716 insertions(+), 60 deletions(-) create mode 100644 src/scene/sdChannelSelect/iplSDChannelSelect.cpp diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 2ab7fbb1..625ff77d 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4558,44 +4558,44 @@ __ct__Q33ipl5scene15SDChannelSelectFPQ23EGG4Heap = .text:0x813DAB08; // type:fun __dt__Q33ipl5scene15SDChannelSelectFv = .text:0x813DAE7C; // type:function size:0x5C prepare__Q33ipl5scene15SDChannelSelectFv = .text:0x813DAED8; // type:function size:0xA8 create__Q33ipl5scene15SDChannelSelectFv = .text:0x813DAF80; // type:function size:0x248 -iplSDChannelSelect_813DB1C8 = .text:0x813DB1C8; // type:function size:0x44 -iplSDChannelSelect_813DB20C = .text:0x813DB20C; // type:function size:0x48 -iplSDChannelSelect_813DB254 = .text:0x813DB254; // type:function size:0xB4 -iplSDChannelSelect_813DB308 = .text:0x813DB308; // type:function size:0x5C -iplSDChannelSelect_813DB364 = .text:0x813DB364; // type:function size:0x5C -iplSDChannelSelect_813DB3C0 = .text:0x813DB3C0; // type:function size:0x5C -iplSDChannelSelect_813DB41C = .text:0x813DB41C; // type:function size:0x5C -iplSDChannelSelect_813DB478 = .text:0x813DB478; // type:function size:0x5C -iplSDChannelSelect_813DB4D4 = .text:0x813DB4D4; // type:function size:0x5C -iplSDChannelSelect_813DB530 = .text:0x813DB530; // type:function size:0x5C -iplSDChannelSelect_813DB58C = .text:0x813DB58C; // type:function size:0x60 -iplSDChannelSelect_813DB5EC = .text:0x813DB5EC; // type:function size:0x60 -iplSDChannelSelect_813DB64C = .text:0x813DB64C; // type:function size:0x40 -iplSDChannelSelect_813DB68C = .text:0x813DB68C; // type:function size:0x40 -iplSDChannelSelect_813DB6CC = .text:0x813DB6CC; // type:function size:0x518 -iplSDChannelSelect_813DBBE4 = .text:0x813DBBE4; // type:function size:0xB0 -iplSDChannelSelect_813DBC94 = .text:0x813DBC94; // type:function size:0xB8 -iplSDChannelSelect_813DBD4C = .text:0x813DBD4C; // type:function size:0x48 -iplSDChannelSelect_813DBD94 = .text:0x813DBD94; // type:function size:0xD8 -iplSDChannelSelect_813DBE6C = .text:0x813DBE6C; // type:function size:0x28 -iplSDChannelSelect_813DBE94 = .text:0x813DBE94; // type:function size:0x124 -iplSDChannelSelect_813DBFB8 = .text:0x813DBFB8; // type:function size:0x28 +enqueueStartNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB1C8; // type:function size:0x44 +enqueueFinishNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB20C; // type:function size:0x48 +enqueueNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB254; // type:function size:0xB4 +enqueueLoadNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB308; // type:function size:0x5C +enqueuePageNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB364; // type:function size:0x5C +enqueueResultNotice__Q33ipl5scene15SDChannelSelectFUl = .text:0x813DB3C0; // type:function size:0x5C +enqueueChannelNotice__Q33ipl5scene15SDChannelSelectFUlUlUlUl = .text:0x813DB41C; // type:function size:0x5C +enqueueMoveNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB478; // type:function size:0x5C +enqueueStateNotice__Q33ipl5scene15SDChannelSelectFUlUlUlUl = .text:0x813DB4D4; // type:function size:0x5C +enqueueErrorNotice__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DB530; // type:function size:0x5C +enqueueCommandNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB58C; // type:function size:0x60 +enqueueDeleteNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB5EC; // type:function size:0x60 +clearCommandQueue__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB64C; // type:function size:0x40 +clearNoticeQueue__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB68C; // type:function size:0x40 +processWorkerCommands__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB6CC; // type:function size:0x518 +handleWorkerStartup__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBBE4; // type:function size:0xB0 +handleNandTitleCount__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBC94; // type:function size:0xB8 +handleNandTitleUsageComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBD4C; // type:function size:0x48 +handleNandTitleUsage__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBD94; // type:function size:0xD8 +compareTitleUsage__Q33ipl5scene15SDChannelSelectFPCvPCv = .text:0x813DBE6C; // type:function size:0x28 +handleSDTitleList__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBE94; // type:function size:0x124 +compareTitleInfo__Q33ipl5scene15SDChannelSelectFPCvPCv = .text:0x813DBFB8; // type:function size:0x28 iplSDChannelSelect_813DBFE0 = .text:0x813DBFE0; // type:function size:0x2AC -iplSDChannelSelect_813DC28C = .text:0x813DC28C; // type:function size:0x64 +handleSDMountComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC28C; // type:function size:0x64 iplSDChannelSelect_813DC2F0 = .text:0x813DC2F0; // type:function size:0x1B0 -iplSDChannelSelect_813DC4A0 = .text:0x813DC4A0; // type:function size:0x5C -iplSDChannelSelect_813DC4FC = .text:0x813DC4FC; // type:function size:0x78 -iplSDChannelSelect_813DC574 = .text:0x813DC574; // type:function size:0x80 -iplSDChannelSelect_813DC5F4 = .text:0x813DC5F4; // type:function size:0x48 -iplSDChannelSelect_813DC63C = .text:0x813DC63C; // type:function size:0x48 -iplSDChannelSelect_813DC684 = .text:0x813DC684; // type:function size:0x90 -iplSDChannelSelect_813DC714 = .text:0x813DC714; // type:function size:0x48 -iplSDChannelSelect_813DC75C = .text:0x813DC75C; // type:function size:0x48 -iplSDChannelSelect_813DC7A4 = .text:0x813DC7A4; // type:function size:0x48 +handleSDCardReady__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC4A0; // type:function size:0x5C +handleCardCommand__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC4FC; // type:function size:0x78 +handleCopyComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC574; // type:function size:0x80 +handleSDLocationUpdateComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC5F4; // type:function size:0x48 +handleSDLocationReadComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC63C; // type:function size:0x48 +handleMoveComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC684; // type:function size:0x90 +handleBackupFitComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC714; // type:function size:0x48 +handleNandSDCleanupComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC75C; // type:function size:0x48 +handleSDDeleteComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC7A4; // type:function size:0x48 iplSDChannelSelect_813DC7EC = .text:0x813DC7EC; // type:function size:0x14C -iplSDChannelSelect_813DC938 = .text:0x813DC938; // type:function size:0x18C -iplSDChannelSelect_813DCAC4 = .text:0x813DCAC4; // type:function size:0x42C -iplSDChannelSelect_813DCEF0 = .text:0x813DCEF0; // type:function size:0x24 +processWorkerState__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC938; // type:function size:0x18C +updateDialogAnimation__Q33ipl5scene15SDChannelSelectFv = .text:0x813DCAC4; // type:function size:0x42C +setDialogMessage__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DCEF0; // type:function size:0x24 iplSDChannelSelect_813DCF14 = .text:0x813DCF14; // type:function size:0xCC iplSDChannelSelect_813DCFE0 = .text:0x813DCFE0; // type:function size:0xCC iplSDChannelSelect_813DD0AC = .text:0x813DD0AC; // type:function size:0x194 @@ -4619,13 +4619,13 @@ initCalcFadeout__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE24C; // type:fun calcFadeout__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE2EC; // type:function size:0x50 draw__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE33C; // type:function size:0x38C destroy__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE6C8; // type:function size:0x334 -iplSDChannelSelect_813DE9FC = .text:0x813DE9FC; // type:function size:0x440 -iplSDChannelSelect_813DEE3C = .text:0x813DEE3C; // type:function size:0x5C -iplSDChannelSelect_813DEE98 = .text:0x813DEE98; // type:function size:0x78 -iplSDChannelSelect_813DEF10 = .text:0x813DEF10; // type:function size:0x58 +createBaseLayout__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE9FC; // type:function size:0x440 +updateChannelObjects__Q33ipl5scene15SDChannelSelectFv = .text:0x813DEE3C; // type:function size:0x5C +updateChannelObject__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene12SDChannelObj = .text:0x813DEE98; // type:function size:0x78 +calcChannelObjects__Q33ipl5scene15SDChannelSelectFv = .text:0x813DEF10; // type:function size:0x58 iplSDChannelSelect_813DEF68 = .text:0x813DEF68; // type:function size:0x27C iplSDChannelSelect_813DF1E4 = .text:0x813DF1E4; // type:function size:0x14 -iplSDChannelSelect_813DF1F8 = .text:0x813DF1F8; // type:function size:0xB0 +drawChannelObjects__Q33ipl5scene15SDChannelSelectFv = .text:0x813DF1F8; // type:function size:0xB0 iplSDChannelSelect_813DF2A8 = .text:0x813DF2A8; // type:function size:0x138 iplSDChannelSelect_813DF3E0 = .text:0x813DF3E0; // type:function size:0x1C iplSDChannelSelect_813DF3FC = .text:0x813DF3FC; // type:function size:0x110 @@ -4637,13 +4637,13 @@ iplSDChannelSelect_813DF944 = .text:0x813DF944; // type:function size:0x84 iplSDChannelSelect_813DF9C8 = .text:0x813DF9C8; // type:function size:0xF8 iplSDChannelSelect_813DFAC0 = .text:0x813DFAC0; // type:function size:0xFC iplSDChannelSelect_813DFBBC = .text:0x813DFBBC; // type:function size:0xE4 -iplSDChannelSelect_813DFCA0 = .text:0x813DFCA0; // type:function size:0x50 +destroyChannelObject__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene12SDChannelObj = .text:0x813DFCA0; // type:function size:0x50 iplSDChannelSelect_813DFCF0 = .text:0x813DFCF0; // type:function size:0x74 iplSDChannelSelect_813DFD64 = .text:0x813DFD64; // type:function size:0x154 iplSDChannelSelect_813DFEB8 = .text:0x813DFEB8; // type:function size:0x74 iplSDChannelSelect_813DFF2C = .text:0x813DFF2C; // type:function size:0x1C0 -iplSDChannelSelect_813E00EC = .text:0x813E00EC; // type:function size:0x140 -iplSDChannelSelect_813E022C = .text:0x813E022C; // type:function size:0x68 +hasChannelObject__Q33ipl5scene15SDChannelSelectCFii = .text:0x813E00EC; // type:function size:0x140 +isChannelInCalc__Q33ipl5scene15SDChannelSelectCFiii = .text:0x813E022C; // type:function size:0x68 iplSDChannelSelect_813E0294 = .text:0x813E0294; // type:function size:0x104 iplSDChannelSelect_813E0398 = .text:0x813E0398; // type:function size:0x18 iplSDChannelSelect_813E03B0 = .text:0x813E03B0; // type:function size:0xA0 @@ -4651,13 +4651,13 @@ iplSDChannelSelect_813E0450 = .text:0x813E0450; // type:function size:0xEC iplSDChannelSelect_813E053C = .text:0x813E053C; // type:function size:0x84 iplSDChannelSelect_813E05C0 = .text:0x813E05C0; // type:function size:0x64 iplSDChannelSelect_813E0624 = .text:0x813E0624; // type:function size:0xB4 -iplSDChannelSelect_813E06D8 = .text:0x813E06D8; // type:function size:0xAC -iplSDChannelSelect_813E0784 = .text:0x813E0784; // type:function size:0x30 -iplSDChannelSelect_813E07B4 = .text:0x813E07B4; // type:function size:0x30 -iplSDChannelSelect_813E07E4 = .text:0x813E07E4; // type:function size:0x64 +getChannelBasePane__Q33ipl5scene15SDChannelSelectCFiii = .text:0x813E06D8; // type:function size:0xAC +getCenterChannelPane__Q33ipl5scene15SDChannelSelectCFi = .text:0x813E0784; // type:function size:0x30 +getChannelPane__Q33ipl5scene15SDChannelSelectCFi = .text:0x813E07B4; // type:function size:0x30 +getChannelPanePosition__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene15SDChannelSelecti = .text:0x813E07E4; // type:function size:0x64 iplSDChannelSelect_813E0848 = .text:0x813E0848; // type:function size:0x3A4 iplSDChannelSelect_813E0BEC = .text:0x813E0BEC; // type:function size:0x294 -iplSDChannelSelect_813E0E80 = .text:0x813E0E80; // type:function size:0x60 +calcPageAnimations__Q33ipl5scene15SDChannelSelectFv = .text:0x813E0E80; // type:function size:0x60 iplSDChannelSelect_813E0EE0 = .text:0x813E0EE0; // type:function size:0x26C iplSDChannelSelect_813E114C = .text:0x813E114C; // type:function size:0x78 iplSDChannelSelect_813E11C4 = .text:0x813E11C4; // type:function size:0x3A4 @@ -4678,10 +4678,10 @@ iplSDChannelSelect_813E2750 = .text:0x813E2750; // type:function size:0x164 iplSDChannelSelect_813E28B4 = .text:0x813E28B4; // type:function size:0x2A0 iplSDChannelSelect_813E2B54 = .text:0x813E2B54; // type:function size:0x240 startResetting__Q33ipl5scene15SDChannelSelectFv = .text:0x813E2D94; // type:function size:0x44 -iplSDChannelSelect_813E2DD8 = .text:0x813E2DD8; // type:function size:0x4C -iplSDChannelSelect_813E2E24 = .text:0x813E2E24; // type:function size:0x80 -iplSDChannelSelect_813E2EA4 = .text:0x813E2EA4; // type:function size:0x4C -iplSDChannelSelect_813E2EF0 = .text:0x813E2EF0; // type:function size:0x34 +pop__Q33ipl5scene26SDChannelSelectNoticeQueueFv = .text:0x813E2DD8; // type:function size:0x4C +push__Q33ipl5scene27SDChannelSelectCommandQueueFRCQ33ipl5scene22SDChannelSelectCommand = .text:0x813E2E24; // type:function size:0x80 +pop__Q33ipl5scene27SDChannelSelectCommandQueueFv = .text:0x813E2EA4; // type:function size:0x4C +copyFrom__Q33ipl5scene22SDChannelSelectCommandFRCQ33ipl5scene22SDChannelSelectCommand = .text:0x813E2EF0; // type:function size:0x34 @20@__dt__Q33ipl5scene15SDChannelSelectFv = .text:0x813E2F24; // type:function size:0x8 __ct__Q33ipl5scene12SDChannelObjFPQ23EGG4Heapii = .text:0x813E2F2C; // type:function size:0x130 __dt__Q33ipl5scene12SDChannelObjFv = .text:0x813E305C; // type:function size:0xA8 diff --git a/include/math/iplMathTypes.h b/include/math/iplMathTypes.h index 45a21ff4..8e7b0ef8 100644 --- a/include/math/iplMathTypes.h +++ b/include/math/iplMathTypes.h @@ -103,7 +103,7 @@ namespace ipl { y = r.y; z = 0.0f; } -#ifdef IPL_ADDRESS_EDIT_CPP +#if defined(IPL_ADDRESS_EDIT_CPP) || defined(IPL_SD_CHANNEL_SELECT_CPP) VEC3(f32 fx, f32 fy, f32 fz); #else VEC3(f32 fx, f32 fy, f32 fz) { diff --git a/include/scene/sdChannelSelect/iplSDChannelSelect.h b/include/scene/sdChannelSelect/iplSDChannelSelect.h index a98697da..d650b64d 100644 --- a/include/scene/sdChannelSelect/iplSDChannelSelect.h +++ b/include/scene/sdChannelSelect/iplSDChannelSelect.h @@ -1,18 +1,259 @@ #ifndef IPL_SCENE_SD_CHANNEL_SELECT_H #define IPL_SCENE_SD_CHANNEL_SELECT_H -#include "iplSceneHeader.h" +#include "iplSceneUIHeader.h" + +#include "math/iplInterporation.h" +#include "scene/sdButton/iplSDButton.h" +#include "system/iplChannelRsoThread.h" +#include "system/iplNandSDWorker.h" namespace ipl { namespace scene { - FADER_SCENE_CLASS(SDChannelSelect) { + class SDChannelObj { public: - SDChannelSelect(EGG::Heap * heap); + ~SDChannelObj(); + + EGG::Heap* getHeap() const { return mpHeap; } + int getPage() const { return mPage; } + int getIndex() const { return mIndex; } private: - u8 unk_0x58[0x728]; + nw4r::ut::Link mListLink; + f32 mOffsetX; + f32 mOffsetY; + EGG::Heap* mpHeap; + u32 mState; + int mPage; + int mIndex; }; - } // namespace scene -} // namespace ipl + extern "C" void iplSDChannelObj_813E3104(SDChannelObj* channel); + extern "C" void iplSDChannelObj_813E311C(SDChannelObj* channel, EGG::ExpHeap* firstHeap, + EGG::ExpHeap* secondHeap); + extern "C" void iplSDChannelObj_813E322C(SDChannelObj* channel); + extern "C" void iplSDChannelObj_813E3178(SDChannelObj* channel, nw4r::lyt::Pane* pane); + extern "C" void iplSDChannelObj_813E3180(SDChannelObj* channel, nand::LayoutFile* layoutFile); + extern "C" void iplSDChannelObj_813E3304(SDChannelObj* channel); + extern "C" void iplSDChannelObj_813E330C(SDChannelObj* channel); -#endif // IPL_SCENE_SD_CHANNEL_SELECT_H + union SDChannelSelectCommandArguments { + u32 values[3]; + NandSDWorker::AppBlocksInfo* appBlocks[3]; + NandSDWorker::TitleIdList* titleLists[3]; + void* pointers[3]; + }; + + struct SDChannelSelectCommand { + u32 type; + u64 titleId; + SDChannelSelectCommandArguments arguments; + + void copyFrom(const SDChannelSelectCommand& other); + }; + + struct SDChannelSelectCommandQueue { + SDChannelSelectCommand commands[4]; + int capacity; + int count; + int readIndex; + int writeIndex; + + SDChannelSelectCommandQueue(u32 capacity, u32 count, u32 readIndex, u32 writeIndex) + : capacity(capacity), count(count), readIndex(readIndex), writeIndex(writeIndex) { + } + + bool push(const SDChannelSelectCommand& command); + bool pop(); + }; + + struct SDChannelSelectTitleInfo { + ESTitleId32 titleId; + u32 state; + }; + + struct SDChannelSelectNoticeQueue { + SDChannelSelectCommand notices[42]; + int capacity; + int count; + int readIndex; + int writeIndex; + + SDChannelSelectNoticeQueue(u32 capacity, u32 count, u32 readIndex, u32 writeIndex) + : capacity(capacity), count(count), readIndex(readIndex), writeIndex(writeIndex) { + } + + bool pop(); + }; + + FADER_SCENE_CLASS(SDChannelSelect) { + public: + enum { + PAGE_COUNT = 5, + }; + + SDChannelSelect(EGG::Heap* heap); + virtual ~SDChannelSelect(); + + virtual BOOL isResetProcessDone(); + virtual void startResetting(); + virtual void prepare(); + virtual void create(); + virtual void draw(); + virtual void destroy(); + virtual void initCalcFadeout(); + virtual void calcCommon(); + virtual FaderSceneCommand calcFadein(); + virtual FaderSceneCommand calcNormal(); + virtual FaderSceneCommand calcFadeout(); + + static const char* mscChannelPaneNames[PAGE_COUNT][MAX_CHANNEL_INDEX]; + static const char* mscBasePaneNames[PAGE_COUNT]; + static const char* mscPicturePaneNames[PAGE_COUNT]; + static const char* mscEdgePaneNames[PAGE_COUNT]; + static const char* mscClockPaneNames[3]; + static const char* mscMaskPaneName; + + private: + void enqueueStartNotice(); + bool enqueueFinishNotice(); + bool enqueueNotice(u32 highTitleId, u32 lowTitleId, u32 result); + bool enqueueLoadNotice(); + bool enqueuePageNotice(); + bool enqueueResultNotice(u32 result); + bool enqueueChannelNotice(u32 controller, u32 page, u32 index, u32 value); + bool enqueueMoveNotice(u32 controller, u32 page, u32 index); + bool enqueueStateNotice(u32 controller, u32 page, u32 index, u32 state); + bool enqueueErrorNotice(u32 page, u32 index); + bool enqueueCommandNotice(u32 page, u32 index, u32 command); + bool enqueueDeleteNotice(u32 controller, u32 page, u32 index); + void clearCommandQueue(); + void clearNoticeQueue(); + void calcChannelObjects(); + void updateChannelObjects(); + void updateChannelObject(SDChannelObj* channel); + void drawChannelObjects(); + bool isChannelInCalc(int page, int index, int currentPage) const; + nw4r::lyt::Pane* getChannelBasePane(int page, int index, int currentPage) const; + nw4r::lyt::Pane* getCenterChannelPane(int index) const; + nw4r::lyt::Pane* getChannelPane(int index) const; + static math::VEC3 getChannelPanePosition(SDChannelSelect* scene, int index); + void calcPageAnimations(); + void updateArrowVisibility(); + void processWorkerState(); + void updateDialogAnimation(); + void processWorkerCommands(); + void handleWorkerStartup(); + void handleNandTitleCount(); + void handleNandTitleUsage(); + void handleNandTitleUsageComplete(); + void handleSDTitleList(); + void handleSDMountComplete(); + void handleCopyComplete(); + void handleDeleteComplete(); + void handleMoveComplete(); + void handleStorageCheckComplete(); + void handleCardCommand(); + void handleSDCardReady(); + void handleSDLocationUpdateComplete(); + void handleSDLocationReadComplete(); + void handleBackupFitComplete(); + void handleNandSDCleanupComplete(); + void handleSDDeleteComplete(); + bool setDialogMessage(u32 state, u32 message); + static int compareTitleUsage(const void* lhs, const void* rhs); + static int compareTitleInfo(const void* lhs, const void* rhs); + void createChannelList(int page, bool force); + void destroyChannelObject(SDChannelObj* channel); + bool hasChannelObject(int page, int index) const; + void createChannelObject(int page, int index); + void createBaseLayout(); + void updateNoCardLayouts(); + void createChannelThumbnails(); + + nw4r::ut::List mChannelObjects; + nand::LayoutFile* mpLayoutFile; + layout::Object* mpLayout; + math::HermiteIntp* mpPageAnimations[4]; + gui::PaneManager* mpPaneManager; + layout::Object* mpNoCardLayout; + layout::Object* mpPageLayouts[3]; + layout::Object* mpDialogLayout; + SDButtonEventHandlerBase* mpButtonEventHandler; + int mState; + int mCurrentPage; + int mPageCount; + int mCurrentChannelIndex; + f32 mThumbOffsetX; + f32 mThumbOffsetY; + nw4r::math::VEC3 mPosition; + math::VEC2 mScale; + f32 mAspectRatioScale; + bool mbLeftArrowVisible; + bool mbRightArrowVisible; + u8 mArrowState; + u8 mNoCardState; + EGG::UnitHeap* mpLayoutHeap; + EGG::ExpHeap* mpDialogHeap; + EGG::ExpHeap* mpChannelHeap; + EGG::ExpHeap* mpThumbnailHeap; + nw4r::math::VEC2 mPointerPosition; + int mControllerChannel; + int mSourcePage; + int mSourceIndex; + int mDestinationPage; + int mDestinationIndex; + int mPendingPage; + int mPendingIndex; + int mMoveState; + bool mbButtonEnabled; + bool mbDialogActive; + u16 mInputFlags; + SDChannelObj* mpCurrentChannel; + layout::Object* mpStateLayout; + layout::Object* mpHelpLayout; + EGG::ExpHeap* mpRsoHeap; + channel::RsoThread* mpRsoThread; + u32 mCommandQueueState; + SDChannelSelectCommandQueue mCommandQueue; + SDChannelSelectNoticeQueue mNoticeQueue; + int mCurrentSDState; + int mPreviousSDState; + int mWorkerState; + int mWorkerCommand; + EGG::Heap* mpWorkerHeap; + EGG::Heap* mpThumbnailWorkHeap; + NandSDWorker* mpSDWorker; + ESTitleId32* mpSDTitleIds; + SDChannelSelectTitleInfo* mpSDTitleInfo; + NandSDWorker::TitleUsage* mpNandTitleInfo; + u32 mFirstTitleCount; + u32 mSecondTitleCount; + SDChannelObj* mpCurrentLoadedChannel; + u32 mSDTitleCount; + u32 mNandTitleCount; + u32* mpChannelTitleIds; + u32 mPendingOperation; + int mLastOperation; + layout::Object* mpErrorLayout; + layout::Object* mpPointerLayout; + layout::Object* mpHelpButtonLayout; + int mOperationResult; + u8 mbShowNoCardMessage; + u8 mbOperationActive; + u8 mbSDCardBroken; + u32 mOperationState; + u32 mDialogState; + nand::File* mpSaveDataFile; + u32 mAnimationState; + u32 mAnimationTarget; + OSTime mOperationStartTime; + nand::File* mpCorruptIconFile; + u8 mbHazardTitleFound; + u8 mbChannelLimitReached; + u8 mbInitialLoadComplete; + u8 mbNeedsRefresh; + }; + } +} + +#endif diff --git a/include/system/iplSaveDataManager.h b/include/system/iplSaveDataManager.h index 0af3e212..4ede525a 100644 --- a/include/system/iplSaveDataManager.h +++ b/include/system/iplSaveDataManager.h @@ -50,6 +50,12 @@ namespace ipl { int getPrevPage() { return mLastPrevPage; } +#ifdef IPL_SD_CHANNEL_SELECT_ACCESS + int getLastSDPrevPage() { return mLastSDPrevPage; } + void setLastSDPrevPage(int page) { mLastSDPrevPage = page; } + BOOL didntGotoSDMenu() const { return mData.didntGotoSDMenu; } +#endif + bool hasPhotoMP3Dummy() { return mbPhotoMP3; } bool hasPhoto2Title() { return mbPhoto2; } bool hasPhoto2DummyCheck() { return mbPhoto2Check; } diff --git a/src/scene/sdChannelSelect/iplSDChannelSelect.cpp b/src/scene/sdChannelSelect/iplSDChannelSelect.cpp new file mode 100644 index 00000000..793ccfb9 --- /dev/null +++ b/src/scene/sdChannelSelect/iplSDChannelSelect.cpp @@ -0,0 +1,1409 @@ +#define IPL_SD_CHANNEL_SELECT_ACCESS +#define IPL_SD_CHANNEL_SELECT_CPP + +#include + +#include "iplSceneUI.h" +#include "system/iplSystem.h" +#include "system/iplSaveDataManager.h" +#include "utility/iplCSFlags.h" +#include "sound/iplSound.h" + +#include "scene/sdChannelSelect/iplSDChannelSelect.h" + +#include +#include + +namespace ipl { + namespace scene { + namespace { + class SDChannelSelectButtonEventHandler : public SDButtonEventHandlerBase { + public: + explicit SDChannelSelectButtonEventHandler(SDChannelSelect* scene) + : mpScene(scene) { + } + + void onEventDerived(u32 compId, u32 event, const controller::Interface* con) override { + } + + private: + SDChannelSelect* mpScene; + }; + + } + + const char* SDChannelSelect::mscChannelPaneNames[PAGE_COUNT][MAX_CHANNEL_INDEX] = { + { + "", "", "", "N_Ch_a04", "", "", "", "N_Ch_a08", "", "", "", "N_Ch_a12", + }, + { + "N_Ch_b01", "N_Ch_b02", "N_Ch_b03", "N_Ch_b04", "N_Ch_b05", "N_Ch_b06", + "N_Ch_b07", "N_Ch_b08", "N_Ch_b09", "N_Ch_b10", "N_Ch_b11", "N_Ch_b12", + }, + { + "N_Ch_c01", "N_Ch_c02", "N_Ch_c03", "N_Ch_c04", "N_Ch_c05", "N_Ch_c06", + "N_Ch_c07", "N_Ch_c08", "N_Ch_c09", "N_Ch_c10", "N_Ch_c11", "N_Ch_c12", + }, + { + "N_Ch_d01", "N_Ch_d02", "N_Ch_d03", "N_Ch_d04", "N_Ch_d05", "N_Ch_d06", + "N_Ch_d07", "N_Ch_d08", "N_Ch_d09", "N_Ch_d10", "N_Ch_d11", "N_Ch_d12", + }, + { + "N_Ch_e01", "", "", "", "N_Ch_e05", "", "", "", "N_Ch_e09", "", "", "", + }, + }; + + const char* SDChannelSelect::mscBasePaneNames[PAGE_COUNT] = { + "BaseMask0", "BaseMask1", "BaseMask2", "BaseMask3", "BaseMask4", + }; + + const char* SDChannelSelect::mscPicturePaneNames[PAGE_COUNT] = { + "Picture_00", "Picture_01", "Picture_02", "Picture_03", "Picture_04", + }; + + const char* SDChannelSelect::mscEdgePaneNames[PAGE_COUNT] = { + "Edge0", "Edge1", "Edge2", "Edge3", "Edge4", + }; + + const char* SDChannelSelect::mscClockPaneNames[3] = { + "N_Clock0", "N_Clock1", "N_Clock2", + }; + + const char* SDChannelSelect::mscMaskPaneName = "ChMask"; + + static const f32 sThumbnailOffsets[2][2] = { + {64.0f, 48.0f}, + {85.0f, 48.0f}, + }; + + static const u32 sChannelLayoutOrder[12] = { + 11, 7, 3, 10, 6, 2, 9, 5, 1, 8, 4, 0, + }; + + SDChannelSelect::SDChannelSelect(EGG::Heap* heap) + : FaderSceneBase(heap), + mpButtonEventHandler(new SDChannelSelectButtonEventHandler(this)), + mState(0), + mThumbOffsetX(sThumbnailOffsets[SCGetAspectRatio()][0]), + mThumbOffsetY(sThumbnailOffsets[SCGetAspectRatio()][1]), + mCommandQueue(4, 0, 0, 0), + mNoticeQueue(42, 0, 0, 0), + mCurrentSDState(0), + mPreviousSDState(0), + mWorkerState(0), + mWorkerCommand(1), + mpWorkerHeap(NULL), + mpThumbnailWorkHeap(NULL), + mpSDWorker(NULL), + mpSDTitleIds(NULL), + mpSDTitleInfo(NULL), + mpNandTitleInfo(NULL), + mpCurrentLoadedChannel(NULL), + mpChannelTitleIds(NULL), + mLastOperation(14), + mOperationResult(0), + mbShowNoCardMessage(false), + mbOperationActive(false), + mbSDCardBroken(false), + mOperationState(0), + mDialogState(0), + mpSaveDataFile(NULL), + mAnimationState(0), + mAnimationTarget(0), + mbHazardTitleFound(false), + mbChannelLimitReached(false), + mbInitialLoadComplete(false), + mbNeedsRefresh(false) { + mCurrentPage = System::getSaveData()->getLastSDPrevPage(); + mPageCount = 20; + mCurrentChannelIndex = 0; + mbLeftArrowVisible = mCurrentPage != 0; + mbRightArrowVisible = mCurrentPage != mPageCount - 1; + setSceneParentFlags(SCN_PARENTFLAG_DRAW | SCN_PARENTFLAG_CALC); + math::VEC3 position(0.0f, 0.0f, 0.0f); + mPosition = position; + math::VEC2 scale(1.0f, 1.0f); + mScale = scale; + + nw4r::ut::Rect projection4x3; + System::getProjectionRect4x3(&projection4x3); + nw4r::ut::Rect projection16x9; + System::getProjectionRect16x9(&projection16x9); + f32 aspectScale = projection16x9.GetWidth() / projection4x3.GetWidth(); + if (SCGetAspectRatio() != SC_ASPECT_RATIO_16x9) { + aspectScale = 1.0f; + } + mAspectRatioScale = aspectScale; + + memset(&mPointerPosition, 0, 0x30); + mpThumbnailHeap = EGG::ExpHeap::create( + 0x13610, heap, MEM_HEAP_OPT_DEBUG_FILL | MEM_HEAP_OPT_THREAD_SAFE); + mpLayoutHeap = EGG::UnitHeap::create( + EGG::UnitHeap::calcHeapSize(0x212B8, 0x2D, 32), 0x212B8, + System::getMem2App(), 32, 2); + nw4r::ut::List_Init(&mChannelObjects, 0); + createChannelList(mCurrentPage, true); + TVRCManager::getHandle()->setEnable(TRUE); + + mpChannelTitleIds = (u32*)new (System::getMem2App(), 32) u8[mPageCount * 0x30]; + memset(mpChannelTitleIds, 0, mPageCount * 0x30); + mpSDTitleInfo = new (System::getMem2App(), 32) + SDChannelSelectTitleInfo[0x4B00 / sizeof(SDChannelSelectTitleInfo)]; + memset(mpSDTitleInfo, 0, 0x4B00); + mpSDTitleIds = new (System::getMem2App(), 32) ESTitleId32[0x2580 / sizeof(ESTitleId32)]; + memset(mpSDTitleIds, 0, 0x2580); + mpNandTitleInfo = new (System::getMem2App(), 32) + NandSDWorker::TitleUsage[0x600 / sizeof(NandSDWorker::TitleUsage)]; + memset(mpNandTitleInfo, 0, 0x600); + mFirstTitleCount = 0; + mSecondTitleCount = 0; + mSourcePage = -1; + mSourceIndex = -1; + } + + SDChannelSelect::~SDChannelSelect() { + } + + BOOL SDChannelSelect::isResetProcessDone() { + switch (mLastOperation) { + case 5: + case 6: + case 7: + case 8: + return FALSE; + default: + return TRUE; + } + } + + void SDChannelSelect::prepare() { + System::getBS2Manager()->abort(); + mpLayoutFile = System::getNandManager()->readLayoutAsync(getSceneHeap(), "sdChanSel.ash"); + mpCorruptIconFile = System::getNandManager()->readAsync( + getSceneHeap(), "corrupt_icon.ash", 0, 0, 0); + + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + iplSDChannelObj_813E3104(channel); + } + } + + void SDChannelSelect::create() { + mpSDWorker = new (System::getMem2App(), 4) NandSDWorker(); + mpWorkerHeap = (EGG::Heap*)System::getMem2App()->alloc(0x3EA60, 0x40); + u32 thumbnailHeapSize = MEMCalcHeapSizeForUnitHeap(0x19620, 0x60, 0x20); + mpThumbnailWorkHeap = (EGG::Heap*)System::getMem2App()->alloc( + thumbnailHeapSize + 0x40000, 0x40); + mpSDWorker->create(mpWorkerHeap, NULL, mpThumbnailWorkHeap, 0x12); + + if (System::getSaveData()->didntGotoSDMenu() == FALSE) { + mpSDWorker->mount_sd_async(); + mWorkerState = 1; + } + + mpDialogHeap = EGG::ExpHeap::create(0x21100, getSceneHeap(), 6); + mpChannelHeap = EGG::ExpHeap::create(0x2C100, getSceneHeap(), 6); + mpRsoHeap = EGG::ExpHeap::create(TVRCManager::getHandle(), 0x200000, 0); + mpRsoThread = new (System::getMem2App(), 32) channel::RsoThread(mpRsoHeap); + + createBaseLayout(); + if (mCurrentPage < mPageCount - 1) { + createChannelList(mCurrentPage + 1, false); + } + if (mCurrentPage > 0) { + createChannelList(mCurrentPage - 1, false); + } + updateNoCardLayouts(); + createChannelThumbnails(); + + u32 startTick = OSGetTick(); + while (System::getBS2Manager()->getIPLState() != 8) { + System::getBS2Manager()->update(); + OSReport(" ... wait for bs2 abord\n"); + VIWaitForRetrace(); + } + u32 elapsedTicks = OSGetTick() - startTick; + OSReport("*** BS2 abort costs: %dms\n", OSTicksToMilliseconds(elapsedTicks)); + + System::getFader()->fadeIn(); + mState = 2; + utility::CSFlags::UpdateFlagsFile(); + } + + void SDChannelSelect::enqueueStartNotice() { + SDChannelSelectCommand command; + command.type = 1; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + } + + bool SDChannelSelect::enqueueFinishNotice() { + SDChannelSelectCommand command; + command.type = 2; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueNotice(u32 titleId, u32 argument0, u32 argument1) { + if (mCurrentSDState != 6) { + return false; + } + + if (mNoticeQueue.capacity != mNoticeQueue.count) { + SDChannelSelectCommand notice; + notice.type = 4; + notice.titleId = titleId; + notice.arguments.values[0] = argument0; + notice.arguments.values[1] = argument1; + notice.arguments.values[2] = 0; + mNoticeQueue.notices[mNoticeQueue.writeIndex].copyFrom(notice); + ++mNoticeQueue.writeIndex; + if (mNoticeQueue.writeIndex >= mNoticeQueue.capacity) { + mNoticeQueue.writeIndex = 0; + } + ++mNoticeQueue.count; + } + return true; + } + + bool SDChannelSelect::enqueueLoadNotice() { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 8; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueuePageNotice() { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 9; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueResultNotice(u32 result) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 5; + command.titleId = result; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueChannelNotice(u32 controller, u32 page, u32 index, u32 value) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 10; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = value; + command.arguments.values[1] = (u32)&mFirstTitleCount; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueMoveNotice(u32 controller, u32 page, u32 index) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 6; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueStateNotice(u32 controller, u32 page, u32 index, u32 state) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 7; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = state; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueErrorNotice(u32 page, u32 index) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 11; + command.titleId = 0; + command.arguments.values[0] = page; + command.arguments.values[1] = index; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueCommandNotice(u32 page, u32 index, u32 commandType) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 12; + command.titleId = 0; + command.arguments.values[0] = page; + command.arguments.values[1] = index; + command.arguments.values[2] = commandType; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueDeleteNotice(u32 controller, u32 page, u32 index) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 13; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + void SDChannelSelect::clearCommandQueue() { + while (mCommandQueue.count > 0) { + mCommandQueue.pop(); + } + } + + void SDChannelSelect::clearNoticeQueue() { + while (mNoticeQueue.count > 0) { + mNoticeQueue.pop(); + } + } + + void SDChannelSelect::handleWorkerStartup() { + if (!mpSDWorker->is_working()) { + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OK) { + if (mOperationState == 0) { + setDialogMessage(8, 0xaa); + } + enqueueFinishNotice(); + mWorkerCommand = 1; + } + mpSDWorker->startup_async(); + mWorkerState = 2; + } else if (mPreviousSDState != mCurrentSDState && mCurrentSDState == 7) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } + } + + void SDChannelSelect::handleNandTitleCount() { + if (!mpSDWorker->is_working()) { + int result = mpSDWorker->get_async_result(); + if (result == NandSDWorker::RESULT_NAND_CORRUPT) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + return; + } + + mNandTitleCount = mpSDWorker->get_nand_app_num(); + if (mNandTitleCount > 0x60) { + mNandTitleCount = 0x60; + } + if (mNandTitleCount != 0) { + mpSDWorker->list_nand_apps_usage_async( + mpNandTitleInfo, reinterpret_cast(mNandTitleCount)); + mWorkerState = 3; + } else { + mWorkerState = 4; + } + } + } + + void SDChannelSelect::handleNandTitleUsage() { + if (!mpSDWorker->is_working()) { + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OK) { + qsort(mpNandTitleInfo, mNandTitleCount, sizeof(NandSDWorker::TitleUsage), + compareTitleUsage); + for (u32 index = 0; index < mNandTitleCount; ++index) { + mpNandTitleInfo[index].size -= 0x4000; + --mpNandTitleInfo[index].inode; + } + mWorkerState = 4; + } else { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2); + } + } + } + + void SDChannelSelect::handleNandTitleUsageComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDTitleList() { + if (mpSDWorker->is_working()) { + return; + } + + mLastOperation = 14; + if (mSDTitleCount == 0) { + if (mDialogState == 0) { + setDialogMessage(1, 0); + mWorkerCommand = 15; + } + return; + } + + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OK) { + for (u32 index = 0; index < mSDTitleCount; ++index) { + mpSDTitleInfo[index].titleId = mpSDTitleIds[index]; + if (mpSDTitleIds[index] == 0x48415A41) { + mbHazardTitleFound = true; + } + } + qsort(mpSDTitleInfo, mSDTitleCount, sizeof(SDChannelSelectTitleInfo), + compareTitleInfo); + enqueuePageNotice(); + mWorkerCommand = 1; + } else if (mDialogState == 0) { + setDialogMessage(2, 0xc3); + mWorkerCommand = 15; + } + } + + bool SDChannelSelect::setDialogMessage(u32 state, u32 message) { + if (mDialogState == 0) { + mDialogState = state; + mAnimationTarget = message; + return true; + } + return false; + } + + int SDChannelSelect::compareTitleUsage(const void* lhs, const void* rhs) { + const NandSDWorker::TitleUsage* left = + static_cast(lhs); + const NandSDWorker::TitleUsage* right = + static_cast(rhs); + if ((s32)left->size < (s32)right->size) { + return -1; + } + return left->size != right->size; + } + + int SDChannelSelect::compareTitleInfo(const void* lhs, const void* rhs) { + const SDChannelSelectTitleInfo* left = + static_cast(lhs); + const SDChannelSelectTitleInfo* right = + static_cast(rhs); + if (left->titleId < right->titleId) { + return -1; + } + return left->titleId != right->titleId; + } + + void SDChannelSelect::processWorkerCommands() { + if (mpSDWorker->is_working() || mWorkerState != 4) { + return; + } + + if (mCommandQueue.count == 0) { + if (mNoticeQueue.count > 0) { + mNoticeQueue.pop(); + } + return; + } + + SDChannelSelectCommand command = {0, 0, {{0, 0, 0}}}; + command.copyFrom(mCommandQueue.commands[mCommandQueue.readIndex]); + mLastOperation = command.type; + + switch (command.type) { + case 1: + mpSDWorker->mount_sd_async(); + mWorkerCommand = 0; + mbInitialLoadComplete = false; + break; + case 2: + mSDTitleCount = mpSDWorker->get_sd_app_num(); + mpSDWorker->list_sd_app_async(mpSDTitleIds); + mWorkerCommand = 2; + break; + case 5: + mpSDWorker->copy_sd_app_to_nand_async((ESTitleId32)command.titleId, true); + mWorkerCommand = 7; + break; + case 6: + mpSDWorker->copy_nand_app_to_sd_async((ESTitleId)command.titleId); + mWorkerCommand = 9; + break; + case 7: { + mpSDWorker->delete_nand_app_async((ESTitleId)command.titleId, + command.arguments.values[2] != 0); + mWorkerCommand = 10; + u32 index = 0; + while (index < mNandTitleCount && + mpNandTitleInfo[index].curTitleId != command.titleId) { + ++index; + } + if (index < mNandTitleCount) { + for (; index + 1 < mNandTitleCount; ++index) { + mpNandTitleInfo[index] = mpNandTitleInfo[index + 1]; + } + --mNandTitleCount; + } + break; + } + case 8: + mpSDWorker->update_sd_app_location_async(mpChannelTitleIds); + mWorkerCommand = 4; + break; + case 9: + mpSDWorker->read_sd_app_location_async(mpChannelTitleIds); + mWorkerCommand = 5; + break; + case 10: + mpSDWorker->check_for_sd_app_to_nand_async( + (ESTitleId)command.titleId, + command.arguments.appBlocks[0], command.arguments.appBlocks[1]); + mWorkerCommand = 8; + break; + case 11: + mpSDWorker->check_backup_fits_async( + command.arguments.titleLists[0], command.arguments.titleLists[1]); + mWorkerCommand = 11; + break; + case 12: + mpSDWorker->iplNandSD_81348EA8( + command.arguments.pointers[0], command.arguments.pointers[1], + command.arguments.pointers[2]); + mWorkerCommand = 12; + break; + case 13: + mpSDWorker->delete_sd_app_async((ESTitleId32)command.titleId); + mWorkerCommand = 13; + break; + default: + break; + } + + mCommandQueue.pop(); + } + + void SDChannelSelect::handleSDMountComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OUT_OF_SPACE) { + mbSDCardBroken = true; + } + mbShowNoCardMessage = true; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleCopyComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_NAND_CORRUPT) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } else { + mWorkerCommand = 1; + } + } + } + + void SDChannelSelect::handleDeleteComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleMoveComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_NAND_CORRUPT) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } else { + System::getChannelManager()->reserveRefresh(); + mWorkerCommand = 1; + } + } + } + + void SDChannelSelect::handleStorageCheckComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleCardCommand() { + if (mDialogState != 0) { + return; + } + + if (mpSDWorker->get_sd_state() == NandSDWorker::SD_STATE_EJECTED) { + setDialogMessage(2, 0xa9); + mWorkerCommand = 6; + } else if (mpSDWorker->get_sd_state() == NandSDWorker::SD_STATE_INSERTED) { + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDCardReady() { + if (mpSDWorker->get_sd_state() == NandSDWorker::SD_STATE_INSERTED && + mDialogState == 0) { + setDialogMessage(1, 0); + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDLocationUpdateComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDLocationReadComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleBackupFitComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleNandSDCleanupComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDDeleteComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::processWorkerState() { + mPreviousSDState = mCurrentSDState; + mCurrentSDState = mpSDWorker->get_sd_state(); + + if (mWorkerState == 2) { + handleNandTitleCount(); + } else if (mWorkerState < 2) { + if (mWorkerState > 0) { + handleWorkerStartup(); + } + } else if (mWorkerState < 4) { + handleNandTitleUsage(); + } + + switch (mWorkerCommand) { + case 0: + handleNandTitleUsageComplete(); + break; + case 1: + processWorkerCommands(); + break; + case 2: + handleSDTitleList(); + break; + case 3: + handleCopyComplete(); + break; + case 4: + handleSDMountComplete(); + break; + case 5: + handleDeleteComplete(); + break; + case 6: + handleSDCardReady(); + break; + case 7: + handleCopyComplete(); + break; + case 8: + handleSDLocationUpdateComplete(); + break; + case 9: + handleSDLocationReadComplete(); + break; + case 10: + handleMoveComplete(); + break; + case 11: + handleBackupFitComplete(); + break; + case 12: + handleNandSDCleanupComplete(); + break; + case 13: + handleSDDeleteComplete(); + break; + case 15: + handleCardCommand(); + break; + } + + if (mCurrentSDState != 6 && mState > 14 && mState < 24) { + mbDialogActive = true; + } + + updateDialogAnimation(); + } + + void SDChannelSelect::updateDialogAnimation() { + u32 animationIndex = 0xffffffff; + if (mpNoCardLayout->isPlaying()) { + animationIndex = 4; + if (!mpNoCardLayout->isPlaying(animationIndex)) { + return; + } + } + + switch (mOperationState) { + case 3: + mOperationState = 4; + mOperationStartTime = OSGetTime(); + break; + case 6: + mOperationState = 7; + break; + case 9: + mOperationState = 10; + mOperationStartTime = OSGetTime(); + break; + case 12: + mOperationState = 13; + break; + } + + if (mDialogState == 0) { + if (mOperationState == 10) { + mOperationState = 14; + } else if (mOperationState < 10 && mOperationState == 7) { + mOperationState = 8; + } + } else if (mDialogState == 2) { + switch (mOperationState) { + case 0: + case 1: + case 7: + case 13: + mOperationState = 2; + mAnimationState = mAnimationTarget; + break; + case 2: + if (mAnimationState != mAnimationTarget) { + mAnimationState = mAnimationTarget; + } + mDialogState = 0; + break; + case 4: + if (mAnimationState == mAnimationTarget) { + mDialogState = 0; + } else { + mOperationState = 5; + } + break; + case 10: + case 14: + case 15: + mOperationState = 11; + break; + } + } else if (mDialogState < 2) { + if (mDialogState > 0) { + switch (mOperationState) { + case 0: + case 1: + case 2: + case 7: + case 8: + case 13: + mOperationState = 1; + mDialogState = 0; + mAnimationState = mAnimationTarget; + break; + case 4: + mOperationState = 5; + break; + case 10: + case 14: + case 15: + mOperationState = 11; + break; + } + } + } else if (mDialogState == 8) { + switch (mOperationState) { + case 0: + case 1: + case 7: + case 13: + mOperationState = 8; + mAnimationState = mAnimationTarget; + break; + case 4: + mOperationState = 5; + break; + case 8: + if (mAnimationState != mAnimationTarget) { + mAnimationState = mAnimationTarget; + } + mDialogState = 0; + break; + case 10: + case 14: + case 15: + if (mAnimationState == mAnimationTarget) { + mDialogState = 0; + } else { + mOperationState = 11; + } + break; + } + } + + layout::Animator* animator = NULL; + switch (mOperationState) { + case 2: + static_cast(mpNoCardLayout->FindPaneByName("T_TimerMes")) + ->SetString(System::getMessage(mAnimationState), 0); + animator = mpNoCardLayout->getAnim(0); + break; + case 5: + animator = mpNoCardLayout->getAnim(1); + break; + case 8: + static_cast(mpNoCardLayout->FindPaneByName("T_TimerMes_01")) + ->SetString(System::getMessage(mAnimationState), 0); + animator = mpNoCardLayout->getAnim(2); + break; + case 11: + mpNoCardLayout->getAnim(4)->stop(); + animator = mpNoCardLayout->getAnim(3); + break; + case 14: + animator = mpNoCardLayout->getAnim(4); + break; + } + + if (animator != NULL) { + animator->initAnmFrame(); + animator->initFrame(); + animator->restart(); + ++mOperationState; + } + } + + void SDChannelSelect::updateChannelObjects() { + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + updateChannelObject(channel); + } + } + + void SDChannelSelect::updateChannelObject(SDChannelObj* channel) { + iplSDChannelObj_813E3104(channel); + iplSDChannelObj_813E311C(channel, mpDialogHeap, mpChannelHeap); + iplSDChannelObj_813E3178(channel, + getChannelBasePane(channel->getPage(), channel->getIndex(), + mCurrentPage)); + iplSDChannelObj_813E3180(channel, mpLayoutFile); + } + + void SDChannelSelect::calcChannelObjects() { + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + iplSDChannelObj_813E322C(channel); + } + } + + void SDChannelSelect::drawChannelObjects() { + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + if (hasChannelObject(channel->getPage(), channel->getIndex())) { + iplSDChannelObj_813E3304(channel); + } + } + + channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + if (hasChannelObject(channel->getPage(), channel->getIndex())) { + iplSDChannelObj_813E330C(channel); + } + } + } + + void SDChannelSelect::updateArrowVisibility() { + int leftPageOffset = (mState == 10 || mState == 22) ? 1 : 0; + int rightPageOffset = (mState == 11 || mState == 23) ? 1 : 0; + layout::Object* layout = mpLayout; + + if (mCurrentPage <= leftPageOffset) { + layout->hide(mscEdgePaneNames[0]); + layout->hide(mscEdgePaneNames[1]); + } else { + layout->show(mscEdgePaneNames[0]); + layout->show(mscEdgePaneNames[1]); + } + + if (mCurrentPage + rightPageOffset + 1 >= mPageCount) { + layout->hide(mscEdgePaneNames[3]); + layout->hide(mscEdgePaneNames[4]); + } else { + layout->show(mscEdgePaneNames[3]); + layout->show(mscEdgePaneNames[4]); + } + } + + FaderSceneCommand SDChannelSelect::calcFadein() { + return mpLayout->isPlaying(0) ? FADER_SCN_CONTINUE : FADER_SCN_NEXT; + } + + void SDChannelSelect::calcCommon() { + if (mState == 2 && !mpLayout->isPlaying(0)) { + SDButton* button = static_cast(System::getSceneManager()->getScene(0x24)); + if (button != NULL) { + button->setEventHandler(mpButtonEventHandler, NULL); + mState = 3; + if (mCurrentPage < 1) { + button->initArrowAppearance(1, false); + } else { + button->initArrowAppearance(1, true); + } + + if (mPageCount < 2 || mPageCount - 1 <= mCurrentPage) { + button->initArrowAppearance(0, false); + } else { + button->initArrowAppearance(0, true); + } + } + } + + if (mState == 3 && System::getFader()->getStatus() == EGG::Fader::PREPARE_OUT) { + if (System::getSaveData()->didntGotoSDMenu()) { + mOperationResult = 0; + mState = 24; + } else { + mState = 1; + } + } + + mpLayout->calc(); + mpPaneManager->calc(); + calcChannelObjects(); + mpPageLayouts[0]->calc(); + mpPageLayouts[1]->calc(); + mpPageLayouts[2]->calc(); + mpHelpButtonLayout->calc(); + mpErrorLayout->calc(); + mpStateLayout->calc(); + mpNoCardLayout->calc(); + processWorkerState(); + } + + void SDChannelSelect::initCalcFadeout() { + if (mState == 4) { + clearCommandQueue(); + clearNoticeQueue(); + System::getFader()->fadeOut(); + TVRCManager::getHandle()->setEnable(FALSE); + System::getChannelManager()->refreshAsync(); + reserveAllSceneDestruction(4, NULL); + } + } + + FaderSceneCommand SDChannelSelect::calcFadeout() { + FaderSceneCommand command = FADER_SCN_CONTINUE; + if (mState == 4) { + command = (FaderSceneCommand)!System::getFader()->getStatus(); + } + return command; + } + + void SDChannelSelect::draw() { + bool onDrawLayer = System::onDrawLayer(DRAW_LAYER_DEFAULT); + if (mState == 13) { + if (onDrawLayer) { + utility::Graphics::setOrtho(); + GXColor color = {0, 0, 0, 255}; + nw4r::ut::Rect projection; + System::getProjectionRect(&projection); + utility::Graphics::drawPolygon(projection, color); + } + return; + } + + if (!onDrawLayer) { + return; + } + + if (mState == 7 || mState == 12 || mState == 14) { + utility::Graphics::setOrthoTransAndScale(mPosition, mScale); + } + utility::Graphics::setOrtho(); + + for (int edge = 0; edge < PAGE_COUNT; ++edge) { + nw4r::lyt::Pane* pane = mpLayout->FindPaneByName(mscEdgePaneNames[edge]); + pane->SetVisible(true); + mpLayout->draw(pane); + pane->SetVisible(false); + } + + drawChannelObjects(); + updateArrowVisibility(); + + GXSetScissor(0, 0, System::getRenderModeObj()->fbWidth, + System::getRenderModeObj()->efbHeight); + + nw4r::lyt::Pane* mask = mpLayout->FindPaneByName(mscMaskPaneName); + mask->SetVisible(false); + mpLayout->draw(); + + nw4r::lyt::TextBox* pageText = static_cast( + mpDialogLayout->FindPaneByName("TextBox_00")); + for (int page = 0; page < 3; ++page) { + wchar_t pageNumber[20]; + swprintf(pageNumber, 19, L"%d", mCurrentPage + page); + pageText->SetString(pageNumber, 0); + mpDialogLayout->draw(); + } + + drawChannelObjects(); + mask->SetVisible(true); + mpLayout->draw(mask); + mpPageLayouts[1]->draw(); + mpNoCardLayout->draw(); + } + + void SDChannelSelect::destroyChannelObject(SDChannelObj* channel) { + EGG::Heap* heap = channel->getHeap(); + delete channel; + if (heap != NULL) { + heap->destroy(); + } + } + + bool SDChannelSelect::hasChannelObject(int page, int index) const { + if (page == mCurrentPage) { + return true; + } + + if (page == mCurrentPage - 1) { + if (mState == 10 || mState == 22) { + return true; + } + for (int current = 3; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } else if (page == mCurrentPage - 2) { + if (mState == 10 || mState == 22) { + for (int current = 3; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } + } else if (page == mCurrentPage + 1) { + if (mState == 11 || mState == 23) { + return true; + } + for (int current = 0; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } else if (page == mCurrentPage + 2 && (mState == 11 || mState == 23)) { + for (int current = 0; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } + + return false; + } + + void SDChannelSelect::destroy() { + System::getBS2Manager()->restart(); + System::getSaveData()->setLastSDPrevPage(mCurrentPage); + + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + nw4r::ut::List_Remove(&mChannelObjects, channel); + destroyChannelObject(channel); + } + + if (mpRsoThread != NULL) { + delete mpRsoThread; + mpRsoThread = NULL; + } + + if (mpThumbnailHeap != NULL) { + mpThumbnailHeap->destroy(); + } + if (mpLayoutHeap != NULL) { + mpLayoutHeap->destroy(); + } + if (mpDialogHeap != NULL) { + mpDialogHeap->destroy(); + } + if (mpChannelHeap != NULL) { + mpChannelHeap->destroy(); + } + + if (mpSaveDataFile != NULL) { + while (!System::getSaveData()->isFinished(mpSaveDataFile)) { + OSYieldThread(); + } + delete mpSaveDataFile; + mpSaveDataFile = NULL; + } + + if (mpSDWorker != NULL) { + if (!mpSDWorker->is_terminated()) { + mpSDWorker->terminate_async(); + while (mpSDWorker->is_working()) { + OSYieldThread(); + } + while (!mpSDWorker->is_terminated()) { + OSYieldThread(); + } + } + + if (mpWorkerHeap != NULL) { + mpWorkerHeap->destroy(); + } + if (mpThumbnailWorkHeap != NULL) { + mpThumbnailWorkHeap->destroy(); + } + + delete[] mpSDTitleIds; + delete[] mpSDTitleInfo; + delete[] mpChannelTitleIds; + delete[] mpNandTitleInfo; + delete mpSDWorker; + mpSDWorker = NULL; + } + } + + void SDChannelSelect::createBaseLayout() { + GXTexObj widescreenTexture; + GXTexObj standardTexture; + + mpLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "mn_SdcardMenu_a.brlyt"); + + if (SCGetAspectRatio() == SC_ASPECT_RATIO_16x9) { + mpLayout->FindPaneByName("ChangeTex16x9") + ->GetMaterial() + ->GetTexture(&widescreenTexture, GX_TEXMAP0); + mpLayout->FindPaneByName("Picture_16") + ->GetMaterial() + ->GetTexture(&standardTexture, GX_TEXMAP0); + + for (int page = 0; page < PAGE_COUNT; ++page) { + mpLayout->FindPaneByName(mscPicturePaneNames[page]) + ->GetMaterial() + ->SetTexture(GX_TEXMAP0, widescreenTexture); + mpLayout->FindPaneByName(mscEdgePaneNames[page]) + ->GetMaterial() + ->SetTexture(GX_TEXMAP0, standardTexture); + } + } + + mpLayout->bind("mn_SdcardMenu_a.brlan"); + mpLayout->finishBinding(); + + mpDialogLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "mn_SdcardMenu_Page.brlyt"); + mpNoCardLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "mn_Nocard.brlyt"); + mpNoCardLayout->bindToGroup("mn_Nocard_IN.brlan", "Group_00", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_Out.brlan", "Group_00", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_IN_02.brlan", "Group_01", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_Out_02.brlan", "Group_01", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_Wait.brlan", "G_Wait", false, true); + mpNoCardLayout->getAnim(0)->initAnmFrame(); + mpNoCardLayout->getAnim(2)->initAnmFrame(); + mpNoCardLayout->finishBinding(); + + mpHelpButtonLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "help_Btn.brlyt"); + + mpButtonEventHandler = new SDChannelSelectButtonEventHandler(this); + mpPaneManager = new gui::PaneManager(mpButtonEventHandler, mpLayout->getDrawInfo(), + NULL, NULL); + mpPaneManager->createLayoutScene(*mpLayout->getNW4RLyt()); + mpPaneManager->setAllComponentTriggerTarget(false); + + for (int index = 0; index < MAX_CHANNEL_INDEX; ++index) { + const char* paneName = mscChannelPaneNames[mCurrentPage % PAGE_COUNT][index]; + if (paneName[0] != '\0') { + mpPaneManager->getPaneComponentByPane(mpLayout->FindPaneByName(paneName)) + ->setTriggerTarget(true); + } + } + + for (int index = 0; index < 4; ++index) { + mpPageAnimations[index] = new math::HermiteIntp(); + } + } + + bool SDChannelSelect::isChannelInCalc(int page, int index, int currentPage) const { + int relativePage = page - currentPage; + if (relativePage <= -3 || relativePage >= 3 || + strcmp(mscChannelPaneNames[relativePage + 2][index], "") == 0) { + return false; + } + return true; + } + + nw4r::lyt::Pane* SDChannelSelect::getChannelBasePane(int page, int index, + int currentPage) const { + if (isChannelInCalc(page, index, currentPage)) { + return mpLayout->FindPaneByName(mscChannelPaneNames[page - currentPage + 2][index]); + } + return mpLayout->FindPaneByName("Picture_16"); + } + + nw4r::lyt::Pane* SDChannelSelect::getCenterChannelPane(int index) const { + return mpLayout->FindPaneByName(mscChannelPaneNames[2][index]); + } + + nw4r::lyt::Pane* SDChannelSelect::getChannelPane(int index) const { + return mpLayout->FindPaneByName(mscChannelPaneNames[2][index]); + } + + math::VEC3 SDChannelSelect::getChannelPanePosition(SDChannelSelect* scene, int index) { + math::VEC3 position(0.0f, 0.0f, 0.0f); + MTXMultVec(scene->getCenterChannelPane(index)->GetGlobalMtx(), position, position); + return position; + } + + void SDChannelSelect::calcPageAnimations() { + for (int index = 0; index < 4; ++index) { + math::HermiteIntp* animation = mpPageAnimations[index]; + animation->calc(); + } + } + + void SDChannelSelect::startResetting() { + snd::getSystem()->resetAllSound(); + clearCommandQueue(); + clearNoticeQueue(); + } + + void SDChannelSelectCommand::copyFrom(const SDChannelSelectCommand& other) { + type = other.type; + titleId = other.titleId; + arguments.values[0] = other.arguments.values[0]; + arguments.values[1] = other.arguments.values[1]; + arguments.values[2] = other.arguments.values[2]; + } + + bool SDChannelSelectCommandQueue::push(const SDChannelSelectCommand& command) { + if (capacity == count) { + return false; + } + + commands[writeIndex].copyFrom(command); + ++writeIndex; + if (writeIndex >= capacity) { + writeIndex = 0; + } + ++count; + return true; + } + + bool SDChannelSelectCommandQueue::pop() { + bool result = true; + if (count == 0) { + result = false; + } else { + ++readIndex; + if (readIndex >= capacity) { + readIndex = 0; + } + --count; + } + return result; + } + + bool SDChannelSelectNoticeQueue::pop() { + bool result = true; + if (count == 0) { + result = false; + } else { + ++readIndex; + if (readIndex >= capacity) { + readIndex = 0; + } + --count; + } + return result; + } + } +} -- 2.49.1