From 38db6d9418f482a629a467a1f4983139894794df Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:57:11 +0000 Subject: [PATCH 1/2] cleanup: NandSDWorker and ESMisc (gotos, comma conditions) (worker 7a56f54f) --- src/system/iplNandSDWorker.cpp | 220 ++++++++++---------- src/utility/iplESMisc.cpp | 106 ++++------ tools/decomp-assist/cleanup2-w2.attempts.md | 105 ++++++++++ 3 files changed, 254 insertions(+), 177 deletions(-) create mode 100644 tools/decomp-assist/cleanup2-w2.attempts.md diff --git a/src/system/iplNandSDWorker.cpp b/src/system/iplNandSDWorker.cpp index b360acaa..d3af23c8 100644 --- a/src/system/iplNandSDWorker.cpp +++ b/src/system/iplNandSDWorker.cpp @@ -4,7 +4,7 @@ #include "titledb.h" -#pragma sym on // required to match (fakematch?) +#pragma sym on // MWCC needs symbol mode to preserve this unit's inline code generation. // (for now, unless dtk makes the ATTRIBUTE_ALIGN part optional :P) // stub ATTRIBUTE_ALIGN @@ -37,7 +37,7 @@ namespace ipl { #ifndef NON_MATCHING - // this could work as a seperate unit??? + // MWCC needs these calls to emit the stack container's weak functions. void forceStackWeaks() { ut::FreeList freeList; freeList.init(NULL, 0, 0); @@ -77,6 +77,7 @@ namespace ipl { /* Setup important stuff */ + // MWCC needs this Work pointer when computing the thread stack end. Work* workForStackP = (Work*)((u8*)myWork + sizeof(myWork->threadStack)); OSCreateThread(&myWork->thread, thread_main, this, workForStackP->threadStack, sizeof(myWork->threadStack), priority, OS_THREAD_ATTR_DETACH); @@ -1169,7 +1170,6 @@ namespace ipl { } else { // transfer.id is valid. Do nothing. OSReport("NandSDWorker: %s already exist.\n", c_transferid_path); - goto clean_up; } clean_up: @@ -1314,7 +1314,6 @@ namespace ipl { } } result = RESULT_OK; - ret: return result; } @@ -1608,11 +1607,10 @@ namespace ipl { if (bannerFile->signature != WII_SAVE_BANNER_SIGNATURE) { OSReport("NandSDWorker: banner file %s signature is not correct\n", path); ret = RESULT_BAD_FILE; - goto clean_up; + } else { + ret = RESULT_OK; } - ret = RESULT_OK; - clean_up: if (fileOpened) { err = nand::wrapper::Close(&fileInfo); @@ -1980,6 +1978,7 @@ namespace ipl { ((AppBlocksInfo*)myWork->paramB)->blocks = userNodes; } + // MWCC needs the banner result to remain live through the free-area query. if (result != RESULT_OK) { myWork->asyncResult = result; goto clean_up; @@ -2111,11 +2110,10 @@ namespace ipl { if (netSize + 0x19000 > sdFreeArea) { OSReport("NandSDWorker: total backup size [%d] is too large for SD card. \n", netSize + 0x19000); myWork->asyncResult = netSize + 0x19000; - goto clean_up; + } else { + myWork->asyncResult = RESULT_OK; } - myWork->asyncResult = RESULT_OK; - clean_up: MEMFreeToExpHeap(myWork->mainHeap, backupData); } @@ -2885,47 +2883,44 @@ namespace ipl { isDataOnlyTitle = true; } - if (isDataOnlyTitle) { - goto start_backup; + if (!isDataOnlyTitle) { + if (!change_uid(myWork->curTitleId)) { + myWork->asyncResult = RESULT_FATAL_SD_ERROR; + goto clean_up; + } + get_nand_data_only_title_save_path(myWork->curTitleId, bnrPath); + + strncat(bnrPath, "/", NAND_MAX_PATH); + strncat(bnrPath, c_banner_file_name, NAND_MAX_PATH); + + err = nand::wrapper::GetStatus(bnrPath, &bnrFileStatus); + if (check_nand_corrupt(err, &myWork->asyncResult)) + goto clean_up; + if (err != NAND_RESULT_OK) { + OSReport("NandSDWorker: NANDGetStatus[%s] failed %d\n", bnrPath, err); + myWork->asyncResult = RESULT_FATAL_SD_ERROR; + goto clean_up; + } + sdSaveBnr->perms = bnrFileStatus.permission; + sdSaveBnr->attr = bnrFileStatus.attribute; + + bnrLen = nand_get_length(bnrPath); + if (bnrLen < 0) { + myWork->asyncResult = bnrLen; + goto clean_up; + } + sdSaveBnr->headerSize = bnrLen; + get_nand_data_only_title_save_path(myWork->curTitleId, bnrPath); + + err = nand::wrapper::ChangeDir(bnrPath); + if (err != NAND_RESULT_OK) { + OSReport("NandSDWorker: NANDChangeDir %s failed.[%d]\n", bnrPath, err); + myWork->asyncResult = RESULT_FATAL_SD_ERROR; + goto clean_up; + } + changedDir = true; } - if (!change_uid(myWork->curTitleId)) { - myWork->asyncResult = RESULT_FATAL_SD_ERROR; - goto clean_up; - } - get_nand_data_only_title_save_path(myWork->curTitleId, bnrPath); - - strncat(bnrPath, "/", NAND_MAX_PATH); - strncat(bnrPath, c_banner_file_name, NAND_MAX_PATH); - - err = nand::wrapper::GetStatus(bnrPath, &bnrFileStatus); - if (check_nand_corrupt(err, &myWork->asyncResult)) - goto clean_up; - if (err != NAND_RESULT_OK) { - OSReport("NandSDWorker: NANDGetStatus[%s] failed %d\n", bnrPath, err); - myWork->asyncResult = RESULT_FATAL_SD_ERROR; - goto clean_up; - } - sdSaveBnr->perms = bnrFileStatus.permission; - sdSaveBnr->attr = bnrFileStatus.attribute; - - bnrLen = nand_get_length(bnrPath); - if (bnrLen < 0) { - myWork->asyncResult = bnrLen; - goto clean_up; - } - sdSaveBnr->headerSize = bnrLen; - get_nand_data_only_title_save_path(myWork->curTitleId, bnrPath); - - err = nand::wrapper::ChangeDir(bnrPath); - if (err != NAND_RESULT_OK) { - OSReport("NandSDWorker: NANDChangeDir %s failed.[%d]\n", bnrPath, err); - myWork->asyncResult = RESULT_FATAL_SD_ERROR; - goto clean_up; - } - changedDir = true; - - start_backup: backupWadSize = 0; s32 wadErr; @@ -3014,6 +3009,7 @@ namespace ipl { nocopyExists = item_exist_nand_save_folder(myWork->curTitleId, c_nocopy_folder_name); notransferExists = item_exist_nand_save_folder(myWork->curTitleId, c_notransfer_folder_name); + // MWCC needs this separate boolean conversion when packing the copy flags. bool dataOnlyTitle; dataOnlyTitle = false; if (isDataOnlyTitle) { @@ -3165,6 +3161,7 @@ namespace ipl { char sdSavePath[NAND_MAX_PATH]; char targetPath[NAND_MAX_PATH]; char tmpPath[NAND_MAX_PATH]; + // MWCC needs this initialized buffer to preserve the retail stack frame. char unusedPath[NAND_MAX_PATH] = ""; bool changedDir = false; @@ -3543,56 +3540,49 @@ namespace ipl { OSTick startTick = OSGetTick(); - goto open_lib; - while (true) { + while (NWC24OpenLib(nwc24Work) != NWC24_OK) { OSReport("NandSDWorker: waiting NWC24Open.\n"); OSSleepTicks(OSMillisecondsToTicks((OSTime)30)); if (OSTicksToMilliseconds(OSGetTick() - startTick) > 3000) { ret = RESULT_FATAL_SD_ERROR; OSReport("NandSDWorker: NWC24Open failed.\n"); - break; + goto clean_up; } + } - open_lib: - if (NWC24OpenLib(nwc24Work) != NWC24_OK) { + u16 dlId = 0; + NWC24Err nwc24Err; + for (nwc24Err = NWC24IterateDlTask(&dlId, TRUE); nwc24Err >= NWC24_OK; nwc24Err = NWC24IterateDlTask(&dlId, FALSE)) { + NWC24DlTask dlTask; + nwc24Err = NWC24GetDlTask(&dlTask, dlId); + if (nwc24Err != NWC24_OK) { + OSReport("NandSDWorker: NWC24GetDlTask failed - [%d] -> continue\n", nwc24Err); continue; } - u16 dlId = 0; - NWC24Err nwc24Err; - for (nwc24Err = NWC24IterateDlTask(&dlId, TRUE); nwc24Err >= NWC24_OK; nwc24Err = NWC24IterateDlTask(&dlId, FALSE)) { - NWC24DlTask dlTask; - nwc24Err = NWC24GetDlTask(&dlTask, dlId); - if (nwc24Err != NWC24_OK) { - OSReport("NandSDWorker: NWC24GetDlTask failed - [%d] -> continue\n", nwc24Err); - continue; - } - - u32 dlAppId; - nwc24Err = NWC24GetDlAppId(&dlTask, &dlAppId); - if (nwc24Err != NWC24_OK) { - OSReport("NandSDWorker: NWC24GetDlAppId failed - [%d] -> continue\n", nwc24Err); - continue; - } - - if (dlAppId == titleId) { - OSReport("NandSDWorker: found dl task owned same titleid [%p]\n", &dlTask); - nwc24Err = NWC24DeleteDlTask(&dlTask); - if (nwc24Err != NWC24_OK) { - // @bug this should say NWC24DeleteDlTask, looks like it was copy-pasted from above - OSReport("NandSDWorker: NWC24GetDlAppId failed - [%d] -> continue\n", nwc24Err); - } else { - OSReport("NandSDWorker: delete download task for index : %d\n", dlId); - } - } else { - OSReport("NandSDWorker: ignore title id %d: %08x \n", dlId, dlAppId); - } - } - nwc24Err = NWC24CloseLib(); + u32 dlAppId; + nwc24Err = NWC24GetDlAppId(&dlTask, &dlAppId); if (nwc24Err != NWC24_OK) { - OSReport("NandSDWorker: NWC24CloseLib failed - [%d] -> continue\n", nwc24Err); + OSReport("NandSDWorker: NWC24GetDlAppId failed - [%d] -> continue\n", nwc24Err); + continue; } - break; + + if (dlAppId == titleId) { + OSReport("NandSDWorker: found dl task owned same titleid [%p]\n", &dlTask); + nwc24Err = NWC24DeleteDlTask(&dlTask); + if (nwc24Err != NWC24_OK) { + // @bug this should say NWC24DeleteDlTask, looks like it was copy-pasted from above + OSReport("NandSDWorker: NWC24GetDlAppId failed - [%d] -> continue\n", nwc24Err); + } else { + OSReport("NandSDWorker: delete download task for index : %d\n", dlId); + } + } else { + OSReport("NandSDWorker: ignore title id %d: %08x \n", dlId, dlAppId); + } + } + nwc24Err = NWC24CloseLib(); + if (nwc24Err != NWC24_OK) { + OSReport("NandSDWorker: NWC24CloseLib failed - [%d] -> continue\n", nwc24Err); } clean_up: @@ -3746,12 +3736,11 @@ namespace ipl { if (handle_sd_error(FAFclose(fStream), &myWork->asyncResult) != RESULT_OK) { OSReport("NandSDWorker: FAFclose %s failed.\n", sdAppPath); - goto clean_up; + } else { + myWork->sdAppNum++; + myWork->asyncResult = RESULT_OK; } - myWork->sdAppNum++; - myWork->asyncResult = RESULT_OK; - clean_up: MEMFreeToExpHeap(myWork->mainHeap, sdBanner); if (encBanner != NULL) { @@ -4006,12 +3995,12 @@ namespace ipl { if (err < ES_ERR_OK) { OSReport("NandSDWorker: ES_OpenTitleContentFile titleid 0x%016llx cidx %d failed.[%d]\n", titleId, contentIdx, err); ret = RESULT_FATAL_SD_ERROR; - goto clean_up; - } - ret = err; + } else { + ret = err; - *contentSizeOut = tmdView->contents[contentIdx].size; - OSReport("NandSDWorker: successfully open titleid 0x%016llx cidx %d. fd = %d, size = %d.\n", titleId, contentIdx, ret, *contentSizeOut); + *contentSizeOut = tmdView->contents[contentIdx].size; + OSReport("NandSDWorker: successfully open titleid 0x%016llx cidx %d. fd = %d, size = %d.\n", titleId, contentIdx, ret, *contentSizeOut); + } clean_up: if (tmdView != NULL) { @@ -4231,7 +4220,6 @@ namespace ipl { if (wadErr == WAD_ERROR_INCORRECT_DEVICE) { OSReport("NandSDWorker: WADRestoreSDEx failed, not original Wii.[%d]\n", wadErr); myWork->asyncResult = RESULT_NOT_TRANSFERRABLE; - goto clean_up; } else if (wadErr != WAD_ERROR_OK) { OSReport("NandSDWorker: WADRestoreSDEx failed.[%d]\n", wadErr); if (nand_app_exist_ex(sdAppBanner->titleId) == 1) { @@ -4245,17 +4233,16 @@ namespace ipl { } } myWork->asyncResult = RESULT_BAD_FILE; - goto clean_up; - } + } else { + OSReport("NandSDWorker: import app data titleid = 0x%016llx.\n", sdAppBanner->titleId); + myWork->nandAppNum++; + if (!changeAppCount) { + change_nand_app_count(1); + } - OSReport("NandSDWorker: import app data titleid = 0x%016llx.\n", sdAppBanner->titleId); - myWork->nandAppNum++; - if (!changeAppCount) { - change_nand_app_count(1); + myWork->asyncResult = RESULT_OK; } - myWork->asyncResult = RESULT_OK; - clean_up: if (sdAppBanner != NULL) { MEMFreeToAllocator(&myWork->scratchAllocator, sdAppBanner); @@ -4342,10 +4329,8 @@ namespace ipl { if (handle_sd_error_for_entry(FAFstat(appPath, &fileStat), &ret) != RESULT_OK) { // @bug this should say FAFstat, looks like it was copy-pasted from above OSReport("NandSDWorker: FAFclose failed.\n"); - goto clean_up; - } - if (fileStat.size <= ROUNDUP(appBanner->thumbSize, 64) + sizeof(SDAppBanner)) { + } else if (fileStat.size <= ROUNDUP(appBanner->thumbSize, 64) + sizeof(SDAppBanner)) { ret = RESULT_BAD_FILE; } @@ -4412,11 +4397,10 @@ namespace ipl { if (ret < RESULT_OK) { OSReport("NandSDWorker: cannot uncompress thumbnail of %016llx [%d].\n", appBanner->titleId, ret); ret = RESULT_BAD_FILE; - goto clean_up; + } else { + OSReport("NandSDWorker: uncompress thumbnail size = %d.\n", ret); } - OSReport("NandSDWorker: uncompress thumbnail size = %d.\n", ret); - clean_up: MEMFreeToExpHeap(myWork->mainHeap, cmprBuf); MEMFreeToAllocator(&myWork->scratchAllocator, encBanner); @@ -4526,7 +4510,6 @@ namespace ipl { } else { OSReport("NandSDWorker: ES_ListTitleContentsOnCard failed.[%d]\n", esErr); ret = EXISTENCE_NOEXIST; - goto clean_up; } clean_up: @@ -4647,6 +4630,13 @@ namespace ipl { } s32 NandSDWorker::uncompress_app_thumbnail(const u8* cmpr, u32 uncmprSize, u8* uncmpr) { + struct MD5Head { + u8 signature[4]; + u32 length; + u8 reserved[8]; + NETMD5Sum md5; + }; + s32 size; NETMD5Sum MD5Sum; @@ -4654,10 +4644,10 @@ namespace ipl { u32 dataLen = 0; u32 offset = 0; if (NAND_CHECK_MAGIC4(cmpr, 'I', 'M', 'D', '5')) { - dataLen = *(u32*)(cmpr + 4); + dataLen = ((const MD5Head*)cmpr)->length; hasMd5 = true; - memcpy(MD5Sum, cmpr + 0x10, 0x10); - offset = 0x20; + memcpy(MD5Sum, ((const MD5Head*)cmpr)->md5, sizeof(MD5Sum)); + offset = sizeof(MD5Head); } if (is_compressed(cmpr + offset)) { diff --git a/src/utility/iplESMisc.cpp b/src/utility/iplESMisc.cpp index 39804365..51989485 100644 --- a/src/utility/iplESMisc.cpp +++ b/src/utility/iplESMisc.cpp @@ -24,7 +24,6 @@ namespace ipl { namespace utility { -// meh #define ES_ERR_REPORT(msg, ...) OSReport("%s::%s: " msg "\n", __FILE__, __FUNCTION__, __VA_ARGS__); BOOL checkForNullTermination(char* str, u32 len); @@ -51,7 +50,6 @@ namespace ipl { OSReport("ESMisc::GetTmdView: ES_GetTmdView2 err %d\n", ret); heap->free(*outTmdView); *outTmdView = NULL; - goto out; } out: @@ -103,13 +101,9 @@ namespace ipl { if (numTicketViews >= inNumTicketViews) { OSReport("ESMisc::GetTicketView: Invalid index %d\n", numTicketViews); ret = ES_ERR_TICKET_NOT_FOUND; - goto out; - } - - if (ret == ES_ERR_OK) { + } else if (ret == ES_ERR_OK) { memcpy(ticketView, inTicketView + numTicketViews, sizeof(ESTicketView)); } - out: if (inTicketView != NULL) { heap->free(inTicketView); } @@ -673,12 +667,10 @@ namespace ipl { if (ret != NAND_RESULT_OK) { ES_ERR_REPORT("NANDReadDir failed: %d", ret); result = ret; - goto out; + } else { + result = nodes; } - - result = nodes; } - out: if (changedUid) { ChangeUid(SYSMENU_TITLE_ID); } @@ -721,6 +713,7 @@ namespace ipl { if (result < 0) { ES_ERR_REPORT("NumInodesSaveDirRoot failed: %d", result); } else { + // MWCC needs the rotate form for this zero test. result = __rlwnm(1, __cntlzw(result), 31, 31); } } @@ -741,15 +734,12 @@ namespace ipl { s32 ret = tmdFile.Open((char*)TMD_FILE); if (ret != ES_ERR_OK) { ES_ERR_REPORT("Open TMD Backup file failed: %d", ret); - goto do_proc; + } else { + ret = tmdFile.Backup(titleId); + if (ret != ES_ERR_OK) { + ES_ERR_REPORT("Backup TMD failed: %d", ret); + } } - - ret = tmdFile.Backup(titleId); - if (ret != ES_ERR_OK) { - ES_ERR_REPORT("Backup TMD failed: %d", ret); - goto do_proc; - } - do_proc: ret = ES_DeleteTitle(titleId); if (ret != ES_ERR_OK) { ES_ERR_REPORT("ES_DeleteTitle failed: %d for %016llx", ret, titleId); @@ -824,8 +814,7 @@ namespace ipl { u32 dlAppId; NWC24Err err; - goto open_lib; - while (true) { + while (NWC24OpenLib(nwc24Work) != NWC24_OK) { OSReport("%s::%s waiting NWC24Open.\n", __FILE__, __FUNCTION__); OSSleepTicks(OSMillisecondsToTicks((OSTime)30)); if (OSTicksToMilliseconds(OSGetTick() - startTick) > 3000) { @@ -833,42 +822,36 @@ namespace ipl { OSReport("%s::%s NWC24Open failed with time out.\n", __FILE__, __FUNCTION__); goto cleanup; } + } - open_lib: - if (NWC24OpenLib(nwc24Work) != NWC24_OK) { - continue; - } - - dlId = 0; - err = NWC24IterateDlTask(&dlId, TRUE); - while (err >= NWC24_OK) { - err = NWC24GetDlTask(&dlTask, dlId); + dlId = 0; + err = NWC24IterateDlTask(&dlId, TRUE); + while (err >= NWC24_OK) { + err = NWC24GetDlTask(&dlTask, dlId); + if (err != NWC24_OK) { + OSReport("%s::%s NWC24GetDlTask failed - [%d] -> continue\n", __FILE__, __FUNCTION__, err); + } else { + err = NWC24GetDlAppId(&dlTask, &dlAppId); if (err != NWC24_OK) { - OSReport("%s::%s NWC24GetDlTask failed - [%d] -> continue\n", __FILE__, __FUNCTION__, err); - } else { - err = NWC24GetDlAppId(&dlTask, &dlAppId); + OSReport("%s::%s NWC24GetDlAppId failed - [%d] -> continue\n", __FILE__, __FUNCTION__, err); + } else if (dlAppId == titleId) { + OSReport("%s::%s found dl task owned same titleid [%p]\n", __FILE__, __FUNCTION__, &dlTask); + err = NWC24DeleteDlTask(&dlTask); if (err != NWC24_OK) { OSReport("%s::%s NWC24GetDlAppId failed - [%d] -> continue\n", __FILE__, __FUNCTION__, err); - } else if (dlAppId == titleId) { - OSReport("%s::%s found dl task owned same titleid [%p]\n", __FILE__, __FUNCTION__, &dlTask); - err = NWC24DeleteDlTask(&dlTask); - if (err != NWC24_OK) { - OSReport("%s::%s NWC24GetDlAppId failed - [%d] -> continue\n", __FILE__, __FUNCTION__, err); - } else { - OSReport("%s::%s delete download task for index : %d\n", __FILE__, __FUNCTION__, dlId); - } } else { - OSReport("%s::%s ignore title id %d: %08x \n", __FILE__, __FUNCTION__, dlId, dlAppId); + OSReport("%s::%s delete download task for index : %d\n", __FILE__, __FUNCTION__, dlId); } + } else { + OSReport("%s::%s ignore title id %d: %08x \n", __FILE__, __FUNCTION__, dlId, dlAppId); } - err = NWC24IterateDlTask(&dlId, FALSE); } + err = NWC24IterateDlTask(&dlId, FALSE); + } - ret = NWC24CloseLib(); - if (ret != NWC24_OK) { - OSReport("%s::%s NWC24CloseLib failed - [%d] -> continue\n", __FILE__, __FUNCTION__, ret); - } - goto cleanup; + ret = NWC24CloseLib(); + if (ret != NWC24_OK) { + OSReport("%s::%s NWC24CloseLib failed - [%d] -> continue\n", __FILE__, __FUNCTION__, ret); } cleanup: @@ -950,42 +933,42 @@ namespace ipl { } ESError ESMisc::DeleteSavedata(ESTitleId titleId, EGG::Heap* heap) { - char dirPath[0x80] ALIGN32; - char filePath[0x41]; + char dirPath[OSRoundUp32B(NAND_MAX_PATH + 1)] ALIGN32; + char filePath[OSRoundUp32B(NAND_MAX_PATH + 1)] ALIGN32; char* entries = NULL; u32 entryCount = 0; char* entry; u32 i; s32 ret; - sprintf(dirPath + 0x20, "/title/%08x/%08x/data/", NANDTitleIdHi(titleId), NANDTitleIdLo(titleId)); - ret = NANDReadDir(dirPath + 0x20, NULL, &entryCount); + sprintf(dirPath, "/title/%08x/%08x/data/", NANDTitleIdHi(titleId), NANDTitleIdLo(titleId)); + ret = NANDReadDir(dirPath, NULL, &entryCount); if (ret != ES_ERR_OK || entryCount == 0) { - ES_ERR_REPORT("Could not read1 %s: %d", dirPath + 0x20, ret); + ES_ERR_REPORT("Could not read1 %s: %d", dirPath, ret); goto cleanup; } - entries = (char*)heap->alloc(OSRoundUp32B(entryCount * 0x41), -DEFAULT_ALIGN); + entries = (char*)heap->alloc(OSRoundUp32B(entryCount * (NAND_MAX_PATH + 1)), -DEFAULT_ALIGN); if (entries == NULL) { ret = -2; ES_ERR_REPORT("Could not alloc: %d", -2); goto cleanup; } - ret = NANDReadDir(dirPath + 0x20, entries, &entryCount); + ret = NANDReadDir(dirPath, entries, &entryCount); if (ret != ES_ERR_OK) { - ES_ERR_REPORT("Could not read2 %s: %d", dirPath + 0x20, ret); + ES_ERR_REPORT("Could not read2 %s: %d", dirPath, ret); goto cleanup; } entry = entries; for (i = 0; i < entryCount;) { - snprintf(filePath + 0x1c, 0x40, "%s%s", dirPath + 0x20, entry); - (filePath + 0x1c)[0x40] = 0; - ret = NANDPrivateDelete(filePath + 0x1c); + snprintf(filePath, NAND_MAX_PATH, "%s%s", dirPath, entry); + filePath[NAND_MAX_PATH] = 0; + ret = NANDPrivateDelete(filePath); if (ret != ES_ERR_OK) { - ES_ERR_REPORT("Failed to delete %s: %d", filePath + 0x1c, ret); + ES_ERR_REPORT("Failed to delete %s: %d", filePath, ret); } i++; entry += strlen(entry) + 1; @@ -1076,6 +1059,7 @@ namespace ipl { } valid = TRUE; + // MWCC needs both verification loops to share this failure label. verify_failed: if (!valid) { @@ -1364,7 +1348,6 @@ namespace ipl { // We are done!!! ret = NAND_RESULT_OK; mFileLength += entryLen; - goto out; } out: if (entry != NULL) { @@ -1425,7 +1408,6 @@ namespace ipl { ret = ES_ImportTitleDone(); if (ret != ES_ERR_OK) { ES_ERR_REPORT("ES_ImportTitleDone err: %d", ret); - goto out; } } out: diff --git a/tools/decomp-assist/cleanup2-w2.attempts.md b/tools/decomp-assist/cleanup2-w2.attempts.md new file mode 100644 index 00000000..27a0013a --- /dev/null +++ b/tools/decomp-assist/cleanup2-w2.attempts.md @@ -0,0 +1,105 @@ +# cleanup2-w2 + +Owned files: `src/system/iplNandSDWorker.cpp` and `src/utility/iplESMisc.cpp`. +Branch: `agent/w1009/cleanup2-w2`, baseline `85d653b0`. +Read `cleanup-common.md`, including wave-2 goto/comma guidance, and the unslop and writing-for-agents skills before edits. + +## Baseline + +- Full 43U build passed before edits. +- Live report: code, data, and linking 100%; 12563/12563 functions and 1028/1028 units. +- DOL SHA1: `26116613f624061ba99c8d1a299aaa6efa85670d`. +- Completion checker: `DECOMPLETE_OK`. +- Initial goto statements: NandSDWorker 208; ESMisc 52. +- Preserve ordinary error/resource cleanup paths. Try each structured rewrite separately and revert any changed allocated section, relocation, or symbol. +- Prior effort policy explains the exact Zelda verification helper's parameter-to-local title ID copy. Preserve it; do not repeat register-allocation permutations. + +## Trials +- `src/system/iplNandSDWorker` / `unit`: remove debug-symbol pragma. reverted; changed rel('.data', 0), ('.text', 0), rel('.text', 1), ('.text', 1), symbols, rel('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::delete_download_task`: replace jump into retry loop with while condition. reverted; changed symbols, rel('.text', 0). +- `src/utility/iplESMisc` / `DeleteDownloadTask`: replace jump into retry loop with while condition. reverted; changed rel('.text', 0), symbols. +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_nand_save_to_sd`: replace start_backup jump with guarded setup. reverted; changed symbols, rel('.text', 0). +- `src/utility/iplESMisc` / `ESMisc::DeleteTitle`: replace do_proc jumps with else around backup. kept; all allocated sections, relocations, and symbols unchanged. + +The first comparison conservatively rejected three control-flow rewrites because MWCC renumbered anonymous `@N` literal symbols. Their bytes and relocation destinations were unchanged. Normalize only these compiler-generated names and retry; named symbols and relocation destinations remain checked. +- `src/system/iplNandSDWorker` / `NandSDWorker::delete_download_task`: replace jump into retry loop with while condition. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `DeleteDownloadTask`: replace jump into retry loop with while condition. reverted; changed rel('.text', 0), symbols. +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_nand_save_to_sd`: replace start_backup jump with guarded setup. kept; all allocated sections, relocations, and symbols unchanged. + +The retry-loop rewrite in ESMisc also renumbers compiler-generated `__FUNCTION__$N` string symbols. Normalize their names while preserving their section, offset, size, bytes, and relocation destinations; retry it. +- `src/utility/iplESMisc` / `DeleteDownloadTask`: replace retry-entry jump and final cleanup jump with while condition. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::clean_duplicated_nand_app`: replace return-only goto label with early returns. reverted; changed symbols, rel('.text', 0), ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::clean_partial_nand_app`: replace return-only goto label with early returns. reverted; changed symbols, rel('.text', 0), ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::get_sd_wad_header`: replace return-only goto label with early returns. reverted; changed symbols, rel('.text', 0), ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::do_startup`: remove final jump to immediately following cleanup. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `ESMisc::GetTmdView`: replace return-only goto label with early returns. reverted; changed rel('.text', 0), ('.text', 0), symbols. +- `src/utility/iplESMisc` / `ESMisc::NumInodesSaveDirRoot`: replace cleanup jump with else for directory count. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `TMDFile::Backup`: remove final jump to immediately following cleanup. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `TMDFile::Restore`: remove final error jump to immediately following cleanup. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::do_check_for_sd_app_to_nand`: remove repeated result check after successful banner read. reverted; changed symbols, rel('.text', 0), ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_nand_save_to_sd`: remove copied boolean before encoding copy flags. reverted; changed symbols, rel('.text', 0), ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::check_backup_fits`: replace final jump to cleanup with else for success path. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::open_nand_app_content`: replace final jump to cleanup with else for success path. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_nand_app_to_sd`: replace final jump to cleanup with else for success path. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::get_sd_app_banner`: replace final jump to cleanup with else for success path. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::get_sd_app_thumbnail`: replace final jump to cleanup with else for success path. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::nand_app_exist_ex`: remove final jump to immediately following cleanup. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `ESMisc::GetTmdView`: remove final jump to immediately following return. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `ESMisc::GetTicketView`: replace cleanup jump with else-if around ticket copy. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `verifySavedataZD`: replace jumps between verification loops with an inline validation helper. reverted; changed symbols, rel('.text', 0), ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_sd_app_to_nand`: replace restore-error jumps with else for successful import. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::get_nand_save_banner`: replace signature-error cleanup jump with else for success result. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `forceStackWeaks`: remove stand-in function that emits stack inline functions. reverted; changed symbols, ('.text', 1), rel('.text', 0), rel('.text', 1), ('.text', 0), rel('.data', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::uncompress_app_thumbnail`: replace raw IMD5 offsets with the format header fields. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `ESMisc::CheckSafeDeleteTitle`: replace zero-test intrinsics with comparison. reverted; changed rel('.text', 0), symbols, ('.text', 0). +- `src/utility/iplESMisc` / `ESMisc::DeleteSavedata`: use path arrays directly instead of displaced stack addresses. reverted; changed ('.text', 0). +- `src/utility/iplESMisc` / `verifySavedataZD`: replace verification gotos with inline validation while retaining the outer valid flag. reverted; changed rel('.text', 0), symbols, ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::clean_duplicated_nand_app`: try early returns without shortening the final result lifetime. reverted; changed ('.text', 0), rel('.text', 0), symbols. +- `src/system/iplNandSDWorker` / `NandSDWorker::clean_partial_nand_app`: try early returns without shortening the final result lifetime. reverted; changed ('.text', 0), rel('.text', 0), symbols. +- `src/system/iplNandSDWorker` / `NandSDWorker::get_sd_wad_header`: try early returns without shortening the final result lifetime. reverted; changed ('.text', 0), rel('.text', 0), symbols. +- `src/system/iplNandSDWorker` / `NandSDWorker::clean_partial_nand_save`: remove unreferenced return label. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `ESMisc::DeleteSavedata`: use aligned path buffers rounded for a terminator, preserving the observed 0x40/0xa0 stack addresses. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::create`: use the thread stack end directly instead of a shifted Work pointer. reverted; changed rel('.text', 0), rel('.data', 0), symbols, ('.text', 0). +- `src/utility/iplESMisc` / `ESMisc::DeleteSavedata`: replace path-size literals with NAND_MAX_PATH. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_nand_save_to_sd`: assign the data-only title flag directly. reverted; changed rel('.text', 0), symbols, ('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_sd_save_to_nand`: remove unused initialized path buffer. reverted; changed ('.text', 0), symbols, rel('.text', 0). +- `src/system/iplNandSDWorker` / `NandSDWorker::do_copy_sd_app_to_nand`: use the success else at the final restore result, avoiding nesting the entire import setup. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `NandSDWorker::get_sd_app_banner`: combine nested success check into else-if. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `unit`: document compiler-required workarounds and trim rewrite whitespace. kept; all allocated sections, relocations, and symbols unchanged. +- `src/utility/iplESMisc` / `unit`: document retained zero-test and verification edges; remove stray comment. kept; all allocated sections, relocations, and symbols unchanged. +- `src/system/iplNandSDWorker` / `unit`: remove the remaining blank line left by the else-if rewrite. kept; all allocated sections, relocations, and symbols unchanged. + +## Accepted cleanup + +- NandSDWorker: 208 -> 197 goto statements. Replaced the retry-loop entry and save-backup setup jump with structured control flow, made final success paths explicit, removed redundant final jumps and an unreferenced label, and replaced raw IMD5 offsets with a real header struct. Ordinary resource/error cleanup jumps stay. +- ESMisc: 52 -> 43 goto statements. Structured ticket copying, inode counting, title backup, and the download retry loop; removed redundant final jumps. Replaced displaced save-data path addresses with aligned buffers and existing NAND path constants. +- Save-data frame evidence: baseline assembly uses directory path at `r1+0xa0` and file path at `r1+0x40`, with a dynamically aligned `0x120` frame. Two real path arrays sized `OSRoundUp32B(NAND_MAX_PATH + 1)` and aligned to 32 bytes preserve those addresses and every instruction. The file-path terminator now lies inside its declared buffer. +- Canonical object comparisons cover every allocated section, relocation target, and named symbol. Only compiler-generated anonymous literal and `__FUNCTION__` symbol numbers are normalized. All accepted edits preserve the baseline bytes and relocation destinations. +- No condition-level comma tricks or function-scoped optimization pragmas were present in these files. + +## Retained with evidence + +- NandSDWorker symbol mode and `forceStackWeaks`: removing either changes main/weak text and relocation ownership. The required emission remains, with one-line explanations. +- Shared return paths in duplicated/partial app cleanup and WAD-header reading: both early-return forms changed code, including the version preserving the final result assignment. These are ordinary common exits. +- Thread stack-end intermediate pointer, repeated banner result check, integer-to-boolean copy-flag conversion, and initialized unused save-path buffer: simpler forms change code. Added one-line MWCC explanations. +- ESMisc zero-test intrinsics and Zelda verification failure label: a comparison and two structured inline-validation forms change code. Retained them with one-line explanations. The existing title ID parameter copy remains untouched. +- The direct data-only flag assignment changed code. The SD-to-NAND version includes additional checks in its branch, so the simple replacement did not apply and made no edit. +- Replaced the initial wide import guard with a smaller final restore-result `else` after review. The final source keeps setup flat and preserves every byte. + +## Final validation + +- Required gate command: `python3 /mnt/drive2/projects/wii-ipl-workers/_restore0928-tools/gate.py src/system/iplNandSDWorker src/utility/iplESMisc --quick`. +- `GATE PASS`; full build passed; 0 regressions; 0 forbidden-pattern additions; 0 readability warnings. +- NandSDWorker: objdiff 203/203 functions, 51428/51428 code bytes, 12312/12312 data bytes; code/data/linking and every reported section 100%. +- ESMisc: objdiff 31/31 functions, 11200/11200 code bytes, 4416/4416 data bytes; code/data/linking and every reported section 100%. +- Explicit pool checks: NandSDWorker 280/280 identical strings; ESMisc 114/114 identical strings. +- Gate diagnostic caveat: its raw instruction counter prints NandSDWorker 7/203 because `odiff.dis` obtains `.text` by name, and pyelftools selects the last of this symbol-mode object's two `.text` sections. A direct `ctxdiff` trial likewise read 0 instructions for the 133-instruction download function. This is a reader error, not a source mismatch. +- Independent section-aware verification selects each function's `st_shndx`: NandSDWorker 203/203 and ESMisc 31/31 have identical instruction counts and raw function bytes against the original object. Disassembly also reports zero differences for every function. Evidence is in `/tmp/cleanup2-w2-sections.log`; the read-only helper is `/tmp/cleanup2-w2-sections.py`. +- Regenerated live report: `ninja build/43U/report.json`; completion checker: `DECOMPLETE_OK`. +- DOL SHA1: `26116613f624061ba99c8d1a299aaa6efa85670d`. +- Scope: only the two assigned source files and this attempts log. No push, PR, merge, rebase, other-worktree edits, or subagents. + +## Source commits + +- `483f492f`: NandSDWorker cleanup only. +- `6daf7896`: ESMisc cleanup only. -- 2.49.1 From 2bdc63eab74758d3fb7608dec91fea29351f9201 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:57:16 -0500 Subject: [PATCH 2/2] fix(checker): enforce section coverage and strict assembly inventory (#1351) --- .github/workflows/build.yml | 3 +- AGENTS.md | 5 +- tools/check_decomp_complete.py | 55 +++++++--- .../completion-sections-attempts.md | 36 +++++++ tools/test_workflow_guards.py | 102 +++++++++++++++++- 5 files changed, 184 insertions(+), 17 deletions(-) create mode 100644 tools/decomp-assist/completion-sections-attempts.md diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7f0f4c91..ec6e95fd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,7 +6,7 @@ on: workflow_dispatch: inputs: require_complete: - description: Fail unless 43U code, data, functions, units, and links are all 100% + description: Fail unless 43U binary matches completely and source inventory is complete required: false default: false type: boolean @@ -79,6 +79,7 @@ jobs: python tools/check_decomp_complete.py \ build/${{ matrix.version }}/report.json \ --dol build/${{ matrix.version }}/main.dol + python tools/check_asm_inventory.py # Upload map files - name: Upload map diff --git a/AGENTS.md b/AGENTS.md index 93f2ba55..971cf2b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,10 +94,11 @@ The final completion assertion is machine-checkable: ``` python3 tools/check_decomp_complete.py build/43U/report.json \ --dol build/43U/main.dol +python3 tools/check_asm_inventory.py ``` -It must pass before claiming full completion. GitHub Actions runs the same -assertion when manually dispatched with `require_complete=true`. +Both checks must pass before claiming full completion. GitHub Actions runs the same +assertions when manually dispatched with `require_complete=true`. Normal push and pull-request builds publish progress without failing on the current incomplete state. Use the manual `require_complete=true` dispatch for the terminal all-100% gate. diff --git a/tools/check_decomp_complete.py b/tools/check_decomp_complete.py index 6c8ceee3..80fabd84 100644 --- a/tools/check_decomp_complete.py +++ b/tools/check_decomp_complete.py @@ -15,6 +15,10 @@ EXPECTED_TOTAL_DATA = 1832684 EXPECTED_TOTAL_FUNCTIONS = 12563 INTEGER_PATTERN = re.compile(r"-?(0|[1-9][0-9]*)\Z") CODE_SECTIONS = frozenset({".text", ".init"}) +DATA_SECTIONS = frozenset({ + ".bss", "extab", "extabindex", ".ctors", ".ctors$10", ".dtors", + ".rodata", ".data", ".sdata2", ".sbss2", ".sdata", ".sbss", +}) # objdiff accumulates the aggregate fuzzy_match_percent in 32-bit floats over every code byte, # so a fully matched report can read 99.9998 instead of 100.0. Aggregates are accepted within # this tolerance only when every code byte is counted as matched; units, sections and functions @@ -132,6 +136,43 @@ def check_complete_measures(measures, label, failures, aggregate=False): percent(measures, "fuzzy_match_percent", f"{label} fuzzy_match_percent", failures) +def check_sections(sections, measures, name, failures): + if not isinstance(sections, list): + failures.append(f"{name}: missing sections") + return + sizes = {"code": 0, "data": 0} + names = set() + for section in sections: + if not isinstance(section, dict): + failures.append(f"{name}: invalid section entry") + continue + section_name = section.get("name") + label = f"{name} section {section_name}" + if not isinstance(section_name, str) or section_name not in CODE_SECTIONS | DATA_SECTIONS: + failures.append(f"{label}: unknown section name") + continue + if section_name in names: + failures.append(f"{label}: duplicate section") + names.add(section_name) + # Protobuf JSON omits a zero-valued size. objdiff counts data sections in + # full, but code measures exclude ignored/deduplicated function symbols. + size = count({"size": section.get("size", 0)}, "size", label, failures) + if size is not None: + sizes["code" if section_name in CODE_SECTIONS else "data"] += size + if "fuzzy_match_percent" in section: + percent(section, "fuzzy_match_percent", label, failures) + elif section_name in CODE_SECTIONS: + failures.append(f"{label}: missing fuzzy_match_percent") + for kind in ("code", "data"): + total = count({f"total_{kind}": measures.get(f"total_{kind}", 0)}, + f"total_{kind}", name, failures) + if total is not None and ( + sizes[kind] < total if kind == "code" else sizes[kind] != total + ): + relation = "<" if kind == "code" else "!=" + failures.append(f"{name} section {kind} coverage: {sizes[kind]} {relation} {total}") + + def key_for(value): return type(value).__name__, repr(value) @@ -215,19 +256,7 @@ def check_report(report): equal(unit_measures, "matched_functions", "total_functions", f"{name} function match", failures) percent(unit_measures, "matched_functions_percent", f"{name} function percent", failures) - sections = unit.get("sections") - if not isinstance(sections, list): - failures.append(f"{name}: missing sections") - else: - for section in sections: - if not isinstance(section, dict): - failures.append(f"{name}: invalid section entry") - continue - section_name = section.get("name", "") - if "fuzzy_match_percent" in section: - percent(section, "fuzzy_match_percent", f"{name} section {section_name}", failures) - elif isinstance(section_name, str) and section_name in CODE_SECTIONS: - failures.append(f"{name} section {section_name}: missing fuzzy_match_percent") + check_sections(unit.get("sections"), unit_measures, name, failures) functions = unit.get("functions", []) if total_functions is not None and total_functions > 0: diff --git a/tools/decomp-assist/completion-sections-attempts.md b/tools/decomp-assist/completion-sections-attempts.md new file mode 100644 index 00000000..ad07a9a3 --- /dev/null +++ b/tools/decomp-assist/completion-sections-attempts.md @@ -0,0 +1,36 @@ +# Strict completion section coverage + +Base: c3dd1c08c04a38975b63dded77a7aef6fce385f3 (rebased from aed62d8530993250fe0237e5adfd3b5a4d811020). +No source or build inputs changed by this candidate. + +Schema evidence: locally available objdiff source at c02eb31dbbf9dd33577aead353bb2db62933b2af, +`objdiff-cli/src/cmd/report.rs:250-325`, emits full section sizes, sums Data/Bss +section sizes into total_data, but sums only retained function symbols into +total_code. Hidden, ignored, zero-size and previously seen global/weak symbols +are excluded from code totals. `objdiff-core/protos/report.proto` declares +ReportItem.size as proto3 uint64; a missing JSON scalar size represents zero. +43U section classification comes from `config/43U/splits.txt`; `.ctors$10` +is a constructor subsection present in the generated report. + +Consequently section data bytes must equal total_data; section code bytes must +cover total_code, not necessarily equal it. In the current report msghndlr has +28 .text bytes but only 16 counted code bytes. No unit-specific exception is +needed. Unknown/duplicate section names and malformed sizes fail closed. +A structural check cannot authenticate a report against deliberately forged +sizes/names; original report generation and the independent DOL gate remain +required. Truly zero-byte records contribute no measurable coverage. + +Validation repeated after rebasing, using an unchanged copy of the parent-generated +c3dd1c08 main 43U report and DOL, without building main: + +- All 23 preexisting guards pass; 12 new guards bring the total to 35, no skips. +- Actual report and main DOL: DECOMPLETE_OK. +- All section lists emptied only in memory: 1,695 coverage failures. +- Each of the 2,676 section records deleted individually in memory: rejected. +- Data-only and protobuf zero-sized sections accepted; deduplicated code-size + slack accepted; code/data deficits, excess data and invalid records rejected. +- Strict combined report/DOL plus live inventory: exit 1, as required. + Inventory reports 166 functions / 168 bodies, 162 ORIGINAL and 4 PLACEHOLDER: + TMCJPEGDEC_err_restart, CNTCACHEClear, Manager::hasChannel, System::warning_run. +- CI inventory command is conditional on workflow_dispatch require_complete; + ordinary progress builds do not acquire a source-completion requirement. diff --git a/tools/test_workflow_guards.py b/tools/test_workflow_guards.py index ff5b171b..0fd44380 100644 --- a/tools/test_workflow_guards.py +++ b/tools/test_workflow_guards.py @@ -9,7 +9,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from check_decomp_complete import check_dol, check_report, exact +from check_decomp_complete import check_dol, check_report, check_sections, exact from check_asm_inventory import check_inventory @@ -138,6 +138,69 @@ void inactive() { asm("sync"); } self.assertTrue(any("inventory:" in failure for failure in self.check()[2])) +class SectionCoverageTests(unittest.TestCase): + def check(self, sections, **measures): + failures = [] + check_sections(sections, measures, "fixture", failures) + return failures + + def test_code_and_data_coverage_pass(self): + sections = [ + {"name": ".init", "size": "16", "fuzzy_match_percent": 100.0}, + {"name": ".data", "size": "8", "fuzzy_match_percent": 100.0}, + ] + self.assertEqual(self.check(sections, total_code="16", total_data="8"), []) + + def test_data_only_and_proto_zero_sizes_pass(self): + self.assertEqual(self.check([{"name": ".sbss", "size": "64"}], total_data="64"), []) + self.assertEqual(self.check([], total_code=0, total_data=0), []) + self.assertEqual(self.check([ + {"name": ".text", "fuzzy_match_percent": 100.0}, + {"name": ".bss"}, + ], total_code=0, total_data=0), []) + + def test_deduplicated_code_is_not_required_to_equal_section_size(self): + sections = [{"name": ".text", "size": "28", "fuzzy_match_percent": 100.0}] + self.assertEqual(self.check(sections, total_code="16"), []) + self.assertEqual(self.check(sections, total_code=0), []) + + def test_deleted_or_truncated_sections_fail(self): + for sections in ([], [{"name": ".text", "size": "12", "fuzzy_match_percent": 100.0}]): + with self.subTest(sections=sections): + failures = self.check(sections, total_code="16", total_data="8") + self.assertTrue(any("section code coverage" in item for item in failures)) + self.assertTrue(any("section data coverage" in item for item in failures)) + + def test_excess_data_is_not_hidden_by_code_slack(self): + failures = self.check([ + {"name": ".text", "size": "28", "fuzzy_match_percent": 100.0}, + {"name": ".bss", "size": "12"}, + ], total_code="16", total_data="8") + self.assertIn("fixture section data coverage: 12 != 8", failures) + + def test_invalid_section_sizes_fail(self): + for size in (-1, "-1", True, 1.5, "1.5", None): + with self.subTest(size=size): + self.assertTrue(self.check([{"name": ".data", "size": size}], total_data=0)) + + def test_invalid_and_duplicate_section_names_fail(self): + for name in (None, [], "", ".unknown"): + with self.subTest(name=name): + self.assertTrue(self.check([{"name": name, "size": "8"}], total_data="8")) + section = {"name": ".data", "size": "4"} + self.assertIn("fixture section .data: duplicate section", self.check([section, section], total_data="8")) + + def test_section_scores_remain_strict(self): + for section in ( + {"name": ".text", "size": "16"}, + {"name": ".text", "size": "16", "fuzzy_match_percent": 99.9999}, + {"name": ".data", "size": "8", "fuzzy_match_percent": 99.9999}, + ): + with self.subTest(section=section): + failures = self.check([section], total_code="16", total_data="8") + self.assertTrue(any("fixture section " + section["name"] in item for item in failures)) + + class WorkflowGuardTests(unittest.TestCase): def test_exact_percent_is_strict(self): self.assertTrue(exact(100.0)) @@ -233,6 +296,43 @@ class WorkflowGuardTests(unittest.TestCase): def test_complete_report_schema_passes(self): self.assertEqual(check_report(self.complete_report()), []) + def test_empty_section_arrays_cannot_claim_completion(self): + report = self.complete_report() + for unit in report["units"]: + unit["sections"] = [] + failures = check_report(report) + self.assertTrue(any("section code coverage" in failure for failure in failures)) + self.assertTrue(any("section data coverage" in failure for failure in failures)) + + def test_deleting_one_code_or_data_section_fails(self): + for kind, section_name in (("code", ".text"), ("data", ".sbss")): + with self.subTest(kind=kind): + report = self.complete_report() + unit = next(unit for unit in report["units"] + if any(section["name"] == section_name for section in unit["sections"])) + unit["sections"] = [section for section in unit["sections"] if section["name"] != section_name] + self.assertTrue(any(f"{unit['name']} section {kind} coverage" in failure + for failure in check_report(report))) + + def test_every_current_section_is_required_for_coverage(self): + for unit in self.complete_report()["units"]: + for index, section in enumerate(unit["sections"]): + with self.subTest(unit=unit["name"], section=section["name"]): + remaining = unit["sections"][:index] + unit["sections"][index + 1:] + failures = [] + check_sections(remaining, unit["measures"], unit["name"], failures) + self.assertTrue(any("coverage" in failure for failure in failures), failures) + + def test_inventory_gate_is_only_in_strict_completion_step(self): + workflow = (Path(__file__).resolve().parents[1] / ".github/workflows/build.yml").read_text(encoding="utf-8") + steps = workflow.split(" - name: ") + inventory_steps = [step for step in steps if "python tools/check_asm_inventory.py" in step] + self.assertEqual(len(inventory_steps), 1) + step = inventory_steps[0] + self.assertTrue(step.startswith("Enforce completion gate\n")) + self.assertIn("if: matrix.version == '43U' && github.event_name == 'workflow_dispatch' && inputs.require_complete == true", step) + self.assertIn("python tools/check_decomp_complete.py", step) + def test_aggregate_fuzzy_float_rounding_passes_only_when_fully_matched(self): report = self.complete_report() report["measures"]["fuzzy_match_percent"] = 99.999886 -- 2.49.1