diff --git a/src/Main/jkRes.c b/src/Main/jkRes.c index 5159e7972..f2dd88645 100644 --- a/src/Main/jkRes.c +++ b/src/Main/jkRes.c @@ -527,6 +527,17 @@ stdFile_t jkRes_FileOpen(const char *fpath, const char *mode) if ( v12 ) { v13 = resIdx; + // Added: a loose file in a later directory replaces an earlier hit + // (cutscenes rely on getting the real "resource\video\..." path), but + // the earlier handle was leaked: a FILE, or a GOB handle whose + // stdEmbeddedRes copy holds the whole file in memory (a 7 MB cutscene). + if ( v6 ) + { + if ( jkRes_aFiles[v13].useLowLevel ) + pLowLevelHS->fileClose(jkRes_aFiles[v13].fsHandle); + else + stdGob_FileClose(jkRes_aFiles[v13].gobHandle); + } jkRes_aFiles[v13].useLowLevel = 1; jkRes_aFiles[v13].fsHandle = v12; stdString_SafeStrCopy(jkRes_aFiles[resIdx].fpath, jkRes_idkGobPath, 128); diff --git a/src/Platform/Common/stdEmbeddedRes.c b/src/Platform/Common/stdEmbeddedRes.c index a95947d6e..4623d3e5d 100644 --- a/src/Platform/Common/stdEmbeddedRes.c +++ b/src/Platform/Common/stdEmbeddedRes.c @@ -59,9 +59,13 @@ for (int i = 0; i < strlen(tmp_filepath); i++) #if defined(TARGET_ESP32) // This runs for every GOB entry open; a real stat on the card costs a // FatFs directory scan each time. Consult the directory cache first. + // A loose file is read whole into memory here, which suits small overrides; + // a big one (a cutscene, checked before it plays) is left to jkRes, which + // opens resource/ files as streams. { const char* absPath = jk_esp_fs_path(tmp_filepath); - exists = jk_esp_fs_dir_might_exist(absPath) && (stat(absPath, &statstuff) >= 0); + exists = jk_esp_fs_dir_might_exist(absPath) && (stat(absPath, &statstuff) >= 0) && + statstuff.st_size <= 1024 * 1024; } if (!exists) { goto skip_fopen; @@ -101,6 +105,8 @@ for (int i = 0; i < strlen(tmp_filepath); i++) char errtmp[256]; snprintf(errtmp, 256, "Failed to read file `%s`!\n", filepath); stdEmbeddedRes_errmsg(errtmp); + free(file_contents); // Added: don't leak the copy and the file + fclose(f); return NULL; } file_contents[len] = 0; @@ -212,6 +218,8 @@ for (int i = 0; i < strlen(tmp_filepath); i++) char errtmp[256]; snprintf(errtmp, 256, "Failed to read file `%s`!\n", filepath); stdEmbeddedRes_errmsg(errtmp); + free(file_contents); // Added: don't leak the copy and the file + fclose(f); return NULL; } file_contents[len] = 0; diff --git a/src/Win95/stdGob.c b/src/Win95/stdGob.c index 99748314c..07504a2bc 100644 --- a/src/Win95/stdGob.c +++ b/src/Win95/stdGob.c @@ -200,14 +200,19 @@ GobFileHandle* stdGob_FileOpen(Gob *pGob, const char *aName) if (data) { result = pGob->aHandles; v5 = 0; - if ( !pGob->numHandles ) + // Added: free the loaded copy when no handle is free + if ( !pGob->numHandles ) { + free(data); return 0; + } while ( result->bUsed ) { ++result; - if ( ++v5 >= pGob->numHandles ) + if ( ++v5 >= pGob->numHandles ) { + free(data); return 0; + } } result->bIsMemoryMapped = 1; result->pMemory = (intptr_t)data;