Wrapped fopen/close/read/write functions inside a simple "IOFile" class. Reading, writing, and error checking became simpler in most cases. It should be near impossible to forget to close a file now that the destructor takes care of it. (I hope this fixes Issue 3635) I have tested the functionality of most things, but it is possible I broke something. :p

git-svn-id: https://dolphin-emu.googlecode.com/svn/trunk@7328 8ced0084-cf51-0410-be5f-012b33b47a6e
This commit is contained in:
Jordan Woyak
2011-03-11 10:21:46 +00:00
parent 4f69672b2b
commit 59fd1008ca
68 changed files with 1112 additions and 1154 deletions

View File

@ -205,16 +205,16 @@ bool CBoot::SetupWiiMemory(unsigned int _CountryCode)
break;
}
FILE* pTmp = fopen(filename.c_str(), "rb");
{
File::IOFile pTmp(filename, "rb");
if (!pTmp)
{
PanicAlertT("SetupWiiMem: Cant find setting file");
return false;
}
fread(Memory::GetPointer(0x3800), 256, 1, pTmp);
fclose(pTmp);
pTmp.ReadBytes(Memory::GetPointer(0x3800), 256);
}
/*
Set hardcoded global variables to Wii memory. These are partly collected from

View File

@ -29,15 +29,16 @@ CDolLoader::CDolLoader(u8* _pBuffer, u32 _Size)
CDolLoader::CDolLoader(const char* _szFilename)
: m_isWii(false)
{
u64 size = File::GetSize(_szFilename);
u8* tmpBuffer = new u8[(size_t)size];
const u64 size = File::GetSize(_szFilename);
u8* const tmpBuffer = new u8[(size_t)size];
FILE* pStream = fopen(_szFilename, "rb");
fread(tmpBuffer, (size_t)size, 1, pStream);
fclose(pStream);
{
File::IOFile pStream(_szFilename, "rb");
pStream.ReadBytes(tmpBuffer, (size_t)size);
}
Initialize(tmpBuffer, (u32)size);
delete [] tmpBuffer;
delete[] tmpBuffer;
}
CDolLoader::~CDolLoader()

View File

@ -27,11 +27,14 @@ bool CBoot::IsElfWii(const char *filename)
{
/* We already check if filename existed before we called this function, so
there is no need for another check, just read the file right away */
FILE *f = fopen(filename, "rb");
u64 filesize = File::GetSize(f);
u8 *mem = new u8[(size_t)filesize];
fread(mem, 1, (size_t)filesize, f);
fclose(f);
const u64 filesize = File::GetSize(filename);
u8 *const mem = new u8[(size_t)filesize];
{
File::IOFile f(filename, "rb");
f.ReadBytes(mem, (size_t)filesize);
}
ElfReader reader(mem);
// TODO: Find a more reliable way to distinguish.
@ -44,11 +47,13 @@ bool CBoot::IsElfWii(const char *filename)
bool CBoot::Boot_ELF(const char *filename)
{
FILE *f = fopen(filename, "rb");
u64 filesize = File::GetSize(f);
const u64 filesize = File::GetSize(filename);
u8 *mem = new u8[(size_t)filesize];
fread(mem, 1, (size_t)filesize, f);
fclose(f);
{
File::IOFile f(filename, "rb");
f.ReadBytes(mem, (size_t)filesize);
}
ElfReader reader(mem);
reader.LoadInto(0x80000000);

View File

@ -108,19 +108,20 @@ u64 CBoot::Install_WiiWAD(const char* _pFilename)
std::string TMDFileName(ContentPath);
TMDFileName += "title.tmd";
FILE* pTMDFile = fopen(TMDFileName.c_str(), "wb");
if (pTMDFile == NULL) {
File::IOFile pTMDFile(TMDFileName, "wb");
if (!pTMDFile)
{
PanicAlertT("WAD installation failed: error creating %s", TMDFileName.c_str());
return 0;
}
fwrite(ContentLoader.GetTmdHeader(), DiscIO::INANDContentLoader::TMD_HEADER_SIZE, 1, pTMDFile);
pTMDFile.WriteBytes(ContentLoader.GetTmdHeader(), DiscIO::INANDContentLoader::TMD_HEADER_SIZE);
for (u32 i = 0; i < ContentLoader.GetContentSize(); i++)
{
DiscIO::SNANDContent Content = ContentLoader.GetContent()[i];
fwrite(Content.m_Header, DiscIO::INANDContentLoader::CONTENT_HEADER_SIZE, 1, pTMDFile);
pTMDFile.WriteBytes(Content.m_Header, DiscIO::INANDContentLoader::CONTENT_HEADER_SIZE);
char APPFileName[1024];
if (Content.m_Type & 0x8000) //shared
@ -136,15 +137,14 @@ u64 CBoot::Install_WiiWAD(const char* _pFilename)
if (!File::Exists(APPFileName))
{
File::CreateFullPath(APPFileName);
FILE* pAPPFile = fopen(APPFileName, "wb");
if (pAPPFile == NULL)
File::IOFile pAPPFile(APPFileName, "wb");
if (!pAPPFile)
{
PanicAlertT("WAD installation failed: error creating %s", APPFileName);
return 0;
}
fwrite(Content.m_pData, Content.m_Size, 1, pAPPFile);
fclose(pAPPFile);
pAPPFile.WriteBytes(Content.m_pData, Content.m_Size);
}
else
{
@ -152,7 +152,7 @@ u64 CBoot::Install_WiiWAD(const char* _pFilename)
}
}
fclose(pTMDFile);
pTMDFile.Close();
//Extract and copy WAD's ticket to ticket directory
@ -164,8 +164,9 @@ u64 CBoot::Install_WiiWAD(const char* _pFilename)
sprintf(TicketFileName, "%sticket/%08x/%08x.tik",
File::GetUserPath(D_WIIUSER_IDX).c_str(), TitleID_HI, TitleID_LO);
FILE* pTicketFile = fopen(TicketFileName, "wb");
if (pTicketFile == NULL) {
File::IOFile pTicketFile(TicketFileName, "wb");
if (!pTicketFile)
{
PanicAlertT("WAD installation failed: error creating %s", TicketFileName);
return 0;
}
@ -173,13 +174,10 @@ u64 CBoot::Install_WiiWAD(const char* _pFilename)
DiscIO::WiiWAD Wad(_pFilename);
if (!Wad.IsValid())
{
fclose(pTicketFile);
return 0;
}
fwrite(Wad.GetTicket(), Wad.GetTicketSize(), 1, pTicketFile);
fclose(pTicketFile);
pTicketFile.WriteBytes(Wad.GetTicket(), Wad.GetTicketSize());
if (!DiscIO::cUIDsys::AccessInstance().AddTitle(TitleID))
{

View File

@ -104,13 +104,12 @@ void Console_Submit(const char *cmd)
u32 end;
sscanf(cmd, "%s %08x %08x %s", temp, &start, &end, filename);
FILE *f = fopen(filename, "wb");
File::IOFile f(filename, "wb");
for (u32 i = start; i < end; i++)
{
u8 b = Memory::ReadUnchecked_U8(i);
fputc(b,f);
fputc(b, f.GetHandle());
}
fclose(f);
INFO_LOG(CONSOLE, "Dumped from %08x to %08x to %s",start,end,filename);
}
CASE("disa")

View File

@ -31,6 +31,7 @@
#include "DSPHost.h"
#include "DSPAnalyzer.h"
#include "MemoryUtil.h"
#include "FileUtil.h"
#include "DSPHWInterface.h"
#include "DSPIntUtil.h"
@ -45,12 +46,12 @@ static std::mutex ExtIntCriticalSection;
static bool LoadRom(const char *fname, int size_in_words, u16 *rom)
{
FILE *pFile = fopen(fname, "rb");
File::IOFile pFile(fname, "rb");
const size_t size_in_bytes = size_in_words * sizeof(u16);
if (pFile)
{
fread(rom, 1, size_in_bytes, pFile);
fclose(pFile);
pFile.ReadArray(rom, size_in_words);
pFile.Close();
// Byteswap the rom.
for (int i = 0; i < size_in_words; i++)

View File

@ -50,7 +50,7 @@ DSPDisassembler::~DSPDisassembler()
{
// Some old code for logging unknown ops.
std::string filename = File::GetUserPath(D_DUMPDSP_IDX) + "UnkOps.txt";
FILE *uo = fopen(filename.c_str(), "w");
File::IOFile uo(filename, "w");
if (!uo)
return;
@ -61,18 +61,17 @@ DSPDisassembler::~DSPDisassembler()
if (iter->second > 0)
{
count++;
fprintf(uo, "OP%04x\t%d", iter->first, iter->second);
fprintf(uo.GetHandle(), "OP%04x\t%d", iter->first, iter->second);
for (int j = 15; j >= 0; j--) // print op bits
{
if ((j & 0x3) == 3)
fprintf(uo, "\tb");
fprintf(uo, "%d", (iter->first >> j) & 0x1);
fprintf(uo.GetHandle(), "\tb");
fprintf(uo.GetHandle(), "%d", (iter->first >> j) & 0x1);
}
fprintf(uo, "\n");
fprintf(uo.GetHandle(), "\n");
}
}
fprintf(uo, "Unknown opcodes count: %d\n", count);
fclose(uo);
fprintf(uo.GetHandle(), "Unknown opcodes count: %d\n", count);
}
bool DSPDisassembler::Disassemble(int start_pc, const std::vector<u16> &code, int base_addr, std::string &text)
@ -80,9 +79,10 @@ bool DSPDisassembler::Disassemble(int start_pc, const std::vector<u16> &code, in
const char *tmp1 = "tmp1.bin";
// First we have to dump the code to a bin file.
FILE *f = fopen(tmp1, "wb");
fwrite(&code[0], 1, code.size() * 2, f);
fclose(f);
{
File::IOFile f(tmp1, "wb");
f.WriteArray(&code[0], code.size());
}
// Run the two passes.
return DisFile(tmp1, base_addr, 1, text) && DisFile(tmp1, base_addr, 2, text);
@ -335,25 +335,25 @@ bool DSPDisassembler::DisOpcode(const u16 *binbuf, int base_addr, int pass, u16
bool DSPDisassembler::DisFile(const char* name, int base_addr, int pass, std::string &output)
{
FILE* in = fopen(name, "rb");
if (in == NULL)
File::IOFile in(name, "rb");
if (!in)
{
printf("gd_dis_file: No input\n");
return false;
}
int size = (int)File::GetSize(in) & ~1;
u16 *binbuf = new u16[size / 2];
fread(binbuf, 1, size, in);
fclose(in);
const int size = ((int)in.GetSize() & ~1) / 2;
u16 *const binbuf = new u16[size];
in.ReadArray(binbuf, size);
in.Close();
// Actually do the disassembly.
for (u16 pc = 0; pc < (size / 2);)
for (u16 pc = 0; pc < size;)
{
DisOpcode(binbuf, base_addr, pass, &pc, output);
if (pass == 2)
output.append("\n");
}
delete [] binbuf;
delete[] binbuf;
return true;
}

View File

@ -24,16 +24,14 @@ CDump::CDump(const char* _szFilename) :
m_pData(NULL),
m_bInit(false)
{
FILE* pStream = fopen(_szFilename, "rb");
if (pStream != NULL)
File::IOFile pStream(_szFilename, "rb");
if (pStream)
{
m_size = (size_t)File::GetSize(pStream);
m_size = (size_t)pStream.GetSize();
m_pData = new u8[m_size];
fread(m_pData, m_size, 1, pStream);
fclose(pStream);
pStream.ReadArray(m_pData, m_size);
}
}

View File

@ -21,7 +21,7 @@
#pragma once
#include "Common.h"
#include "FileUtil.h"
// C L A S S
@ -34,11 +34,10 @@ public:
m_bInit(false)
{
// try to open file
FILE* pStream = NULL;
fopen_s(&pStream, _szFilename, "rb");
File::IOFile pStream(_szFilename, "rb");
if (pStream)
{
fread(&m_dolheader, 1, sizeof(SDolHeader), pStream);
pStream.ReadArray(&m_dolheader, 1);
// swap memory
u32* p = (u32*)&m_dolheader;
@ -52,8 +51,8 @@ public:
{
u8* pTemp = new u8[m_dolheader.textSize[i]];
fseek(pStream, m_dolheader.textOffset[i], SEEK_SET);
fread(pTemp, 1, m_dolheader.textSize[i], pStream);
pStream.Seek(m_dolheader.textOffset[i], SEEK_SET);
pStream.ReadArray(pTemp, m_dolheader.textSize[i]);
for (size_t num=0; num<m_dolheader.textSize[i]; num++)
CMemory::Write_U8(pTemp[num], m_dolheader.textAddress[i] + num);
@ -69,8 +68,8 @@ public:
{
u8* pTemp = new u8[m_dolheader.dataSize[i]];
fseek(pStream, m_dolheader.dataOffset[i], SEEK_SET);
fread(pTemp, 1, m_dolheader.dataSize[i], pStream);
pStream.Seek(m_dolheader.dataOffset[i], SEEK_SET);
pStream.ReadArray(pTemp, m_dolheader.dataSize[i]);
for (size_t num=0; num<m_dolheader.dataSize[i]; num++)
CMemory::Write_U8(pTemp[num], m_dolheader.dataAddress[i] + num);
@ -79,7 +78,6 @@ public:
}
}
fclose(pStream);
m_bInit = true;
}
}

View File

@ -102,12 +102,8 @@ void CUCode_Rom::BootUCode()
char binFile[MAX_PATH];
sprintf(binFile, "%sDSP_UC_%08X.bin", File::GetUserPath(D_DUMPDSP_IDX).c_str(), ector_crc);
FILE* pFile = fopen(binFile, "wb");
if (pFile)
{
fwrite((u8*)Memory::GetPointer(m_CurrentUCode.m_RAMAddress), m_CurrentUCode.m_Length, 1, pFile);
fclose(pFile);
}
File::IOFile pFile(binFile, "wb");
pFile.WriteArray((u8*)Memory::GetPointer(m_CurrentUCode.m_RAMAddress), m_CurrentUCode.m_Length);
#endif
DEBUG_LOG(DSPHLE, "CurrentUCode SOURCE Addr: 0x%08x", m_CurrentUCode.m_RAMAddress);

View File

@ -148,12 +148,9 @@ void IUCode::PrepareBootUCode(u32 mail)
char binFile[MAX_PATH];
sprintf(binFile, "%sDSP_UC_%08X.bin", File::GetUserPath(D_DUMPDSP_IDX).c_str(), ector_crc);
FILE* pFile = fopen(binFile, "wb");
File::IOFile pFile(binFile, "wb");
if (pFile)
{
fwrite((u8*)Memory::GetPointer(m_NextUCode.iram_mram_addr), m_NextUCode.iram_size, 1, pFile);
fclose(pFile);
}
pFile.WriteArray((u8*)Memory::GetPointer(m_NextUCode.iram_mram_addr), m_NextUCode.iram_size);
#endif
DEBUG_LOG(DSPHLE, "PrepareBootUCode 0x%08x", ector_crc);

View File

@ -15,11 +15,8 @@
// Official SVN repository and contact information can be found at
// http://code.google.com/p/dolphin-emu/
#include <iostream> // I hope this doesn't break anything
#include <stdio.h>
#include <stdarg.h>
#include "Common.h" // for Common::swap
#include "FileUtil.h"
#include "DSP/DSPCore.h"
#include "DSPLLEGlobals.h"
@ -50,19 +47,17 @@ void ProfilerInit()
void ProfilerDump(u64 count)
{
FILE* pFile = fopen("DSP_Prof.txt", "wt");
if (pFile != NULL)
File::IOFile pFile("DSP_Prof.txt", "wt");
if (pFile)
{
fprintf(pFile, "Number of DSP steps: %llu\n\n", count);
fprintf(pFile.GetHandle(), "Number of DSP steps: %llu\n\n", count);
for (int i=0; i<PROFILE_MAP_SIZE;i++)
{
if (g_profileMap[i] > 0)
{
fprintf(pFile, "0x%04X: %llu\n", i, g_profileMap[i]);
fprintf(pFile.GetHandle(), "0x%04X: %llu\n", i, g_profileMap[i]);
}
}
fclose(pFile);
}
}

View File

@ -35,11 +35,11 @@ bool DumpDSPCode(const u8 *code_be, int size_in_bytes, u32 crc)
sprintf(binFile, "%sDSP_UC_%08X.bin", File::GetUserPath(D_DUMPDSP_IDX).c_str(), crc);
sprintf(txtFile, "%sDSP_UC_%08X.txt", File::GetUserPath(D_DUMPDSP_IDX).c_str(), crc);
FILE* pFile = fopen(binFile, "wb");
File::IOFile pFile(binFile, "wb");
if (pFile)
{
fwrite(code_be, size_in_bytes, 1, pFile);
fclose(pFile);
pFile.WriteBytes(code_be, size_in_bytes);
pFile.Close();
}
else
{
@ -71,17 +71,15 @@ bool DumpDSPCode(const u8 *code_be, int size_in_bytes, u32 crc)
bool DumpCWCode(u32 _Address, u32 _Length)
{
std::string filename = File::GetUserPath(D_DUMPDSP_IDX) + "DSP_UCode.bin";
FILE* pFile = fopen(filename.c_str(), "wb");
File::IOFile pFile(filename, "wb");
if (pFile != NULL)
if (pFile)
{
for (size_t i = _Address; i < _Address + _Length; i++)
for (size_t i = _Address; i != _Address + _Length; ++i)
{
u16 val = g_dsp.iram[i];
fprintf(pFile, " cw 0x%04x \n", val);
fprintf(pFile.GetHandle(), " cw 0x%04x \n", val);
}
fclose(pFile);
return true;
}

View File

@ -15,8 +15,6 @@
// Official SVN repository and contact information can be found at
// http://code.google.com/p/dolphin-emu/
#include <iostream> // I hope this doesn't break anything
#include <stdio.h>
#include <stdarg.h>
#include <list>
@ -25,6 +23,7 @@
#include "Common.h"
#include "StringUtil.h"
#include "FileUtil.h"
#include "DSP/DSPCore.h"
#include "DSPSymbols.h"
@ -121,8 +120,9 @@ void DisasssembleRange(u16 start, u16 end)
bool ReadAnnotatedAssembly(const char *filename)
{
FILE *f = fopen(filename, "r");
if (!f) {
File::IOFile f(filename, "r");
if (!f)
{
ERROR_LOG(DSPLLE, "Bah! ReadAnnotatedAssembly couldn't find the file %s", filename);
return false;
}
@ -139,7 +139,7 @@ bool ReadAnnotatedAssembly(const char *filename)
int symbol_count = 0;
Symbol current_symbol;
while (fgets(line, 512, f))
while (fgets(line, 512, f.GetHandle()))
{
// Scan string for the first 4-digit hex string.
size_t len = strlen(line);
@ -225,7 +225,6 @@ bool ReadAnnotatedAssembly(const char *filename)
errors++;
if (errors > 10)
{
fclose(f);
return false;
}
}
@ -245,7 +244,7 @@ bool ReadAnnotatedAssembly(const char *filename)
lines.push_back(TabsToSpaces(4, line));
line_counter++;
}
fclose(f);
return true;
}

View File

@ -146,13 +146,9 @@ CEXIIPL::~CEXIIPL()
m_pIPL = NULL;
}
// SRAM
FILE *file = fopen(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM.c_str(), "wb");
if (file)
{
fwrite(&g_SRAM, 1, 64, file);
fclose(file);
}
// SRAM
File::IOFile file(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM, "wb");
file.WriteArray(&g_SRAM, 1);
}
void CEXIIPL::DoState(PointerWrap &p)
{
@ -161,13 +157,12 @@ void CEXIIPL::DoState(PointerWrap &p)
void CEXIIPL::LoadFileToIPL(std::string filename, u32 offset)
{
FILE* pStream = fopen(filename.c_str(), "rb");
if (pStream != NULL)
File::IOFile pStream(filename, "rb");
if (pStream)
{
u64 filesize = File::GetSize(pStream);
u64 filesize = pStream.GetSize();
fread(m_pIPL + offset, 1, filesize, pStream);
fclose(pStream);
pStream.ReadBytes(m_pIPL + offset, filesize);
m_FontsLoaded = true;
}

View File

@ -73,19 +73,17 @@ CEXIMemoryCard::CEXIMemoryCard(const std::string& _rName, const std::string& _rF
card_id = 0xc221; // It's a nintendo brand memcard
FILE* pFile = NULL;
pFile = fopen(m_strFilename.c_str(), "rb");
File::IOFile pFile(m_strFilename, "rb");
if (pFile)
{
// Measure size of the memcard file.
memory_card_size = (int)File::GetSize(pFile);
memory_card_size = (int)pFile.GetSize();
nintendo_card_id = memory_card_size / SIZE_TO_Mb;
memory_card_content = new u8[memory_card_size];
memset(memory_card_content, 0xFF, memory_card_size);
INFO_LOG(EXPANSIONINTERFACE, "Reading memory card %s", m_strFilename.c_str());
fread(memory_card_content, 1, memory_card_size, pFile);
fclose(pFile);
pFile.ReadBytes(memory_card_content, memory_card_size);
SetCardFlashID(memory_card_content, card_index);
}
@ -103,36 +101,30 @@ CEXIMemoryCard::CEXIMemoryCard(const std::string& _rName, const std::string& _rF
}
}
void innerFlush(flushStruct* data)
void innerFlush(FlushData* data)
{
FILE* pFile = NULL;
pFile = fopen(data->filename.c_str(), "wb");
File::IOFile pFile(data->filename, "wb");
if (!pFile)
{
std::string dir;
SplitPath(data->filename, &dir, 0, 0);
if(!File::IsDirectory(dir))
if (!File::IsDirectory(dir))
File::CreateFullPath(dir);
pFile = fopen(data->filename.c_str(), "wb");
pFile.Open(data->filename, "wb");
}
if (!pFile) // Note - pFile changed inside above if
{
PanicAlertT("Could not write memory card file %s.\n\n"
"Are you running Dolphin from a CD/DVD, or is the save file maybe write protected?", data->filename.c_str());
delete data;
return;
}
fwrite(data->memcardContent, data->memcardSize, 1, pFile);
fclose(pFile);
pFile.WriteBytes(data->memcardContent, data->memcardSize);
if (!data->bExiting)
Core::DisplayMessage(StringFromFormat("Wrote memory card %c contents to %s", data->memcardIndex ? 'B' : 'A',
data->filename.c_str()).c_str(), 4000);
delete data;
Core::DisplayMessage(StringFromFormat("Wrote memory card %c contents to %s",
data->memcardIndex ? 'B' : 'A', data->filename.c_str()).c_str(), 4000);
return;
}
@ -150,14 +142,13 @@ void CEXIMemoryCard::Flush(bool exiting)
if(!exiting)
Core::DisplayMessage(StringFromFormat("Writing to memory card %c", card_index ? 'B' : 'A'), 1000);
flushStruct *fs = new flushStruct;
fs->filename = m_strFilename;
fs->memcardContent = memory_card_content;
fs->memcardIndex = card_index;
fs->memcardSize = memory_card_size;
fs->bExiting = exiting;
flushData.filename = m_strFilename;
flushData.memcardContent = memory_card_content;
flushData.memcardIndex = card_index;
flushData.memcardSize = memory_card_size;
flushData.bExiting = exiting;
flushThread = std::thread(innerFlush, fs);
flushThread = std::thread(innerFlush, &flushData);
if (exiting)
flushThread.join();

View File

@ -21,13 +21,13 @@
#include "Thread.h"
// Data structure to be passed to the flushing thread.
typedef struct
struct FlushData
{
bool bExiting;
std::string filename;
u8 *memcardContent;
int memcardSize, memcardIndex;
} flushStruct;
};
class CEXIMemoryCard : public IEXIDevice
{
@ -91,6 +91,7 @@ private:
int memory_card_size; //! in bytes, must be power of 2.
u8 *memory_card_content;
FlushData flushData;
std::thread flushThread;
protected:

View File

@ -71,19 +71,19 @@ SRAM sram_dump_german = {{
void initSRAM()
{
FILE *file = fopen(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM.c_str(), "rb");
if (file != NULL)
{
if (fread(&g_SRAM, 1, 64, file) < 64) {
ERROR_LOG(EXPANSIONINTERFACE, "EXI IPL-DEV: Could not read all of SRAM");
g_SRAM = sram_dump;
File::IOFile file(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM, "rb");
if (file)
{
if (!file.ReadArray(&g_SRAM, 1))
{
ERROR_LOG(EXPANSIONINTERFACE, "EXI IPL-DEV: Could not read all of SRAM");
g_SRAM = sram_dump;
}
}
else
{
g_SRAM = sram_dump;
}
fclose(file);
}
else
{
g_SRAM = sram_dump;
}
}
void SetCardFlashID(u8* buffer, u8 card_index)

View File

@ -56,30 +56,34 @@ void HLE_IPC_CreateVirtualFATFilesystem()
{
// cdb.vff is a virtual Fat filesystem created on first launch of sysmenu
// we create it here as it is faster ~3 minutes for me when sysmenu does it ~1 second created here
u8 cdbHDR[0x20] = {'V', 'F', 'F', 0x20, 0xfe, 0xff, 1, 0, 1, 0x40, 0, 0, 0, 0x20};
u8 cdbFAT[4] = {0xf0, 0xff, 0xff, 0xff};
FILE * cdbFile = fopen(cdbPath.c_str(), "wb");
const u8 cdbHDR[0x20] = {'V', 'F', 'F', 0x20, 0xfe, 0xff, 1, 0, 1, 0x40, 0, 0, 0, 0x20};
const u8 cdbFAT[4] = {0xf0, 0xff, 0xff, 0xff};
File::IOFile cdbFile(cdbPath, "wb");
if (cdbFile)
{
bool success = true;
if (fwrite(cdbHDR, 0x20, 1, cdbFile) != 1) success = false;
if (fwrite(cdbFAT, 0x4, 1, cdbFile) != 1) success = false;
fseeko(cdbFile, 0x14020, SEEK_SET);
if (fwrite(cdbFAT, 0x4, 1, cdbFile) != 1)success = false;
cdbFile.WriteBytes(cdbHDR, 0x20);
cdbFile.WriteBytes(cdbFAT, 0x4);
cdbFile.Seek(0x14020, SEEK_SET);
cdbFile.WriteBytes(cdbFAT, 0x4);
// 20 MiB file
fseeko(cdbFile, 0x01400000 - 1, SEEK_SET);
cdbFile.Seek(0x01400000 - 1, SEEK_SET);
// write the final 0 to 0 file from the second FAT to 20 MiB
if (fwrite(cdbHDR+14, 1, 1, cdbFile) != 1) success = false;
fclose(cdbFile);
if (!success) File::Delete(cdbPath);
cdbFile.WriteBytes(cdbHDR + 14, 1);
if (!cdbFile.IsGood())
{
cdbFile.Close();
File::Delete(cdbPath);
}
}
}
}
CWII_IPC_HLE_Device_FileIO::CWII_IPC_HLE_Device_FileIO(u32 _DeviceID, const std::string& _rDeviceName)
: IWII_IPC_HLE_Device(_DeviceID, _rDeviceName, false) // not a real hardware
, m_pFileHandle(NULL)
, m_FileLength(0)
: IWII_IPC_HLE_Device(_DeviceID, _rDeviceName, false) // not a real hardware
, m_pFileHandle(NULL)
, m_FileLength(0)
, m_Mode(0)
, m_Seek(0)
{
@ -94,11 +98,7 @@ bool CWII_IPC_HLE_Device_FileIO::Close(u32 _CommandAddress, bool _bForce)
{
INFO_LOG(WII_IPC_FILEIO, "FileIO: Close %s (DeviceID=%08x)", m_Name.c_str(), m_DeviceID);
if (m_pFileHandle != NULL)
{
fclose(m_pFileHandle);
m_pFileHandle = NULL;
}
m_pFileHandle.Close();
m_FileLength = 0;
m_Mode = 0;
@ -117,18 +117,14 @@ bool CWII_IPC_HLE_Device_FileIO::Open(u32 _CommandAddress, u32 _Mode)
u32 ReturnValue = 0;
// close the file handle if we get a reopen
if (m_pFileHandle != NULL)
{
fclose(m_pFileHandle);
m_pFileHandle = NULL;
}
m_pFileHandle.Close();
const char Modes[][128] =
const char* const Modes[] =
{
{ "Unk Mode" },
{ "Read only" },
{ "Write only" },
{ "Read and Write" }
"Unk Mode",
"Read only",
"Write only",
"Read and Write"
};
m_Filename = std::string(HLE_IPC_BuildFilename(m_Name.c_str(), 64));
@ -140,11 +136,22 @@ bool CWII_IPC_HLE_Device_FileIO::Open(u32 _CommandAddress, u32 _Mode)
INFO_LOG(WII_IPC_FILEIO, "FileIO: Open %s (%s)", m_Name.c_str(), Modes[_Mode]);
switch(_Mode)
{
case ISFS_OPEN_READ: m_pFileHandle = fopen(m_Filename.c_str(), "rb"); break;
case ISFS_OPEN_READ:
m_pFileHandle.Open(m_Filename, "rb");
break;
// "r+b" is technically wrong, but OPEN_WRITE should not truncate the file as "wb" does.
case ISFS_OPEN_WRITE: m_pFileHandle = fopen(m_Filename.c_str(), "r+b"); break;
case ISFS_OPEN_RW: m_pFileHandle = fopen(m_Filename.c_str(), "r+b"); break;
default: PanicAlertT("FileIO: Unknown open mode : 0x%02x", _Mode); break;
case ISFS_OPEN_WRITE:
m_pFileHandle.Open(m_Filename, "r+b");
break;
case ISFS_OPEN_RW:
m_pFileHandle.Open(m_Filename, "r+b");
break;
default:
PanicAlertT("FileIO: Unknown open mode : 0x%02x", _Mode);
break;
}
}
else
@ -155,7 +162,7 @@ bool CWII_IPC_HLE_Device_FileIO::Open(u32 _CommandAddress, u32 _Mode)
if (m_pFileHandle != NULL)
{
m_FileLength = (u32)File::GetSize(m_pFileHandle);
m_FileLength = (u32)m_pFileHandle.GetSize();
ReturnValue = m_DeviceID;
}
else if (ReturnValue == 0)
@ -173,9 +180,9 @@ bool CWII_IPC_HLE_Device_FileIO::Open(u32 _CommandAddress, u32 _Mode)
bool CWII_IPC_HLE_Device_FileIO::Seek(u32 _CommandAddress)
{
u32 ReturnValue = FS_INVALID_ARGUMENT;
s32 SeekPosition = Memory::Read_U32(_CommandAddress + 0xC);
s32 Mode = Memory::Read_U32(_CommandAddress + 0x10);
u64 fileSize = File::GetSize(m_pFileHandle);
const s32 SeekPosition = Memory::Read_U32(_CommandAddress + 0xC);
const s32 Mode = Memory::Read_U32(_CommandAddress + 0x10);
const u64 fileSize = m_pFileHandle.GetSize();
INFO_LOG(WII_IPC_FILEIO, "FileIO: Seek Pos: 0x%08x, Mode: %i (%s, Length=0x%08llx)", SeekPosition, Mode, m_Name.c_str(), fileSize);
@ -186,14 +193,14 @@ bool CWII_IPC_HLE_Device_FileIO::Seek(u32 _CommandAddress)
{
// POSIX allows seek past EOF, the Wii does not.
// TODO: Can we check this without tell'ing/seek'ing twice?
u64 curPos = ftello(m_pFileHandle);
if (fseeko(m_pFileHandle, SeekPosition, seek_mode[Mode]) == 0)
const u64 curPos = m_pFileHandle.Tell();
if (m_pFileHandle.Seek(SeekPosition, seek_mode[Mode]))
{
u64 newPos = ftello(m_pFileHandle);
const u64 newPos = m_pFileHandle.Tell();
if (newPos > fileSize)
{
ERROR_LOG(WII_IPC_FILEIO, "FILEIO: Seek past EOF - %s", m_Name.c_str());
fseeko(m_pFileHandle, curPos, SEEK_SET);
m_pFileHandle.Seek(curPos, SEEK_SET);
}
else
ReturnValue = (u32)newPos;
@ -214,13 +221,13 @@ bool CWII_IPC_HLE_Device_FileIO::Seek(u32 _CommandAddress)
}
bool CWII_IPC_HLE_Device_FileIO::Read(u32 _CommandAddress)
{
u32 ReturnValue = FS_EACCESS;
u32 Address = Memory::Read_U32(_CommandAddress + 0xC); // Read to this memory address
u32 Size = Memory::Read_U32(_CommandAddress + 0x10);
{
u32 ReturnValue = FS_EACCESS;
const u32 Address = Memory::Read_U32(_CommandAddress + 0xC); // Read to this memory address
const u32 Size = Memory::Read_U32(_CommandAddress + 0x10);
if (m_pFileHandle != NULL)
{
if (m_pFileHandle != NULL)
{
if (m_Mode == ISFS_OPEN_WRITE)
{
WARN_LOG(WII_IPC_FILEIO, "FileIO: Attempted to read 0x%x bytes to 0x%08x on write-only file %s", Size, Address, m_Name.c_str());
@ -228,24 +235,26 @@ bool CWII_IPC_HLE_Device_FileIO::Read(u32 _CommandAddress)
else
{
INFO_LOG(WII_IPC_FILEIO, "FileIO: Read 0x%x bytes to 0x%08x from %s", Size, Address, m_Name.c_str());
ReturnValue = (u32)fread(Memory::GetPointer(Address), 1, Size, m_pFileHandle);
if ((ReturnValue != Size) && ferror(m_pFileHandle)) ReturnValue = FS_EACCESS;
}
}
else
{
ERROR_LOG(WII_IPC_FILEIO, "FileIO: Failed to read from %s (Addr=0x%08x Size=0x%x) - file not open", m_Name.c_str(), Address, Size);
}
Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
return true;
ReturnValue = (u32)fread(Memory::GetPointer(Address), 1, Size, m_pFileHandle.GetHandle());
if (ReturnValue != Size && ferror(m_pFileHandle.GetHandle()))
ReturnValue = FS_EACCESS;
}
}
else
{
ERROR_LOG(WII_IPC_FILEIO, "FileIO: Failed to read from %s (Addr=0x%08x Size=0x%x) - file not open", m_Name.c_str(), Address, Size);
}
Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
return true;
}
bool CWII_IPC_HLE_Device_FileIO::Write(u32 _CommandAddress)
{
{
u32 ReturnValue = FS_EACCESS;
u32 Address = Memory::Read_U32(_CommandAddress + 0xC); // Write data from this memory address
u32 Size = Memory::Read_U32(_CommandAddress + 0x10);
const u32 Address = Memory::Read_U32(_CommandAddress + 0xC); // Write data from this memory address
const u32 Size = Memory::Read_U32(_CommandAddress + 0x10);
INFO_LOG(WII_IPC_FILEIO, "FileIO: Write 0x%04x bytes from 0x%08x to %s", Size, Address, m_Name.c_str());
@ -255,71 +264,66 @@ bool CWII_IPC_HLE_Device_FileIO::Write(u32 _CommandAddress)
{
WARN_LOG(WII_IPC_FILEIO, "FileIO: Attempted to write 0x%x bytes from 0x%08x to read-only file %s", Size, Address, m_Name.c_str());
}
else
else
{
size_t Result = fwrite(Memory::GetPointer(Address), Size, 1, m_pFileHandle);
#if MAX_LOGLEVEL >= DEBUG_LEVEL
_dbg_assert_msg_(WII_IPC_FILEIO, Result == 1, "fwrite failed");
#else
(void)Result;
#endif
ReturnValue = (Result == 1) ? Size : FS_EACCESS;
if (m_pFileHandle.WriteBytes(Memory::GetPointer(Address), Size))
ReturnValue = Size;
}
}
Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
return true;
Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
return true;
}
bool CWII_IPC_HLE_Device_FileIO::IOCtl(u32 _CommandAddress)
{
INFO_LOG(WII_IPC_FILEIO, "FileIO: IOCtl (Device=%s)", m_Name.c_str());
INFO_LOG(WII_IPC_FILEIO, "FileIO: IOCtl (Device=%s)", m_Name.c_str());
#if defined(_DEBUG) || defined(DEBUGFAST)
DumpCommands(_CommandAddress);
#endif
u32 Parameter = Memory::Read_U32(_CommandAddress + 0xC);
const u32 Parameter = Memory::Read_U32(_CommandAddress + 0xC);
//u32 BufferIn = Memory::Read_U32(_CommandAddress + 0x10);
//u32 BufferInSize = Memory::Read_U32(_CommandAddress + 0x14);
//u32 BufferOut = Memory::Read_U32(_CommandAddress + 0x18);
//u32 BufferOutSize = Memory::Read_U32(_CommandAddress + 0x1C);
//u32 BufferIn = Memory::Read_U32(_CommandAddress + 0x10);
//u32 BufferInSize = Memory::Read_U32(_CommandAddress + 0x14);
//u32 BufferOut = Memory::Read_U32(_CommandAddress + 0x18);
//u32 BufferOutSize = Memory::Read_U32(_CommandAddress + 0x1C);
switch(Parameter)
{
case ISFS_IOCTL_GETFILESTATS:
{
m_FileLength = (u32)File::GetSize(m_pFileHandle);
u32 Position = (u32)ftello(m_pFileHandle);
switch(Parameter)
{
case ISFS_IOCTL_GETFILESTATS:
{
m_FileLength = (u32)m_pFileHandle.GetSize();
const u32 Position = (u32)m_pFileHandle.Tell();
u32 BufferOut = Memory::Read_U32(_CommandAddress + 0x18);
INFO_LOG(WII_IPC_FILEIO, "FileIO: ISFS_IOCTL_GETFILESTATS");
const u32 BufferOut = Memory::Read_U32(_CommandAddress + 0x18);
INFO_LOG(WII_IPC_FILEIO, "FileIO: ISFS_IOCTL_GETFILESTATS");
INFO_LOG(WII_IPC_FILEIO, " File: %s, Length: %i, Pos: %i", m_Name.c_str(), m_FileLength, Position);
Memory::Write_U32(m_FileLength, BufferOut);
Memory::Write_U32(Position, BufferOut+4);
}
break;
Memory::Write_U32(m_FileLength, BufferOut);
Memory::Write_U32(Position, BufferOut+4);
}
break;
default:
{
PanicAlert("CWII_IPC_HLE_Device_FileIO: Parameter %i", Parameter);
}
break;
default:
{
PanicAlert("CWII_IPC_HLE_Device_FileIO: Parameter %i", Parameter);
}
break;
}
}
// Return Value
u32 ReturnValue = 0; // no error
Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
// Return Value
const u32 ReturnValue = 0; // no error
Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
return true;
return true;
}
void CWII_IPC_HLE_Device_FileIO::DoState(PointerWrap &p)
{
if (p.GetMode() == PointerWrap::MODE_WRITE)
{
m_Seek = (m_pFileHandle) ? (s32)ftello(m_pFileHandle) : 0;
m_Seek = (m_pFileHandle) ? (s32)m_pFileHandle.Tell() : 0;
}
p.Do(m_Mode);
@ -330,8 +334,7 @@ void CWII_IPC_HLE_Device_FileIO::DoState(PointerWrap &p)
if (m_Mode)
{
Open(0, m_Mode);
if (m_pFileHandle)
fseeko(m_pFileHandle, m_Seek, SEEK_SET);
m_pFileHandle.Seek(m_Seek, SEEK_SET);
}
}
}

View File

@ -19,6 +19,7 @@
#define _WII_IPC_HLE_DEVICE_FILEIO_H_
#include "WII_IPC_HLE_Device.h"
#include "FileUtil.h"
std::string HLE_IPC_BuildFilename(const char* _pFilename, int _size);
void HLE_IPC_CreateVirtualFATFilesystem();
@ -72,7 +73,7 @@ private:
ISFS_IOCTL_SHUTDOWN
};
FILE* m_pFileHandle;
File::IOFile m_pFileHandle;
u32 m_FileLength;
u32 m_Mode;
s32 m_Seek;

View File

@ -486,18 +486,15 @@ bool CWII_IPC_HLE_Device_es::IOCtlV(u32 _CommandAddress)
if (File::Exists(TicketFilename))
{
const u32 SIZE_OF_ONE_TICKET = 676;
FILE* pFile = fopen(TicketFilename.c_str(), "rb");
File::IOFile pFile(TicketFilename, "rb");
if (pFile)
{
unsigned int View = 0;
u8 Ticket[SIZE_OF_ONE_TICKET];
while (View < maxViews && fread(Ticket, SIZE_OF_ONE_TICKET, 1, pFile) == 1)
for (unsigned int View = 0; View != maxViews && pFile.ReadBytes(Ticket, SIZE_OF_ONE_TICKET); ++View)
{
Memory::Write_U32(View, Buffer.PayloadBuffer[0].m_Address + View * 0xD8);
Memory::WriteBigEData(Ticket+0x1D0, Buffer.PayloadBuffer[0].m_Address + 4 + View * 0xD8, 212);
View++;
}
fclose(pFile);
}
}
else
@ -865,15 +862,10 @@ u32 CWII_IPC_HLE_Device_es::ES_DIVerify(u8* _pTMD, u32 _sz)
File::CreateFullPath(dataPath);
if(!File::Exists(tmdPath))
{
FILE* _pTMDFile = fopen(tmdPath.c_str(), "wb");
if (_pTMDFile)
{
if (fwrite(_pTMD, _sz, 1, _pTMDFile) != 1)
ERROR_LOG(WII_IPC_ES, "DIVerify failed to write disc tmd to nand");
fclose(_pTMDFile);
}
File::IOFile _pTMDFile(tmdPath, "wb");
if (!_pTMDFile.WriteBytes(_pTMD, _sz))
ERROR_LOG(WII_IPC_ES, "DIVerify failed to write disc tmd to nand");
}
DiscIO::cUIDsys::AccessInstance().AddTitle(tmdTitleID);
return 0;
}

View File

@ -169,11 +169,10 @@ CWII_IPC_HLE_Device_net_ncd_manage::CWII_IPC_HLE_Device_net_ncd_manage(u32 _Devi
: IWII_IPC_HLE_Device(_DeviceID, _rDeviceName)
{
// store network configuration
std::string filename(File::GetUserPath(D_WIIUSER_IDX));
filename.append("shared2/sys/net/02/config.dat");
FILE *file = fopen(filename.c_str(), "rb");
if (file == NULL || fread(&m_Ifconfig, sizeof(network_config_t), 1, file) != 1)
const std::string filename(File::GetUserPath(D_WIIUSER_IDX) + "shared2/sys/net/02/config.dat");
File::IOFile file(filename, "rb");
if (!file.ReadBytes(&m_Ifconfig, 1))
{
INFO_LOG(WII_IPC_NET, "NET_NCD_MANAGE: Failed to load /shared2/sys/net/02/config.dat, using dummy configuration");
@ -195,10 +194,6 @@ CWII_IPC_HLE_Device_net_ncd_manage::CWII_IPC_HLE_Device_net_ncd_manage(u32 _Devi
m_Ifconfig.connection[0].gateway[2] = 1;
m_Ifconfig.connection[0].gateway[3] = 2;
}
if (file)
{
fclose(file);
}
}
CWII_IPC_HLE_Device_net_ncd_manage::~CWII_IPC_HLE_Device_net_ncd_manage()

View File

@ -35,15 +35,6 @@ CWII_IPC_HLE_Device_sdio_slot0::CWII_IPC_HLE_Device_sdio_slot0(u32 _DeviceID, co
, m_Card(NULL)
{}
CWII_IPC_HLE_Device_sdio_slot0::~CWII_IPC_HLE_Device_sdio_slot0()
{
if(m_Card)
{
fclose(m_Card);
m_Card = NULL;
}
}
void CWII_IPC_HLE_Device_sdio_slot0::EventNotify()
{
if ((SConfig::GetInstance().m_WiiSDCard && m_event.type == EVENT_INSERT) ||
@ -60,17 +51,17 @@ bool CWII_IPC_HLE_Device_sdio_slot0::Open(u32 _CommandAddress, u32 _Mode)
{
INFO_LOG(WII_IPC_SD, "Open");
std::string filename = File::GetUserPath(D_WIIUSER_IDX) + "sd.raw";
m_Card = fopen(filename.c_str(), "r+b");
if(!m_Card)
const std::string filename = File::GetUserPath(D_WIIUSER_IDX) + "sd.raw";
m_Card.Open(filename, "r+b");
if (!m_Card)
{
WARN_LOG(WII_IPC_SD, "Failed to open SD Card image, trying to create a new 128MB image...");
if (SDCardCreate(128, filename.c_str()))
{
WARN_LOG(WII_IPC_SD, "Successfully created %s", filename.c_str());
m_Card = fopen(filename.c_str(), "r+b");
m_Card.Open(filename, "r+b");
}
if(!m_Card)
if (!m_Card)
{
ERROR_LOG(WII_IPC_SD, "Could not open SD Card image or create a new one, are you running from a read-only directory?");
}
@ -85,11 +76,7 @@ bool CWII_IPC_HLE_Device_sdio_slot0::Close(u32 _CommandAddress, bool _bForce)
{
INFO_LOG(WII_IPC_SD, "Close");
if(m_Card)
{
fclose(m_Card);
m_Card = NULL;
}
m_Card.Close();
m_BlockLength = 0;
m_BusWidth = 0;
@ -377,13 +364,12 @@ u32 CWII_IPC_HLE_Device_sdio_slot0::ExecuteCommand(u32 _BufferIn, u32 _BufferInS
{
u32 size = req.bsize * req.blocks;
if (fseeko(m_Card, req.arg, SEEK_SET) != 0)
ERROR_LOG(WII_IPC_SD, "fseeko failed WTF");
if (!m_Card.Seek(req.arg, SEEK_SET))
ERROR_LOG(WII_IPC_SD, "Seek failed WTF");
u8* buffer = new u8[size];
u8* const buffer = new u8[size];
size_t nRead = fread(buffer, req.bsize, req.blocks, m_Card);
if (nRead == req.blocks)
if (m_Card.ReadBytes(buffer, req.bsize * req.blocks))
{
u32 i;
for (i = 0; i < size; ++i)
@ -394,10 +380,8 @@ u32 CWII_IPC_HLE_Device_sdio_slot0::ExecuteCommand(u32 _BufferIn, u32 _BufferInS
}
else
{
ERROR_LOG(WII_IPC_SD, "Read Failed - "
"read %lx, error %i, eof? %i",
(unsigned long)nRead,
ferror(m_Card), feof(m_Card));
ERROR_LOG(WII_IPC_SD, "Read Failed - error: %i, eof: %i",
ferror(m_Card.GetHandle()), feof(m_Card.GetHandle()));
ret = RET_FAIL;
}
@ -418,7 +402,7 @@ u32 CWII_IPC_HLE_Device_sdio_slot0::ExecuteCommand(u32 _BufferIn, u32 _BufferInS
{
u32 size = req.bsize * req.blocks;
if (fseeko(m_Card, req.arg, SEEK_SET) != 0)
if (!m_Card.Seek(req.arg, SEEK_SET))
ERROR_LOG(WII_IPC_SD, "fseeko failed WTF");
u8* buffer = new u8[size];
@ -428,13 +412,10 @@ u32 CWII_IPC_HLE_Device_sdio_slot0::ExecuteCommand(u32 _BufferIn, u32 _BufferInS
buffer[i] = Memory::Read_U8(req.addr++);
}
size_t nWritten = fwrite(buffer, req.bsize, req.blocks, m_Card);
if (nWritten != req.blocks)
if (!m_Card.WriteBytes(buffer, req.bsize * req.blocks))
{
ERROR_LOG(WII_IPC_SD, "Write Failed - "
"wrote %lx, error %i, eof? %i",
(unsigned long)nWritten,
ferror(m_Card), feof(m_Card));
ERROR_LOG(WII_IPC_SD, "Write Failed - error: %i, eof: %i",
ferror(m_Card.GetHandle()), feof(m_Card.GetHandle()));
ret = RET_FAIL;
}

View File

@ -28,8 +28,6 @@ public:
CWII_IPC_HLE_Device_sdio_slot0(u32 _DeviceID, const std::string& _rDeviceName);
virtual ~CWII_IPC_HLE_Device_sdio_slot0();
bool Open(u32 _CommandAddress, u32 _Mode);
bool Close(u32 _CommandAddress, bool _bForce);
bool IOCtl(u32 _CommandAddress);
@ -134,7 +132,7 @@ private:
u32 m_BlockLength;
u32 m_BusWidth;
FILE* m_Card;
File::IOFile m_Card;
u32 ExecuteCommand(u32 BufferIn, u32 BufferInSize,
u32 BufferIn2, u32 BufferInSize2,

View File

@ -50,7 +50,7 @@ unsigned int g_framesToSkip = 0, g_frameSkipCounter = 0;
int g_numPads = 0;
ControllerState g_padState;
FILE *g_recordfd = NULL;
File::IOFile g_recordfd;
u64 g_frameCounter = 0, g_lagCounter = 0, g_totalFrameCount = 0;
bool g_bRecordingFromSaveState = false;
@ -209,15 +209,15 @@ bool BeginRecordingInput(int controllers)
g_bRecordingFromSaveState = true;
}
g_recordfd = fopen(g_recordFile.c_str(), "wb");
if(!g_recordfd) {
if (!g_recordfd.Open(g_recordFile, "wb"))
{
PanicAlertT("Error opening file %s for recording", g_recordFile.c_str());
return false;
}
// Write initial empty header
DTMHeader dummy;
fwrite(&dummy, sizeof(DTMHeader), 1, g_recordfd);
g_recordfd.WriteArray(&dummy, 1);
g_numPads = controllers;
@ -328,7 +328,7 @@ void RecordInput(SPADStatus *PadStatus, int controllerID)
g_padState.CStickX = PadStatus->substickX;
g_padState.CStickY = PadStatus->substickY;
fwrite(&g_padState, sizeof(ControllerState), 1, g_recordfd);
g_recordfd.WriteArray(&g_padState, 1);
SetInputDisplayString(g_padState, controllerID);
}
@ -338,8 +338,8 @@ void RecordWiimote(int wiimote, u8 *data, s8 size)
if(!IsRecordingInput() || !IsUsingWiimote(wiimote))
return;
fwrite(&size, 1, 1, g_recordfd);
fwrite(data, 1, size, g_recordfd);
g_recordfd.WriteArray(&size, 1);
g_recordfd.WriteArray(data, 1);
}
bool PlayInput(const char *filename)
@ -355,11 +355,10 @@ bool PlayInput(const char *filename)
File::Delete(g_recordFile);
File::Copy(filename, g_recordFile);
g_recordfd = fopen(g_recordFile.c_str(), "r+b");
if(!g_recordfd)
if (!g_recordfd.Open(g_recordFile, "r+b"))
return false;
fread(&header, sizeof(DTMHeader), 1, g_recordfd);
g_recordfd.ReadArray(&header, 1);
if(header.filetype[0] != 'D' || header.filetype[1] != 'T' || header.filetype[2] != 'M' || header.filetype[3] != 0x1A) {
PanicAlertT("Invalid recording file");
@ -399,19 +398,18 @@ bool PlayInput(const char *filename)
return true;
cleanup:
fclose(g_recordfd);
g_recordfd = NULL;
g_recordfd.Close();
return false;
}
void LoadInput(const char *filename)
{
FILE *t_record = fopen(filename, "rb");
File::IOFile t_record(filename, "rb");
DTMHeader header;
fread(&header, sizeof(DTMHeader), 1, t_record);
fclose(t_record);
t_record.ReadArray(&header, 1);
t_record.Close();
if(header.filetype[0] != 'D' || header.filetype[1] != 'T' || header.filetype[2] != 'M' || header.filetype[3] != 0x1A)
{
@ -433,14 +431,13 @@ void LoadInput(const char *filename)
if (Core::g_CoreStartupParameter.bWii)
ChangeWiiPads();
if (g_recordfd)
fclose(g_recordfd);
g_recordfd.Close();
File::Delete(g_recordFile);
File::Copy(filename, g_recordFile);
g_recordfd = fopen(g_recordFile.c_str(), "r+b");
fseeko(g_recordfd, 0, SEEK_END);
g_recordfd.Open(g_recordFile, "r+b");
g_recordfd.Seek(0, SEEK_END);
g_rerecords++;
@ -453,11 +450,16 @@ void PlayController(SPADStatus *PadStatus, int controllerID)
{
// Correct playback is entirely dependent on the emulator polling the controllers
// in the same order done during recording
if(!IsPlayingInput() || !IsUsingPad(controllerID))
if (!IsPlayingInput() || !IsUsingPad(controllerID))
return;
memset(PadStatus, 0, sizeof(SPADStatus));
fread(&g_padState, sizeof(ControllerState), 1, g_recordfd);
if (!g_recordfd.ReadArray(&g_padState, 1))
{
Core::DisplayMessage("Movie End", 2000);
EndPlayInput(!g_bReadOnly);
}
PadStatus->triggerLeft = g_padState.TriggerL;
PadStatus->triggerRight = g_padState.TriggerR;
@ -525,7 +527,7 @@ void PlayController(SPADStatus *PadStatus, int controllerID)
SetInputDisplayString(g_padState, controllerID);
if(feof(g_recordfd) || g_frameCounter >= g_totalFrameCount)
if (g_frameCounter >= g_totalFrameCount)
{
Core::DisplayMessage("Movie End", 2000);
EndPlayInput(!g_bReadOnly);
@ -538,12 +540,11 @@ bool PlayWiimote(int wiimote, u8 *data, s8 &size)
if(!IsPlayingInput() || !IsUsingWiimote(wiimote))
return false;
fread(&count, 1, 1, g_recordfd);
g_recordfd.ReadArray(&count, 1);
size = (count > size) ? size : count;
fread(data, 1, size, g_recordfd);
// TODO: merge this with the above so that there's no duplicate code
if(feof(g_recordfd) || g_frameCounter >= g_totalFrameCount)
if (g_frameCounter >= g_totalFrameCount || !g_recordfd.ReadBytes(data, size))
{
Core::DisplayMessage("Movie End", 2000);
EndPlayInput(!g_bReadOnly);
@ -559,19 +560,17 @@ void EndPlayInput(bool cont)
// from the exact point in playback we're at now
// if playback ends before the end of the file.
SaveRecording(g_tmpRecordFile.c_str());
fclose(g_recordfd);
g_recordfd.Close();
File::Delete(g_recordFile);
File::Copy(g_tmpRecordFile, g_recordFile);
g_recordfd = fopen(g_recordFile.c_str(), "r+b");
fseeko(g_recordfd, 0, SEEK_END);
g_recordfd.Open(g_recordFile, "r+b");
g_recordfd.Seek(0, SEEK_END);
g_playMode = MODE_RECORDING;
Core::DisplayMessage("Resuming movie recording", 2000);
}
else
{
if (g_recordfd)
fclose(g_recordfd);
g_recordfd = NULL;
g_recordfd.Close();
g_numPads = g_rerecords = 0;
g_totalFrameCount = g_frameCounter = g_lagCounter = 0;
g_playMode = MODE_NONE;
@ -580,14 +579,14 @@ void EndPlayInput(bool cont)
void SaveRecording(const char *filename)
{
off_t size = ftello(g_recordfd);
const off_t size = g_recordfd.Tell();
// NOTE: Eventually this will not happen in
// read-only mode, but we need a way for the save state to
// store the current point in the file first.
// if (!g_bReadOnly)
{
rewind(g_recordfd);
rewind(g_recordfd.GetHandle());
// Create the real header now and write it
DTMHeader header;
@ -609,11 +608,11 @@ void SaveRecording(const char *filename)
// header.videoBackend;
// header.audioEmulator;
fwrite(&header, sizeof(DTMHeader), 1, g_recordfd);
g_recordfd.WriteArray(&header, 1);
}
bool success = false;
fclose(g_recordfd);
g_recordfd.Close();
File::Delete(filename);
success = File::Copy(g_recordFile, filename);
@ -649,7 +648,7 @@ void SaveRecording(const char *filename)
else
Core::DisplayMessage(StringFromFormat("Failed to save %s", filename).c_str(), 2000);
g_recordfd = fopen(g_recordFile.c_str(), "r+b");
fseeko(g_recordfd, size, SEEK_SET);
g_recordfd.Open(g_recordFile, "r+b");
g_recordfd.Seek(size, SEEK_SET);
}
};

View File

@ -19,6 +19,7 @@
#define __FRAME_H
#include "Common.h"
#include "FileUtil.h"
#include "../../InputCommon/Src/GCPadStatus.h"
#include <string>
@ -59,7 +60,7 @@ extern unsigned int g_framesToSkip, g_frameSkipCounter;
extern int g_numPads;
extern ControllerState *g_padStates;
extern char g_playingFile[256];
extern FILE *g_recordfd;
extern File::IOFile g_recordfd;
extern std::string g_recordFile;
extern u64 g_frameCounter, g_lagCounter;

View File

@ -269,19 +269,21 @@ static std::map<u32, int> been_here;
static void ImHere()
{
static FILE *f = 0;
if (ImHereLog) {
static File::IOFile f;
if (ImHereLog)
{
if (!f)
{
#ifdef _M_X64
f = fopen("log64.txt", "w");
f.Open("log64.txt", "w");
#else
f = fopen("log32.txt", "w");
f.Open("log32.txt", "w");
#endif
}
fprintf(f, "%08x\n", PC);
fprintf(f.GetHandle(), "%08x\n", PC);
}
if (been_here.find(PC) != been_here.end()) {
if (been_here.find(PC) != been_here.end())
{
been_here.find(PC)->second++;
if ((been_here.find(PC)->second) & 1023)
return;

View File

@ -1225,20 +1225,18 @@ InstLoc IRBuilder::isNeg(InstLoc I) const {
}
// TODO: Move the following code to a separated file.
struct Writer {
FILE* file;
Writer() : file(NULL) {
struct Writer
{
File::IOFile file;
Writer() : file(NULL)
{
char buffer[1024];
sprintf(buffer, "JitIL_IR_%d.txt", (int)time(NULL));
file = fopen(buffer, "w");
setvbuf(file, NULL, _IOFBF, 1024 * 1024);
}
virtual ~Writer() {
if (file) {
fclose(file);
file = NULL;
}
file.Open(buffer, "w");
setvbuf(file.GetHandle(), NULL, _IOFBF, 1024 * 1024);
}
virtual ~Writer() {}
};
static std::auto_ptr<Writer> writer;
@ -1295,7 +1293,7 @@ void IRBuilder::WriteToFile(u64 codeHash) {
writer = std::auto_ptr<Writer>(new Writer);
}
FILE* file = writer->file;
FILE* const file = writer->file.GetHandle();
fprintf(file, "\ncode hash:%016llx\n", codeHash);
const InstLoc lastCurReadPtr = curReadPtr;

View File

@ -227,19 +227,17 @@ namespace JitILProfiler
{
char buffer[1024];
sprintf(buffer, "JitIL_profiling_%d.csv", (int)time(NULL));
FILE* file = fopen(buffer, "w");
setvbuf(file, NULL, _IOFBF, 1024 * 1024);
fprintf(file, "code hash,total elapsed,number of calls,elapsed per call\n");
File::IOFile file(buffer, "w");
setvbuf(file.GetHandle(), NULL, _IOFBF, 1024 * 1024);
fprintf(file.GetHandle(), "code hash,total elapsed,number of calls,elapsed per call\n");
for (std::vector<Block>::iterator it = blocks.begin(), itEnd = blocks.end(); it != itEnd; ++it)
{
const u64 codeHash = it->codeHash;
const u64 totalElapsed = it->totalElapsed;
const u64 numberOfCalls = it->numberOfCalls;
const double elapsedPerCall = totalElapsed / (double)numberOfCalls;
fprintf(file, "%016llx,%lld,%lld,%f\n", codeHash, totalElapsed, numberOfCalls, elapsedPerCall);
fprintf(file.GetHandle(), "%016llx,%lld,%lld,%f\n", codeHash, totalElapsed, numberOfCalls, elapsedPerCall);
}
fclose(file);
file = NULL;
}
};
std::auto_ptr<JitILProfilerFinalizer> finalizer;
@ -369,18 +367,20 @@ static std::map<u32, int> been_here;
static void ImHere()
{
static FILE *f = 0;
static File::IOFile f;
if (ImHereLog)
{
if (!f)
{
#ifdef _M_X64
f = fopen("log64.txt", "w");
f.Open("log64.txt", "w");
#else
f = fopen("log32.txt", "w");
f.Open("log32.txt", "w");
#endif
}
fprintf(f, "%08x r0: %08x r5: %08x r6: %08x\n", PC, PowerPC::ppcState.gpr[0], PowerPC::ppcState.gpr[5], PowerPC::ppcState.gpr[6]); fflush(f);
fprintf(f.GetHandle(), "%08x r0: %08x r5: %08x r6: %08x\n", PC, PowerPC::ppcState.gpr[0],
PowerPC::ppcState.gpr[5], PowerPC::ppcState.gpr[6]);
f.Flush();
}
if (been_here.find(PC) != been_here.end()) {
been_here.find(PC)->second++;

View File

@ -15,12 +15,13 @@
// Official SVN repository and contact information can be found at
// http://code.google.com/p/dolphin-emu/
#include "Common.h"
#include <map>
#include <string>
#include <vector>
#include "Common.h"
#include "FileUtil.h"
#include "../HW/Memmap.h"
#include "../PowerPC/PowerPC.h"
#include "../Host.h"
@ -206,19 +207,21 @@ void PPCSymbolDB::LogFunctionCall(u32 addr)
// produced by SaveSymbolMap below.
bool PPCSymbolDB::LoadMap(const char *filename)
{
FILE *f = fopen(filename, "r");
File::IOFile f(filename, "r");
if (!f)
return false;
bool started = false;
while (!feof(f))
char line[512];
while (fgets(line, 512, f.GetHandle()))
{
char line[512], temp[256];
fgets(line, 511, f);
if (strlen(line) < 4)
continue;
char temp[256];
sscanf(line, "%s", temp);
if (strcmp(temp, "UNUSED")==0) continue;
if (strcmp(temp, ".text")==0) {started = true; continue;};
if (strcmp(temp, ".init")==0) {started = true; continue;};
@ -261,7 +264,6 @@ bool PPCSymbolDB::LoadMap(const char *filename)
}
}
fclose(f);
Index();
return true;
}
@ -287,14 +289,14 @@ bool PPCSymbolDB::SaveMap(const char *filename, bool WithCodes) const
if (WithCodes) Host_UpdateStatusBar("Saving code, please stand by ...");
// Make a file
FILE *f = fopen(mapFile.c_str(), "w");
if (!f) return false;
File::IOFile f(mapFile, "w");
if (!f)
return false;
// --------------------------------------------------------------------
// Walk through every code row
// -------------------------
fprintf(f, ".text\n"); // Write ".text" at the top
fprintf(f.GetHandle(), ".text\n"); // Write ".text" at the top
XFuncMap::const_iterator itr = functions.begin();
u32 LastAddress = 0x80004000;
std::string LastSymbolName;
@ -304,7 +306,7 @@ bool PPCSymbolDB::SaveMap(const char *filename, bool WithCodes) const
const Symbol &rSymbol = itr->second;
if (!WithCodes)
{
fprintf(f,"%08x %08x %08x %i %s\n", rSymbol.address, rSymbol.size, rSymbol.address,
fprintf(f.GetHandle(),"%08x %08x %08x %i %s\n", rSymbol.address, rSymbol.size, rSymbol.address,
0, rSymbol.name.c_str());
++itr;
}
@ -340,15 +342,15 @@ bool PPCSymbolDB::SaveMap(const char *filename, bool WithCodes) const
int Address = LastAddress + i;
char disasm[256];
debugger->disasm(Address, disasm, 256);
fprintf(f,"%08x %i %20s %s\n", Address, 0, TempSym.c_str(), disasm);
fprintf(f.GetHandle(),"%08x %i %20s %s\n", Address, 0, TempSym.c_str(), disasm);
}
// Write a blank line after each block
fprintf(f, "\n");
}
fprintf(f.GetHandle(), "\n");
}
}
// ---------------
Host_UpdateStatusBar(StringFromFormat("Saved %s", mapFile.c_str()).c_str());
fclose(f);
return true;
Host_UpdateStatusBar(StringFromFormat("Saved %s", mapFile.c_str()).c_str());
return true;
}
// ===========

View File

@ -233,31 +233,34 @@ void PrintInstructionRunCounts()
void LogCompiledInstructions()
{
static int time = 0;
FILE *f = fopen(StringFromFormat("%sinst_log%i.txt", File::GetUserPath(D_LOGS_IDX).c_str(), time).c_str(), "w");
static unsigned int time = 0;
File::IOFile f(StringFromFormat("%sinst_log%i.txt", File::GetUserPath(D_LOGS_IDX).c_str(), time), "w");
for (int i = 0; i < m_numInstructions; i++)
{
if (m_allInstructions[i]->compileCount > 0) {
fprintf(f, "%s\t%i\t%i\t%08x\n", m_allInstructions[i]->opname, m_allInstructions[i]->compileCount, m_allInstructions[i]->runCount, m_allInstructions[i]->lastUse);
fprintf(f.GetHandle(), "%s\t%i\t%i\t%08x\n", m_allInstructions[i]->opname,
m_allInstructions[i]->compileCount, m_allInstructions[i]->runCount, m_allInstructions[i]->lastUse);
}
}
fclose(f);
f = fopen(StringFromFormat("%sinst_not%i.txt", File::GetUserPath(D_LOGS_IDX).c_str(), time).c_str(), "w");
f.Open(StringFromFormat("%sinst_not%i.txt", File::GetUserPath(D_LOGS_IDX).c_str(), time), "w");
for (int i = 0; i < m_numInstructions; i++)
{
if (m_allInstructions[i]->compileCount == 0) {
fprintf(f, "%s\t%i\t%i\n", m_allInstructions[i]->opname, m_allInstructions[i]->compileCount, m_allInstructions[i]->runCount);
fprintf(f.GetHandle(), "%s\t%i\t%i\n", m_allInstructions[i]->opname,
m_allInstructions[i]->compileCount, m_allInstructions[i]->runCount);
}
}
fclose(f);
#ifdef OPLOG
f = fopen(StringFromFormat("%s" OP_TO_LOG "_at.txt", File::GetUserPath(D_LOGS_IDX).c_str(), time).c_str(), "w");
f.Open(StringFromFormat("%s" OP_TO_LOG "_at.txt", File::GetUserPath(D_LOGS_IDX).c_str(), time), "w");
for (size_t i = 0; i < rsplocations.size(); i++) {
fprintf(f, OP_TO_LOG ": %08x\n", rsplocations[i]);
fprintf(f.GetHandle(), OP_TO_LOG ": %08x\n", rsplocations[i]);
}
fclose(f);
#endif
time++;
++time;
}
} // namespace

View File

@ -25,6 +25,7 @@
#endif
#include "PPCSymbolDB.h"
#include "FileUtil.h"
namespace Profiler
{
@ -70,13 +71,13 @@ void WriteProfileResults(const char *filename)
}
sort(stats.begin(), stats.end());
FILE *f = fopen(filename, "w");
File::IOFile f(filename, "w");
if (!f)
{
PanicAlert("failed to open %s", filename);
return;
}
fprintf(f, "origAddr\tblkName\tcost\ttimeCost\tpercent\ttimePercent\tOvAllinBlkTime(ms)\tblkCodeSize\n");
fprintf(f.GetHandle(), "origAddr\tblkName\tcost\ttimeCost\tpercent\ttimePercent\tOvAllinBlkTime(ms)\tblkCodeSize\n");
for (unsigned int i = 0; i < stats.size(); i++)
{
const JitBlock *block = jit->GetBlockCache()->GetBlock(stats[i].blockNum);
@ -86,17 +87,16 @@ void WriteProfileResults(const char *filename)
double percent = 100.0 * (double)stats[i].cost / (double)cost_sum;
#ifdef _WIN32
double timePercent = 100.0 * (double)block->ticCounter / (double)timecost_sum;
fprintf(f, "%08x\t%s\t%llu\t%llu\t%.2lf\t%llf\t%lf\t%i\n",
fprintf(f.GetHandle(), "%08x\t%s\t%llu\t%llu\t%.2lf\t%llf\t%lf\t%i\n",
block->originalAddress, name.c_str(), stats[i].cost,
block->ticCounter, percent, timePercent,
(double)block->ticCounter*1000.0/(double)countsPerSec, block->codeSize);
#else
fprintf(f, "%08x\t%s\t%llu\t???\t%.2lf\t???\t???\t%i\n",
fprintf(f.GetHandle(), "%08x\t%s\t%llu\t???\t%.2lf\t???\t???\t%i\n",
block->originalAddress, name.c_str(), stats[i].cost, percent, block->codeSize);
#endif
}
}
fclose(f);
}
} // namespace

View File

@ -18,6 +18,7 @@
#include "Common.h"
#include "PPCAnalyst.h"
#include "../HW/Memmap.h"
#include "FileUtil.h"
#include "SignatureDB.h"
#include "PPCSymbolDB.h"
@ -36,17 +37,17 @@ struct FuncDesc
bool SignatureDB::Load(const char *filename)
{
FILE *f = fopen(filename, "rb");
File::IOFile f(filename, "rb");
if (!f)
return false;
u32 fcount = 0;
fread(&fcount, 4, 1, f);
f.ReadArray(&fcount, 1);
for (size_t i = 0; i < fcount; i++)
{
FuncDesc temp;
memset(&temp, 0, sizeof(temp));
fread(&temp, sizeof(temp), 1, f);
f.ReadArray(&temp, 1);
temp.name[sizeof(temp.name)-1] = 0;
DBFunc dbf;
@ -54,20 +55,20 @@ bool SignatureDB::Load(const char *filename)
dbf.size = temp.size;
database[temp.checkSum] = dbf;
}
fclose(f);
return true;
}
bool SignatureDB::Save(const char *filename)
{
FILE *f = fopen(filename,"wb");
File::IOFile f(filename, "wb");
if (!f)
{
ERROR_LOG(OSHLE, "Database save failed");
return false;
}
int fcount = (int)database.size();
fwrite(&fcount, 4, 1, f);
u32 fcount = (u32)database.size();
f.WriteArray(&fcount, 1);
for (FuncDB::const_iterator iter = database.begin(); iter != database.end(); ++iter)
{
FuncDesc temp;
@ -75,9 +76,9 @@ bool SignatureDB::Save(const char *filename)
temp.checkSum = iter->first;
temp.size = iter->second.size;
strncpy(temp.name, iter->second.name.c_str(), 127);
fwrite(&temp, sizeof(temp), 1, f);
f.WriteArray(&temp, 1);
}
fclose(f);
INFO_LOG(OSHLE, "Database save successful");
return true;
}

View File

@ -188,8 +188,8 @@ void CompressAndDumpState(saveStruct* saveArg)
Core::DisplayMessage("Failed to move previous state to state undo backup", 1000);
}
FILE *f = fopen(filename.c_str(), "wb");
if (f == NULL)
File::IOFile f(filename, "wb");
if (!f)
{
Core::DisplayMessage("Could not save state", 2000);
delete[] buffer;
@ -200,7 +200,7 @@ void CompressAndDumpState(saveStruct* saveArg)
memcpy(header.gameID, SConfig::GetInstance().m_LocalCoreStartupParameter.GetUniqueID().c_str(), 6);
header.sz = bCompressed ? sz : 0;
fwrite(&header, sizeof(state_header), 1, f);
f.WriteArray(&header, 1);
if (bCompressed)
{
lzo_uint cur_len = 0;
@ -217,8 +217,8 @@ void CompressAndDumpState(saveStruct* saveArg)
PanicAlertT("Internal LZO Error - compression failed");
// The size of the data to write is 'out_len'
fwrite(&out_len, sizeof(int), 1, f);
fwrite(out, out_len, 1, f);
f.WriteArray(&out_len, 1);
f.WriteBytes(out, out_len);
if (cur_len != IN_LEN)
break;
@ -227,10 +227,9 @@ void CompressAndDumpState(saveStruct* saveArg)
}
else
{
fwrite(buffer, sz, 1, f);
f.WriteBytes(buffer, sz);
}
fclose(f);
delete[] buffer;
Core::DisplayMessage(StringFromFormat("Saved State to %s",
@ -298,7 +297,7 @@ void LoadStateCallback(u64 userdata, int cyclesLate)
SaveBufferStateCallback(userdata, cyclesLate);
}
FILE *f = fopen(cur_filename.c_str(), "rb");
File::IOFile f(cur_filename, "rb");
if (!f)
{
Core::DisplayMessage("State not found", 2000);
@ -311,7 +310,7 @@ void LoadStateCallback(u64 userdata, int cyclesLate)
state_header header;
size_t sz;
fread(&header, sizeof(state_header), 1, f);
f.ReadArray(&header, 1);
if (memcmp(SConfig::GetInstance().m_LocalCoreStartupParameter.GetUniqueID().c_str(), header.gameID, 6))
{
@ -320,7 +319,6 @@ void LoadStateCallback(u64 userdata, int cyclesLate)
Core::DisplayMessage(StringFromFormat("State belongs to a different game (ID %s)",
gameID), 2000);
fclose(f);
// Resume the clock
CCPU::EnableStepping(false);
return;
@ -345,18 +343,17 @@ void LoadStateCallback(u64 userdata, int cyclesLate)
{
lzo_uint cur_len = 0; // number of bytes to read
lzo_uint new_len = 0; // number of bytes to write
if (fread(&cur_len, 1, sizeof(int), f) == 0)
if (!f.ReadArray(&cur_len, 1))
break;
if (feof(f))
break; // don't know if this happens.
fread(out, 1, cur_len, f);
f.ReadBytes(out, cur_len);
int res = lzo1x_decompress(out, cur_len, (buffer + i), &new_len, NULL);
if (res != LZO_E_OK)
{
// This doesn't seem to happen anymore.
PanicAlertT("Internal LZO Error - decompression failed (%d) (%li, %li) \n"
"Try loading the state again", res, i, new_len);
fclose(f);
delete[] buffer;
// Resume the clock
CCPU::EnableStepping(false);
@ -368,14 +365,13 @@ void LoadStateCallback(u64 userdata, int cyclesLate)
}
else
{
sz = (int)(File::GetSize(f) - sizeof(state_header));
sz = (int)(f.GetSize() - sizeof(state_header));
buffer = new u8[sz];
int x;
if ((x = (int)fread(buffer, 1, sz, f)) != (int)sz)
PanicAlert("wtf? %d %lu", x, (unsigned long)sz);
if (!f.ReadBytes(buffer, sz))
PanicAlert("wtf? reading bytes: %lu", (unsigned long)sz);
}
fclose(f);
f.Close();
u8 *ptr = buffer;
PointerWrap p(&ptr, PointerWrap::MODE_READ);
@ -405,7 +401,7 @@ void VerifyStateCallback(u64 userdata, int cyclesLate)
State_Flush();
FILE *f = fopen(cur_filename.c_str(), "rb");
File::IOFile f(cur_filename, "rb");
if (!f)
{
Core::DisplayMessage("State not found", 2000);
@ -416,7 +412,7 @@ void VerifyStateCallback(u64 userdata, int cyclesLate)
state_header header;
size_t sz;
fread(&header, sizeof(state_header), 1, f);
f.ReadArray(&header, 1);
if (memcmp(SConfig::GetInstance().m_LocalCoreStartupParameter.GetUniqueID().c_str(), header.gameID, 6))
{
@ -425,8 +421,6 @@ void VerifyStateCallback(u64 userdata, int cyclesLate)
Core::DisplayMessage(StringFromFormat("State belongs to a different game (ID %s)",
gameID), 2000);
fclose(f);
return;
}
@ -446,18 +440,17 @@ void VerifyStateCallback(u64 userdata, int cyclesLate)
{
lzo_uint cur_len = 0;
lzo_uint new_len = 0;
if (fread(&cur_len, 1, sizeof(int), f) == 0)
if (!f.ReadArray(&cur_len, 1))
break;
if (feof(f))
break; // don't know if this happens.
fread(out, 1, cur_len, f);
f.ReadBytes(out, cur_len);
int res = lzo1x_decompress(out, cur_len, (buffer + i), &new_len, NULL);
if (res != LZO_E_OK)
{
// This doesn't seem to happen anymore.
PanicAlertT("Internal LZO Error - decompression failed (%d) (%ld, %ld) \n"
"Try verifying the state again", res, i, new_len);
fclose(f);
delete [] buffer;
return;
}
@ -468,14 +461,12 @@ void VerifyStateCallback(u64 userdata, int cyclesLate)
}
else
{
sz = (int)(File::GetSize(f) - sizeof(int));
sz = (int)(f.GetSize() - sizeof(int));
buffer = new u8[sz];
int x;
if ((x = (int)fread(buffer, 1, sz, f)) != (int)sz)
PanicAlert("wtf? %d %lu", x, (unsigned long)sz);
}
fclose(f);
if (!f.ReadBytes(buffer, sz))
PanicAlert("wtf? failed to read bytes: %lu", (unsigned long)sz);
}
u8 *ptr = buffer;
PointerWrap p(&ptr, PointerWrap::MODE_VERIFY);

View File

@ -15,11 +15,11 @@
// Official SVN repository and contact information can be found at
// http://code.google.com/p/dolphin-emu/
#include <stdio.h>
#include <stdlib.h>
#include "Common.h"
#include "Tracer.h"
#include "FileUtil.h"
#include "Host.h"
@ -27,7 +27,7 @@
namespace Core {
FILE *tracefile;
File::IOFile tracefile;
bool bReadTrace = false;
bool bWriteTrace = false;
@ -36,13 +36,13 @@ void StartTrace(bool write)
{
if (write)
{
tracefile = fopen("L:\\trace.dat","wb");
tracefile.Open("L:\\trace.dat", "wb");
bReadTrace = false;
bWriteTrace = true;
}
else
{
tracefile = fopen("L:\\trace.dat","rb");
tracefile.Open("L:\\trace.dat", "rb");
bReadTrace = true;
bWriteTrace = false;
}
@ -50,11 +50,7 @@ void StartTrace(bool write)
void StopTrace()
{
if (tracefile)
{
fclose(tracefile);
tracefile = NULL;
}
tracefile.Close();
}
static int stateSize = 32*4;// + 32*16 + 6*4;
@ -63,18 +59,16 @@ int SyncTrace()
{
if (bWriteTrace)
{
fwrite(&PowerPC::ppcState, stateSize, 1, tracefile);
fflush(tracefile);
tracefile.WriteBytes(&PowerPC::ppcState, stateSize);
tracefile.Flush();
return 1;
}
if (bReadTrace)
{
PowerPC::PowerPCState state;
if (feof(tracefile))
{
if (!tracefile.ReadBytes(&state, stateSize))
return 1;
}
fread(&state, stateSize, 1, tracefile);
bool difference = false;
for (int i=0; i<32; i++)
{