Everything: Remove a **lot** of wx, and px nonsense

- common has no wx left except for Path.
 - pcsx2core only has it in a few places (memory cards and path related
   stuff).
This commit is contained in:
Connor McLaughlin 2022-05-18 23:27:23 +10:00 committed by refractionpcsx2
parent c07c942659
commit 893b3c629d
234 changed files with 1952 additions and 2190 deletions

View File

@ -33,25 +33,6 @@
#define pxUSE_SECURE_MALLOC 0 #define pxUSE_SECURE_MALLOC 0
#endif #endif
//////////////////////////////////////////////////////////////////////////////////////////
// Safe deallocation macros -- checks pointer validity (non-null) when needed, and sets
// pointer to null after deallocation.
#define safe_delete(ptr) \
((void)(delete (ptr)), (ptr) = NULL)
#define safe_delete_array(ptr) \
((void)(delete[](ptr)), (ptr) = NULL)
// No checks for NULL -- wxWidgets says it's safe to skip NULL checks and it runs on
// just about every compiler and libc implementation of any recentness.
#define safe_free(ptr) \
((void)(free(ptr), !!0), (ptr) = NULL)
//((void) (( ( (ptr) != NULL ) && (free( ptr ), !!0) ), (ptr) = NULL))
#define safe_fclose(ptr) \
((void)((((ptr) != NULL) && (fclose(ptr), !!0)), (ptr) = NULL))
// Implementation note: all known implementations of _aligned_free check the pointer for // Implementation note: all known implementations of _aligned_free check the pointer for
// NULL status (our implementation under GCC, and microsoft's under MSVC), so no need to // NULL status (our implementation under GCC, and microsoft's under MSVC), so no need to
// do it here. // do it here.
@ -68,27 +49,6 @@ extern void _aligned_free(void* pmem);
_aligned_realloc(handle, new_size, align) _aligned_realloc(handle, new_size, align)
#endif #endif
// --------------------------------------------------------------------------------------
// pxDoOutOfMemory
// --------------------------------------------------------------------------------------
typedef void FnType_OutOfMemory(uptr blocksize);
typedef FnType_OutOfMemory* Fnptr_OutOfMemory;
// This method is meant to be assigned by applications that link against pxWex. It is called
// (invoked) prior to most pxWex built-in memory/array classes throwing exceptions, and can be
// used by an application to remove unneeded memory allocations and/or reduce internal cache
// reserves.
//
// Example: PCSX2 uses several bloated recompiler code caches. Larger caches improve performance,
// however a rouge cache growth could cause memory constraints in the operating system. If an out-
// of-memory error occurs, PCSX2's implementation of this function attempts to reset all internal
// recompiler caches. This can typically free up 100-150 megs of memory, and will allow the app
// to continue running without crashing or hanging the operating system, etc.
//
extern Fnptr_OutOfMemory pxDoOutOfMemory;
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// AlignedBuffer // AlignedBuffer
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------

View File

@ -15,9 +15,10 @@
#pragma once #pragma once
#include <wx/string.h>
#include "common/Pcsx2Defs.h" #include "common/Pcsx2Defs.h"
#include <string>
#ifndef __pxFUNCTION__ #ifndef __pxFUNCTION__
#if defined(__GNUG__) #if defined(__GNUG__)
#define __pxFUNCTION__ __PRETTY_FUNCTION__ #define __pxFUNCTION__ __PRETTY_FUNCTION__
@ -26,25 +27,17 @@
#endif #endif
#endif #endif
#ifndef wxNullChar
#define wxNullChar ((wxChar*)NULL)
#endif
// FnChar_t - function name char type; typedef'd in case it ever changes between compilers
// (ie, a compiler decides to wchar_t it instead of char/UTF8).
typedef char FnChar_t;
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// DiagnosticOrigin // DiagnosticOrigin
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
struct DiagnosticOrigin struct DiagnosticOrigin
{ {
const wxChar* srcfile; const char* srcfile;
const FnChar_t* function; const char* function;
const wxChar* condition; const char* condition;
int line; int line;
DiagnosticOrigin(const wxChar* _file, int _line, const FnChar_t* _func, const wxChar* _cond = NULL) DiagnosticOrigin(const char* _file, int _line, const char* _func, const char* _cond = nullptr)
: srcfile(_file) : srcfile(_file)
, function(_func) , function(_func)
, condition(_cond) , condition(_cond)
@ -52,12 +45,12 @@ struct DiagnosticOrigin
{ {
} }
wxString ToString(const wxChar* msg = NULL) const; std::string ToString(const char* msg = nullptr) const;
}; };
// Returns ture if the assertion is to trap into the debugger, or false if execution // Returns ture if the assertion is to trap into the debugger, or false if execution
// of the program should continue unimpeded. // of the program should continue unimpeded.
typedef bool pxDoAssertFnType(const DiagnosticOrigin& origin, const wxChar* msg); typedef bool pxDoAssertFnType(const DiagnosticOrigin& origin, const char* msg);
extern pxDoAssertFnType pxAssertImpl_LogIt; extern pxDoAssertFnType pxAssertImpl_LogIt;
@ -100,8 +93,8 @@ extern pxDoAssertFnType* pxDoAssert;
// it can lead to the compiler optimizing out code and leading to crashes in dev/release // it can lead to the compiler optimizing out code and leading to crashes in dev/release
// builds. To have code optimized, explicitly use pxAssume(false) or pxAssumeDev(false,msg); // builds. To have code optimized, explicitly use pxAssume(false) or pxAssumeDev(false,msg);
#define pxDiagSpot DiagnosticOrigin(__TFILE__, __LINE__, __pxFUNCTION__) #define pxDiagSpot DiagnosticOrigin(__FILE__, __LINE__, __pxFUNCTION__)
#define pxAssertSpot(cond) DiagnosticOrigin(__TFILE__, __LINE__, __pxFUNCTION__, _T(#cond)) #define pxAssertSpot(cond) DiagnosticOrigin(__FILE__, __LINE__, __pxFUNCTION__, #cond)
// pxAssertRel -> // pxAssertRel ->
// Special release-mode assertion. Limited use since stack traces in release mode builds // Special release-mode assertion. Limited use since stack traces in release mode builds
@ -170,28 +163,12 @@ extern pxDoAssertFnType* pxDoAssert;
#endif #endif
#define pxAssert(cond) pxAssertMsg(cond, wxNullChar) #define pxAssert(cond) pxAssertMsg(cond, nullptr)
#define pxAssume(cond) pxAssumeMsg(cond, wxNullChar) #define pxAssume(cond) pxAssumeMsg(cond, nullptr)
#define pxAssertRelease(cond, msg) #define pxAssertRelease(cond, msg)
// Performs an unsigned index bounds check, and generates a debug assertion if the check fails. extern void pxOnAssert(const DiagnosticOrigin& origin, const char* msg);
// For stricter checking in Devel builds as well as debug builds (but possibly slower), use
// IndexBoundsCheckDev.
#define IndexBoundsCheck(objname, idx, sze) pxAssertMsg((uint)(idx) < (uint)(sze), \
pxsFmt(L"Array index out of bounds accessing object '%s' (index=%d, size=%d)", objname, (idx), (sze)))
#define IndexBoundsCheckDev(objname, idx, sze) pxAssertDev((uint)(idx) < (uint)(sze), \
pxsFmt(L"Array index out of bounds accessing object '%s' (index=%d, size=%d)", objname, (idx), (sze)))
#define IndexBoundsAssume(objname, idx, sze) pxAssumeMsg((uint)(idx) < (uint)(sze), \
pxsFmt(L"Array index out of bounds accessing object '%s' (index=%d, size=%d)", objname, (idx), (sze)))
#define IndexBoundsAssumeDev(objname, idx, sze) pxAssumeDev((uint)(idx) < (uint)(sze), \
pxsFmt(L"Array index out of bounds accessing object '%s' (index=%d, size=%d)", objname, (idx), (sze)))
extern void pxOnAssert(const DiagnosticOrigin& origin, const wxString& msg);
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// jNO_DEFAULT -- disables the default case in a switch, which improves switch optimization // jNO_DEFAULT -- disables the default case in a switch, which improves switch optimization

View File

@ -17,7 +17,6 @@ target_sources(common PRIVATE
CrashHandler.cpp CrashHandler.cpp
EventSource.cpp EventSource.cpp
Exceptions.cpp Exceptions.cpp
FastFormatString.cpp
FastJmp.cpp FastJmp.cpp
FileSystem.cpp FileSystem.cpp
Misc.cpp Misc.cpp
@ -26,10 +25,8 @@ target_sources(common PRIVATE
PrecompiledHeader.cpp PrecompiledHeader.cpp
Perf.cpp Perf.cpp
ProgressCallback.cpp ProgressCallback.cpp
pxTranslate.cpp
Semaphore.cpp Semaphore.cpp
SettingsWrapper.cpp SettingsWrapper.cpp
StringHelpers.cpp
StringUtil.cpp StringUtil.cpp
Timer.cpp Timer.cpp
WindowInfo.cpp WindowInfo.cpp
@ -64,7 +61,6 @@ target_sources(common PRIVATE
boost_spsc_queue.hpp boost_spsc_queue.hpp
Console.h Console.h
CrashHandler.h CrashHandler.h
Dependencies.h
EnumOps.h EnumOps.h
EventSource.h EventSource.h
Exceptions.h Exceptions.h
@ -80,13 +76,11 @@ target_sources(common PRIVATE
PageFaultSource.h PageFaultSource.h
PrecompiledHeader.h PrecompiledHeader.h
ProgressCallback.h ProgressCallback.h
pxForwardDefs.h
RedtapeWindows.h RedtapeWindows.h
SafeArray.h SafeArray.h
ScopedGuard.h ScopedGuard.h
SettingsInterface.h SettingsInterface.h
SettingsWrapper.h SettingsWrapper.h
StringHelpers.h
StringUtil.h StringUtil.h
Timer.h Timer.h
Threading.h Threading.h
@ -262,7 +256,15 @@ if (USE_GCC AND CMAKE_INTERPROCEDURAL_OPTIMIZATION)
set_source_files_properties(FastJmp.cpp PROPERTIES COMPILE_FLAGS -fno-lto) set_source_files_properties(FastJmp.cpp PROPERTIES COMPILE_FLAGS -fno-lto)
endif() endif()
target_link_libraries(common PRIVATE ${LIBC_LIBRARIES} PUBLIC wxWidgets::all) target_link_libraries(common PRIVATE
${LIBC_LIBRARIES}
)
target_link_libraries(common PUBLIC
wxWidgets::all
fmt::fmt
)
target_compile_features(common PUBLIC cxx_std_17) target_compile_features(common PUBLIC cxx_std_17)
target_include_directories(common PUBLIC ../3rdparty/include ../) target_include_directories(common PUBLIC ../3rdparty/include ../)
target_compile_definitions(common PUBLIC "${PCSX2_DEFS}") target_compile_definitions(common PUBLIC "${PCSX2_DEFS}")

View File

@ -15,6 +15,7 @@
#include "common/Threading.h" #include "common/Threading.h"
#include "common/TraceLog.h" #include "common/TraceLog.h"
#include "common/Assertions.h"
#include "common/RedtapeWindows.h" // OutputDebugString #include "common/RedtapeWindows.h" // OutputDebugString
using namespace Threading; using namespace Threading;
@ -73,14 +74,14 @@ void Console_SetActiveHandler(const IConsoleWriter& writer, FILE* flushfp)
// Writes text to the Visual Studio Output window (Microsoft Windows only). // Writes text to the Visual Studio Output window (Microsoft Windows only).
// On all other platforms this pipes to Stdout instead. // On all other platforms this pipes to Stdout instead.
void MSW_OutputDebugString(const wxString& text) static void MSW_OutputDebugString(const char* text)
{ {
#if defined(__WXMSW__) && !defined(__WXMICROWIN__) #ifdef _WIN32
static bool hasDebugger = wxIsDebuggerRunning(); static bool hasDebugger = IsDebuggerPresent();
if (hasDebugger) if (hasDebugger)
OutputDebugString(text); OutputDebugStringA(text);
#else #else
fputs(text.utf8_str(), stdout_fp); fputs(text, stdout_fp);
fflush(stdout_fp); fflush(stdout_fp);
#endif #endif
} }
@ -90,11 +91,11 @@ void MSW_OutputDebugString(const wxString& text)
// ConsoleNull // ConsoleNull
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
static void ConsoleNull_SetTitle(const wxString& title) {} static void ConsoleNull_SetTitle(const char* title) {}
static void ConsoleNull_DoSetColor(ConsoleColors color) {} static void ConsoleNull_DoSetColor(ConsoleColors color) {}
static void ConsoleNull_Newline() {} static void ConsoleNull_Newline() {}
static void ConsoleNull_DoWrite(const wxString& fmt) {} static void ConsoleNull_DoWrite(const char* fmt) {}
static void ConsoleNull_DoWriteLn(const wxString& fmt) {} static void ConsoleNull_DoWriteLn(const char* fmt) {}
const IConsoleWriter ConsoleWriter_Null = const IConsoleWriter ConsoleWriter_Null =
{ {
@ -172,20 +173,21 @@ static __fi const char* GetLinuxConsoleColor(ConsoleColors color)
#endif #endif
// One possible default write action at startup and shutdown is to use the stdout. // One possible default write action at startup and shutdown is to use the stdout.
static void ConsoleStdout_DoWrite(const wxString& fmt) static void ConsoleStdout_DoWrite(const char* fmt)
{ {
MSW_OutputDebugString(fmt); MSW_OutputDebugString(fmt);
} }
// Default write action at startup and shutdown is to use the stdout. // Default write action at startup and shutdown is to use the stdout.
static void ConsoleStdout_DoWriteLn(const wxString& fmt) static void ConsoleStdout_DoWriteLn(const char* fmt)
{ {
MSW_OutputDebugString(fmt + L"\n"); MSW_OutputDebugString(fmt);
MSW_OutputDebugString("\n");
} }
static void ConsoleStdout_Newline() static void ConsoleStdout_Newline()
{ {
MSW_OutputDebugString(L"\n"); MSW_OutputDebugString("\n");
} }
static void ConsoleStdout_DoSetColor(ConsoleColors color) static void ConsoleStdout_DoSetColor(ConsoleColors color)
@ -198,12 +200,12 @@ static void ConsoleStdout_DoSetColor(ConsoleColors color)
#endif #endif
} }
static void ConsoleStdout_SetTitle(const wxString& title) static void ConsoleStdout_SetTitle(const char* title)
{ {
#if defined(__POSIX__) #if defined(__POSIX__)
if (supports_color) if (supports_color)
fputs("\033]0;", stdout_fp); fputs("\033]0;", stdout_fp);
fputs(title.utf8_str(), stdout_fp); fputs(title, stdout_fp);
if (supports_color) if (supports_color)
fputs("\007", stdout_fp); fputs("\007", stdout_fp);
#endif #endif
@ -225,14 +227,14 @@ const IConsoleWriter ConsoleWriter_Stdout =
// ConsoleAssert // ConsoleAssert
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
static void ConsoleAssert_DoWrite(const wxString& fmt) static void ConsoleAssert_DoWrite(const char* fmt)
{ {
pxFail(L"Console class has not been initialized; Message written:\n\t" + fmt); pxFailRel("Console class has not been initialized");
} }
static void ConsoleAssert_DoWriteLn(const wxString& fmt) static void ConsoleAssert_DoWriteLn(const char* fmt)
{ {
pxFail(L"Console class has not been initialized; Message written:\n\t" + fmt); pxFailRel("Console class has not been initialized");
} }
const IConsoleWriter ConsoleWriter_Assert = const IConsoleWriter ConsoleWriter_Assert =
@ -258,16 +260,27 @@ const IConsoleWriter ConsoleWriter_Assert =
// glob_indent - this parameter is used to specify a global indentation setting. It is used by // glob_indent - this parameter is used to specify a global indentation setting. It is used by
// WriteLn function, but defaults to 0 for Warning and Error calls. Local indentation always // WriteLn function, but defaults to 0 for Warning and Error calls. Local indentation always
// applies to all writes. // applies to all writes.
wxString IConsoleWriter::_addIndentation(const wxString& src, int glob_indent = 0) const std::string IConsoleWriter::_addIndentation(const std::string& src, int glob_indent = 0) const
{ {
const int indent = glob_indent + _imm_indentation; const int indent = glob_indent + _imm_indentation;
if (indent == 0)
return src;
wxString result(src); std::string indentStr;
const wxString indentStr(L'\t', indent); for (int i = 0; i < indent; i++)
result.Replace(L"\n", L"\n" + indentStr); indentStr += '\t';
return indentStr + result;
std::string result;
result.reserve(src.length() + 16 * indent);
result.append(indentStr);
result.append(src);
std::string::size_type pos = result.find('\n');
while (pos != std::string::npos)
{
result.insert(pos + 1, indentStr);
pos = result.find('\n', pos + 1);
}
return result;
} }
// Sets the indentation to be applied to all WriteLn's. The indentation is added to the // Sets the indentation to be applied to all WriteLn's. The indentation is added to the
@ -324,7 +337,16 @@ const IConsoleWriter& IConsoleWriter::ClearColor() const
bool IConsoleWriter::FormatV(const char* fmt, va_list args) const bool IConsoleWriter::FormatV(const char* fmt, va_list args) const
{ {
DoWriteLn(_addIndentation(pxsFmtV(fmt, args), conlog_Indent)); // TODO: Make this less rubbish
if ((_imm_indentation + conlog_Indent) > 0)
{
DoWriteLn(_addIndentation(StringUtil::StdStringFromFormatV(fmt, args), conlog_Indent).c_str());
}
else
{
DoWriteLn(StringUtil::StdStringFromFormatV(fmt, args).c_str());
}
return false; return false;
} }
@ -371,105 +393,6 @@ bool IConsoleWriter::Warning(const char* fmt, ...) const
return false; return false;
} }
// --------------------------------------------------------------------------------------
// Write Variants - Unicode/UTF16 style
// --------------------------------------------------------------------------------------
bool IConsoleWriter::FormatV(const wxChar* fmt, va_list args) const
{
DoWriteLn(_addIndentation(pxsFmtV(fmt, args), conlog_Indent));
return false;
}
bool IConsoleWriter::WriteLn(const wxChar* fmt, ...) const
{
va_list args;
va_start(args, fmt);
FormatV(fmt, args);
va_end(args);
return false;
}
bool IConsoleWriter::WriteLn(ConsoleColors color, const wxChar* fmt, ...) const
{
va_list args;
va_start(args, fmt);
ConsoleColorScope cs(color);
FormatV(fmt, args);
va_end(args);
return false;
}
bool IConsoleWriter::Error(const wxChar* fmt, ...) const
{
va_list args;
va_start(args, fmt);
ConsoleColorScope cs(Color_StrongRed);
FormatV(fmt, args);
va_end(args);
return false;
}
bool IConsoleWriter::Warning(const wxChar* fmt, ...) const
{
va_list args;
va_start(args, fmt);
ConsoleColorScope cs(Color_StrongOrange);
FormatV(fmt, args);
va_end(args);
return false;
}
// --------------------------------------------------------------------------------------
// Write Variants - Unknown style
// --------------------------------------------------------------------------------------
bool IConsoleWriter::WriteLn(const wxString fmt, ...) const
{
va_list args;
va_start(args, fmt);
FormatV(fmt.wx_str(), args);
va_end(args);
return false;
}
bool IConsoleWriter::WriteLn(ConsoleColors color, const wxString fmt, ...) const
{
va_list args;
va_start(args, fmt);
ConsoleColorScope cs(color);
FormatV(fmt.wx_str(), args);
va_end(args);
return false;
}
bool IConsoleWriter::Error(const wxString fmt, ...) const
{
va_list args;
va_start(args, fmt);
ConsoleColorScope cs(Color_StrongRed);
FormatV(fmt.wx_str(), args);
va_end(args);
return false;
}
bool IConsoleWriter::Warning(const wxString fmt, ...) const
{
va_list args;
va_start(args, fmt);
ConsoleColorScope cs(Color_StrongOrange);
FormatV(fmt.wx_str(), args);
va_end(args);
return false;
}
bool IConsoleWriter::WriteLn(ConsoleColors color, const std::string& str) const bool IConsoleWriter::WriteLn(ConsoleColors color, const std::string& str) const
{ {
ConsoleColorScope cs(color); ConsoleColorScope cs(color);
@ -478,7 +401,15 @@ bool IConsoleWriter::WriteLn(ConsoleColors color, const std::string& str) const
bool IConsoleWriter::WriteLn(const std::string& str) const bool IConsoleWriter::WriteLn(const std::string& str) const
{ {
DoWriteLn(_addIndentation(fromUTF8(str), conlog_Indent)); // TODO: Make this less rubbish
if ((_imm_indentation + conlog_Indent) > 0)
{
DoWriteLn(_addIndentation(str, conlog_Indent).c_str());
}
else
{
DoWriteLn(str.c_str());
}
return false; return false;
} }
@ -533,11 +464,7 @@ ConsoleIndentScope::ConsoleIndentScope(int tabs)
ConsoleIndentScope::~ConsoleIndentScope() ConsoleIndentScope::~ConsoleIndentScope()
{ {
try LeaveScope();
{
LeaveScope();
}
DESTRUCTOR_CATCHALL
} }
void ConsoleIndentScope::EnterScope() void ConsoleIndentScope::EnterScope()
@ -560,12 +487,8 @@ ConsoleAttrScope::ConsoleAttrScope(ConsoleColors newcolor, int indent)
ConsoleAttrScope::~ConsoleAttrScope() ConsoleAttrScope::~ConsoleAttrScope()
{ {
try Console.SetColor(m_old_color);
{ Console.SetIndent(-m_tabsize);
Console.SetColor(m_old_color);
Console.SetIndent(-m_tabsize);
}
DESTRUCTOR_CATCHALL
} }
@ -599,14 +522,7 @@ NullConsoleWriter NullCon = {};
bool ConsoleLogSource::WriteV(ConsoleColors color, const char* fmt, va_list list) const bool ConsoleLogSource::WriteV(ConsoleColors color, const char* fmt, va_list list) const
{ {
ConsoleColorScope cs(color); ConsoleColorScope cs(color);
DoWrite(pxsFmtV(fmt, list).c_str()); Console.WriteLn(StringUtil::StdStringFromFormatV(fmt, list));
return false;
}
bool ConsoleLogSource::WriteV(ConsoleColors color, const wxChar* fmt, va_list list) const
{
ConsoleColorScope cs(color);
DoWrite(pxsFmtV(fmt, list).c_str());
return false; return false;
} }
@ -618,9 +534,3 @@ bool ConsoleLogSource::WriteV(const char* fmt, va_list list) const
WriteV(DefaultColor, fmt, list); WriteV(DefaultColor, fmt, list);
return false; return false;
} }
bool ConsoleLogSource::WriteV(const wxChar* fmt, va_list list) const
{
WriteV(DefaultColor, fmt, list);
return false;
}

View File

@ -15,7 +15,9 @@
#pragma once #pragma once
#include "common/StringHelpers.h" #include "Pcsx2Defs.h"
#include <string>
enum ConsoleColors enum ConsoleColors
{ {
@ -70,11 +72,11 @@ struct IConsoleWriter
{ {
// A direct console write, without tabbing or newlines. Useful to devs who want to do quick // A direct console write, without tabbing or newlines. Useful to devs who want to do quick
// logging of various junk; but should *not* be used in production code due. // logging of various junk; but should *not* be used in production code due.
void(* WriteRaw)(const wxString& fmt); void(* WriteRaw)(const char* fmt);
// WriteLn implementation for internal use only. Bypasses tabbing, prefixing, and other // WriteLn implementation for internal use only. Bypasses tabbing, prefixing, and other
// formatting. // formatting.
void(* DoWriteLn)(const wxString& fmt); void(* DoWriteLn)(const char* fmt);
// SetColor implementation for internal use only. // SetColor implementation for internal use only.
void(* DoSetColor)(ConsoleColors color); void(* DoSetColor)(ConsoleColors color);
@ -82,16 +84,16 @@ struct IConsoleWriter
// Special implementation of DoWrite that's pretty much for MSVC use only. // Special implementation of DoWrite that's pretty much for MSVC use only.
// All implementations should map to DoWrite, except Stdio which should map to Null. // All implementations should map to DoWrite, except Stdio which should map to Null.
// (This avoids circular/recursive stdio output) // (This avoids circular/recursive stdio output)
void(* DoWriteFromStdout)(const wxString& fmt); void(* DoWriteFromStdout)(const char* fmt);
void(* Newline)(); void(* Newline)();
void(* SetTitle)(const wxString& title); void(* SetTitle)(const char* title);
// internal value for indentation of individual lines. Use the Indent() member to invoke. // internal value for indentation of individual lines. Use the Indent() member to invoke.
int _imm_indentation; int _imm_indentation;
// For internal use only. // For internal use only.
wxString _addIndentation(const wxString& src, int glob_indent) const; std::string _addIndentation(const std::string& src, int glob_indent) const;
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Public members; call these to print stuff to console! // Public members; call these to print stuff to console!
@ -112,17 +114,6 @@ struct IConsoleWriter
bool Error(const char* fmt, ...) const; bool Error(const char* fmt, ...) const;
bool Warning(const char* fmt, ...) const; bool Warning(const char* fmt, ...) const;
bool FormatV(const wxChar* fmt, va_list args) const;
bool WriteLn(ConsoleColors color, const wxChar* fmt, ...) const;
bool WriteLn(const wxChar* fmt, ...) const;
bool Error(const wxChar* fmt, ...) const;
bool Warning(const wxChar* fmt, ...) const;
bool WriteLn(ConsoleColors color, const wxString fmt, ...) const;
bool WriteLn(const wxString fmt, ...) const;
bool Error(const wxString fmt, ...) const;
bool Warning(const wxString fmt, ...) const;
bool WriteLn(ConsoleColors color, const std::string& str) const; bool WriteLn(ConsoleColors color, const std::string& str) const;
bool WriteLn(const std::string& str) const; bool WriteLn(const std::string& str) const;
bool Error(const std::string& str) const; bool Error(const std::string& str) const;
@ -136,12 +127,12 @@ struct IConsoleWriter
// //
struct NullConsoleWriter struct NullConsoleWriter
{ {
void WriteRaw(const wxString& fmt) {} void WriteRaw(const char* fmt) {}
void DoWriteLn(const wxString& fmt) {} void DoWriteLn(const char* fmt) {}
void DoSetColor(ConsoleColors color) {} void DoSetColor(ConsoleColors color) {}
void DoWriteFromStdout(const wxString& fmt) {} void DoWriteFromStdout(const char* fmt) {}
void Newline() {} void Newline() {}
void SetTitle(const wxString& title) {} void SetTitle(const char* title) {}
ConsoleColors GetColor() const { return Color_Current; } ConsoleColors GetColor() const { return Color_Current; }
@ -156,17 +147,6 @@ struct NullConsoleWriter
bool WriteLn(const char* fmt, ...) const { return false; } bool WriteLn(const char* fmt, ...) const { return false; }
bool Error(const char* fmt, ...) const { return false; } bool Error(const char* fmt, ...) const { return false; }
bool Warning(const char* fmt, ...) const { return false; } bool Warning(const char* fmt, ...) const { return false; }
bool FormatV(const wxChar* fmt, va_list args) const { return false; }
bool WriteLn(ConsoleColors color, const wxChar* fmt, ...) const { return false; }
bool WriteLn(const wxChar* fmt, ...) const { return false; }
bool Error(const wxChar* fmt, ...) const { return false; }
bool Warning(const wxChar* fmt, ...) const { return false; }
bool WriteLn(ConsoleColors color, const wxString fmt, ...) const { return false; }
bool WriteLn(const wxString fmt, ...) const { return false; }
bool Error(const wxString fmt, ...) const { return false; }
bool Warning(const wxString fmt, ...) const { return false; }
}; };
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------

View File

@ -23,6 +23,7 @@
#include <wx/string.h> #include <wx/string.h>
#include "common/Pcsx2Types.h" #include "common/Pcsx2Types.h"
#include "common/General.h"
// Darwin (OSX) is a bit different from Linux when requesting properties of // Darwin (OSX) is a bit different from Linux when requesting properties of
// the OS because of its BSD/Mach heritage. Helpfully, most of this code // the OS because of its BSD/Mach heritage. Helpfully, most of this code
@ -85,7 +86,7 @@ static std::string sysctl_str(int category, int name)
return std::string(buf, len > 0 ? len - 1 : 0); return std::string(buf, len > 0 ? len - 1 : 0);
} }
wxString GetOSVersionString() std::string GetOSVersionString()
{ {
std::string type = sysctl_str(CTL_KERN, KERN_OSTYPE); std::string type = sysctl_str(CTL_KERN, KERN_OSTYPE);
std::string release = sysctl_str(CTL_KERN, KERN_OSRELEASE); std::string release = sysctl_str(CTL_KERN, KERN_OSRELEASE);

View File

@ -1,240 +0,0 @@
/* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// Dependencies.h : Contains classes required by all Utilities headers.
// This file is included by most .h files provided by the Utilities class.
#include "pxForwardDefs.h"
// This should prove useful....
#define wxsFormat wxString::Format
// --------------------------------------------------------------------------------------
// ImplementEnumOperators (macro)
// --------------------------------------------------------------------------------------
// This macro implements ++/-- operators for any conforming enumeration. In order for an
// enum to conform, it must have _FIRST and _COUNT members defined, and must have a full
// compliment of sequential members (no custom assignments) --- looking like so:
//
// enum Dummy {
// Dummy_FIRST,
// Dummy_Item = Dummy_FIRST,
// Dummy_Crap,
// Dummy_COUNT
// };
//
// The macro also defines utility functions for bounds checking enumerations:
// EnumIsValid(value); // returns TRUE if the enum value is between FIRST and COUNT.
// EnumAssert(value);
//
// It also defines a *prototype* for converting the enumeration to a string. Note that this
// method is not implemented! You must implement it yourself if you want to use it:
// EnumToString(value);
//
#define ImplementEnumOperators(enumName) \
static __fi enumName& operator++(enumName& src) \
{ \
src = (enumName)((int)src + 1); \
return src; \
} \
\
static __fi enumName& operator--(enumName& src) \
{ \
src = (enumName)((int)src - 1); \
return src; \
} \
\
static __fi enumName operator++(enumName& src, int) \
{ \
enumName orig = src; \
src = (enumName)((int)src + 1); \
return orig; \
} \
\
static __fi enumName operator--(enumName& src, int) \
{ \
enumName orig = src; \
src = (enumName)((int)src - 1); \
return orig; \
} \
\
static __fi bool operator<(const enumName& left, const pxEnumEnd_t&) { return (int)left < enumName##_COUNT; } \
static __fi bool operator!=(const enumName& left, const pxEnumEnd_t&) { return (int)left != enumName##_COUNT; } \
static __fi bool operator==(const enumName& left, const pxEnumEnd_t&) { return (int)left == enumName##_COUNT; } \
\
static __fi bool EnumIsValid(enumName id) \
{ \
return ((int)id >= enumName##_FIRST) && ((int)id < enumName##_COUNT); \
} \
\
static __fi void EnumAssert(enumName id) \
{ \
pxAssert(EnumIsValid(id)); \
} \
\
extern const char* EnumToString(enumName id)
class pxEnumEnd_t
{
};
static const pxEnumEnd_t pxEnumEnd = {};
// --------------------------------------------------------------------------------------
// DeclareNoncopyableObject
// --------------------------------------------------------------------------------------
// This macro provides an easy and clean method for ensuring objects are not copyable.
// Simply add the macro to the head or tail of your class declaration, and attempts to
// copy the class will give you a moderately obtuse compiler error that will have you
// scratching your head for 20 minutes.
//
// (... but that's probably better than having a weird invalid object copy having you
// scratch your head for a day).
//
// Programmer's notes:
// * We intentionally do NOT provide implementations for these methods, which should
// never be referenced anyway.
// * I've opted for macro form over multi-inherited class form (Boost style), because
// the errors generated by the macro are considerably less voodoo. The Boost-style
// The macro reports the exact class that causes the copy failure, while Boost's class
// approach just reports an error in whatever "NoncopyableObject" is inherited.
//
// * This macro is the same as wxWidgets' DECLARE_NO_COPY_CLASS macro. This one is free
// of wx dependencies though, and has a nicer typeset. :)
//
#ifndef DeclareNoncopyableObject
#define DeclareNoncopyableObject(classname) \
public: \
classname(const classname&) = delete; \
classname& operator=(const classname&) = delete
#endif
// --------------------------------------------------------------------------------------
// _(x) / _t(x) / _d(x) / pxL(x) / pxLt(x) [macros]
// --------------------------------------------------------------------------------------
// Define pxWex's own i18n helpers. These override the wxWidgets helpers and provide
// additional functionality. Define them FIRST THING, to make sure that wx's own gettext
// macros aren't in place.
//
// _ is for standard translations
// _t is for tertiary low priority translations
// _d is for debug/devel build translations
#define WXINTL_NO_GETTEXT_MACRO
#ifndef _
#define _(s) pxGetTranslation(_T(s))
#endif
#ifndef _t
#define _t(s) pxGetTranslation(_T(s))
#endif
#ifndef _d
#define _d(s) pxGetTranslation(_T(s))
#endif
// pxL / pxLt / pxDt -- macros provided for tagging translation strings, without actually running
// them through the translator (which the _() does automatically, and sometimes we don't
// want that). This is a shorthand replacement for wxTRANSLATE. pxL is a standard translation
// moniker. pxLt is for tertiary strings that have a very low translation priority. pxDt is for
// debug/devel specific translations.
//
#ifndef pxL
#define pxL(a) wxT(a)
#endif
#ifndef pxLt
#define pxLt(a) wxT(a)
#endif
#ifndef pxDt
#define pxDt(a) wxT(a)
#endif
#include <wx/string.h>
#include <wx/intl.h>
#include <wx/log.h>
#include <wx/crt.h>
#if defined(_WIN32)
// This deals with a mode_t redefinition conflict. The mode_t doesn't seem to be
// used anywhere in w32pthreads, so I've chosen to use the wxWidgets mode_t
// (I think it's unsigned int vs signed int)
#include <wx/filefn.h>
#define HAVE_MODE_T
#endif
#include <stdexcept>
#include <cstring> // string.h under c++
#include <cstdio> // stdio.h under c++
#include <cstdlib>
#include <vector>
#include <list>
#include <algorithm>
#include <memory>
#include <atomic>
#include <thread>
#include "Pcsx2Defs.h"
// --------------------------------------------------------------------------------------
// Handy Human-readable constants for common immediate values (_16kb -> _4gb)
static const sptr _1kb = 1024 * 1;
static const sptr _4kb = _1kb * 4;
static const sptr _16kb = _1kb * 16;
static const sptr _32kb = _1kb * 32;
static const sptr _64kb = _1kb * 64;
static const sptr _128kb = _1kb * 128;
static const sptr _256kb = _1kb * 256;
static const s64 _1mb = 1024 * 1024;
static const s64 _8mb = _1mb * 8;
static const s64 _16mb = _1mb * 16;
static const s64 _32mb = _1mb * 32;
static const s64 _64mb = _1mb * 64;
static const s64 _256mb = _1mb * 256;
static const s64 _1gb = _1mb * 1024;
static const s64 _4gb = _1gb * 4;
// --------------------------------------------------------------------------------------
// pxE(msg) and pxEt(msg) [macros] => now same as _/_t/_d
// --------------------------------------------------------------------------------------
#define pxE(english) pxExpandMsg((english))
// For use with tertiary translations (low priority).
#define pxEt(english) pxExpandMsg((english))
// For use with Dev/debug build translations (low priority).
#define pxE_dev(english) pxExpandMsg((english))
extern const wxChar* pxExpandMsg(const wxChar* message);
extern const wxChar* pxGetTranslation(const wxChar* message);
extern bool pxIsEnglish(int id);
extern wxString fromUTF8(const std::string& str);
extern wxString fromUTF8(const char* src);
extern wxString fromAscii(const char* src);
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include "common/AlignedMalloc.h"

View File

@ -17,7 +17,4 @@
#include "EventSource.h" #include "EventSource.h"
#include "EventSource.inl" #include "EventSource.inl"
#include <wx/event.h>
//template class EventSource< wxCommandEvent >;
//template class EventSource< int >; //template class EventSource< int >;

View File

@ -75,21 +75,21 @@ __fi void EventSource<ListenerType>::_DispatchRaw(ListenerIterator iter, const L
{ {
if (IsDevBuild) if (IsDevBuild)
{ {
pxFailDev(L"Ignoring runtime error thrown from event listener (event listeners should not throw exceptions!): " + ex.FormatDiagnosticMessage()); pxFailDev(("Ignoring runtime error thrown from event listener (event listeners should not throw exceptions!): " + ex.FormatDiagnosticMessage()).c_str());
} }
else else
{ {
Console.Error(L"Ignoring runtime error thrown from event listener: " + ex.FormatDiagnosticMessage()); Console.Error("Ignoring runtime error thrown from event listener: %s", ex.FormatDiagnosticMessage().c_str());
} }
} }
catch (BaseException& ex) catch (BaseException& ex)
{ {
if (IsDevBuild) if (IsDevBuild)
{ {
ex.DiagMsg() = L"Non-runtime BaseException thrown from event listener .. " + ex.DiagMsg(); ex.DiagMsg() = "Non-runtime BaseException thrown from event listener .. " + ex.DiagMsg();
throw; throw;
} }
Console.Error(L"Ignoring non-runtime BaseException thrown from event listener: " + ex.FormatDiagnosticMessage()); Console.Error("Ignoring non-runtime BaseException thrown from event listener: %s", ex.FormatDiagnosticMessage().c_str());
} }
++iter; ++iter;
} }

View File

@ -13,20 +13,19 @@
* If not, see <http://www.gnu.org/licenses/>. * If not, see <http://www.gnu.org/licenses/>.
*/ */
#define WXINTL_NO_GETTEXT_MACRO #include "Threading.h"
#include "General.h"
#include "Exceptions.h"
#include <wx/app.h> #include "fmt/core.h"
#if defined(__UNIX__)
#include <signal.h> #ifdef _WIN32
#include "RedtapeWindows.h"
#endif #endif
#include "common/Dependencies.h" // _ macro #ifdef __UNIX__
#include "common/Threading.h" #include <signal.h>
#include "common/General.h" #endif
#include "common/StringHelpers.h"
// for lack of a better place...
Fnptr_OutOfMemory pxDoOutOfMemory = NULL;
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Force DevAssert to *not* inline for devel builds (allows using breakpoints to trap assertions, // Force DevAssert to *not* inline for devel builds (allows using breakpoints to trap assertions,
@ -43,20 +42,20 @@ pxDoAssertFnType* pxDoAssert = pxAssertImpl_LogIt;
// make life easier for people using VC++ IDE by using this format, which allows double-click // make life easier for people using VC++ IDE by using this format, which allows double-click
// response times from the Output window... // response times from the Output window...
wxString DiagnosticOrigin::ToString(const wxChar* msg) const std::string DiagnosticOrigin::ToString(const char* msg) const
{ {
FastFormatUnicode message; std::string message;
message.Write(L"%ls(%d) : assertion failed:\n", srcfile, line); fmt::format_to(std::back_inserter(message), "{}({}) : assertion failed:\n", srcfile, line);
if (function != NULL) if (function)
message.Write(" Function: %s\n", function); fmt::format_to(std::back_inserter(message), " Function: {}\n", function);
if (condition != NULL) if (condition)
message.Write(L" Condition: %ls\n", condition); fmt::format_to(std::back_inserter(message), " Condition: {}\n", condition);
if (msg != NULL) if (msg)
message.Write(L" Message: %ls\n", msg); fmt::format_to(std::back_inserter(message), " Message: {}\n", msg);
return message; return message;
} }
@ -65,34 +64,33 @@ wxString DiagnosticOrigin::ToString(const wxChar* msg) const
// Because wxTrap isn't available on Linux builds of wxWidgets (non-Debug, typically) // Because wxTrap isn't available on Linux builds of wxWidgets (non-Debug, typically)
void pxTrap() void pxTrap()
{ {
#if defined(__WXMSW__) && !defined(__WXMICROWIN__) #if defined(_WIN32)
__debugbreak(); __debugbreak();
#elif defined(__WXMAC__) && !defined(__DARWIN__)
#if __powerc
Debugger();
#else
SysBreak();
#endif
#elif defined(_MSL_USING_MW_C_HEADERS) && _MSL_USING_MW_C_HEADERS
Debugger();
#elif defined(__UNIX__) #elif defined(__UNIX__)
raise(SIGTRAP); raise(SIGTRAP);
#else #else
// TODO abort();
#endif // Win/Unix #endif
} }
bool pxAssertImpl_LogIt(const DiagnosticOrigin& origin, const wxChar* msg) bool pxAssertImpl_LogIt(const DiagnosticOrigin& origin, const char* msg)
{ {
//wxLogError( L"%s", origin.ToString( msg ).c_str() ); //wxLogError( L"%s", origin.ToString( msg ).c_str() );
wxMessageOutputDebug().Printf(L"%s", origin.ToString(msg).c_str()); std::string full_msg(origin.ToString(msg));
#ifdef _WIN32
OutputDebugStringA(full_msg.c_str());
OutputDebugStringA("\n");
#endif
std::fprintf(stderr, "%s\n", full_msg.c_str());
pxTrap(); pxTrap();
return false; return false;
} }
DEVASSERT_INLINE void pxOnAssert(const DiagnosticOrigin& origin, const wxString& msg) DEVASSERT_INLINE void pxOnAssert(const DiagnosticOrigin& origin, const char* msg)
{ {
// wxWidgets doesn't come with debug builds on some Linux distros, and other distros make // wxWidgets doesn't come with debug builds on some Linux distros, and other distros make
// it difficult to use the debug build (compilation failures). To handle these I've had to // it difficult to use the debug build (compilation failures). To handle these I've had to
@ -104,11 +102,11 @@ DEVASSERT_INLINE void pxOnAssert(const DiagnosticOrigin& origin, const wxString&
if (pxDoAssert == NULL) if (pxDoAssert == NULL)
{ {
// Note: Format uses MSVC's syntax for output window hotlinking. // Note: Format uses MSVC's syntax for output window hotlinking.
trapit = pxAssertImpl_LogIt(origin, msg.wc_str()); trapit = pxAssertImpl_LogIt(origin, msg);
} }
else else
{ {
trapit = pxDoAssert(origin, msg.wc_str()); trapit = pxDoAssert(origin, msg);
} }
if (trapit) if (trapit)
@ -121,83 +119,87 @@ DEVASSERT_INLINE void pxOnAssert(const DiagnosticOrigin& origin, const wxString&
// BaseException (implementations) // BaseException (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
BaseException& BaseException::SetBothMsgs(const wxChar* msg_diag) BaseException& BaseException::SetBothMsgs(const char* msg_diag)
{ {
m_message_user = msg_diag ? wxString(wxGetTranslation(msg_diag)) : wxString(""); m_message_user = msg_diag ? std::string(msg_diag) : std::string();
return SetDiagMsg(msg_diag); return SetDiagMsg(msg_diag);
} }
BaseException& BaseException::SetDiagMsg(const wxString& msg_diag) BaseException& BaseException::SetDiagMsg(std::string msg_diag)
{ {
m_message_diag = msg_diag; m_message_diag = std::move(msg_diag);
return *this; return *this;
} }
BaseException& BaseException::SetUserMsg(const wxString& msg_user) BaseException& BaseException::SetUserMsg(std::string msg_user)
{ {
m_message_user = msg_user; m_message_user = std::move(msg_user);
return *this; return *this;
} }
wxString BaseException::FormatDiagnosticMessage() const std::string BaseException::FormatDiagnosticMessage() const
{ {
return m_message_diag; return m_message_diag;
} }
wxString BaseException::FormatDisplayMessage() const std::string BaseException::FormatDisplayMessage() const
{ {
return m_message_user.IsEmpty() ? m_message_diag : m_message_user; return m_message_user.empty() ? m_message_diag : m_message_user;
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::RuntimeError (implementations) // Exception::RuntimeError (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
Exception::RuntimeError::RuntimeError(const std::runtime_error& ex, const wxString& prefix) Exception::RuntimeError::RuntimeError(const std::runtime_error& ex, const char* prefix /* = nullptr */)
{ {
IsSilent = false; IsSilent = false;
SetDiagMsg(pxsFmt(L"STL Runtime Error%s: %s", const bool has_prefix = prefix && prefix[0] != 0;
(prefix.IsEmpty() ? L"" : pxsFmt(L" (%s)", WX_STR(prefix)).c_str()),
WX_STR(fromUTF8(ex.what())))); SetDiagMsg(fmt::format("STL Runtime Error{}{}{}: {}",
has_prefix ? " (" : "", prefix ? prefix : "", has_prefix ? ")" : "",
ex.what()));
} }
Exception::RuntimeError::RuntimeError(const std::exception& ex, const wxString& prefix) Exception::RuntimeError::RuntimeError(const std::exception& ex, const char* prefix /* = nullptr */)
{ {
IsSilent = false; IsSilent = false;
SetDiagMsg(pxsFmt(L"STL Exception%s: %s", const bool has_prefix = prefix && prefix[0] != 0;
(prefix.IsEmpty() ? L"" : pxsFmt(L" (%s)", WX_STR(prefix)).c_str()),
WX_STR(fromUTF8(ex.what())))); SetDiagMsg(fmt::format("STL Exception{}{}{}: {}",
has_prefix ? " (" : "", prefix ? prefix : "", has_prefix ? ")" : "",
ex.what()));
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::OutOfMemory (implementations) // Exception::OutOfMemory (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
Exception::OutOfMemory::OutOfMemory(const wxString& allocdesc) Exception::OutOfMemory::OutOfMemory(std::string allocdesc)
: AllocDescription(std::move(allocdesc))
{ {
AllocDescription = allocdesc;
} }
wxString Exception::OutOfMemory::FormatDiagnosticMessage() const std::string Exception::OutOfMemory::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retmsg; std::string retmsg;
retmsg.Write(L"Out of memory"); retmsg = "Out of memory";
if (!AllocDescription.IsEmpty()) if (!AllocDescription.empty())
retmsg.Write(L" while allocating '%s'", WX_STR(AllocDescription)); fmt::format_to(std::back_inserter(retmsg), " while allocating '{}'", AllocDescription);
if (!m_message_diag.IsEmpty()) if (!m_message_diag.empty())
retmsg.Write(L":\n%s", WX_STR(m_message_diag)); fmt::format_to(std::back_inserter(retmsg), ":\n{}", m_message_diag);
return retmsg; return retmsg;
} }
wxString Exception::OutOfMemory::FormatDisplayMessage() const std::string Exception::OutOfMemory::FormatDisplayMessage() const
{ {
FastFormatUnicode retmsg; std::string retmsg;
retmsg.Write(L"%s", _("Oh noes! Out of memory!")); retmsg = "Oh noes! Out of memory!";
if (!m_message_user.IsEmpty()) if (!m_message_user.empty())
retmsg.Write(L"\n\n%s", WX_STR(m_message_user)); fmt::format_to(std::back_inserter(retmsg), "\n\n{}", m_message_user);
return retmsg; return retmsg;
} }
@ -206,106 +208,104 @@ wxString Exception::OutOfMemory::FormatDisplayMessage() const
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::VirtualMemoryMapConflict (implementations) // Exception::VirtualMemoryMapConflict (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
Exception::VirtualMemoryMapConflict::VirtualMemoryMapConflict(const wxString& allocdesc) Exception::VirtualMemoryMapConflict::VirtualMemoryMapConflict(std::string allocdesc)
{ {
AllocDescription = allocdesc; AllocDescription = std::move(allocdesc);
m_message_user = _("Virtual memory mapping failure! Your system may have conflicting device drivers, services, or may simply have insufficient memory or resources to meet PCSX2's lofty needs."); m_message_user = "Virtual memory mapping failure! Your system may have conflicting device drivers, services, or may simply have insufficient memory or resources to meet PCSX2's lofty needs.";
} }
wxString Exception::VirtualMemoryMapConflict::FormatDiagnosticMessage() const std::string Exception::VirtualMemoryMapConflict::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retmsg; std::string retmsg;
retmsg.Write(L"Virtual memory map failed"); retmsg = "Virtual memory map failed";
if (!AllocDescription.IsEmpty()) if (!AllocDescription.empty())
retmsg.Write(L" while reserving '%s'", WX_STR(AllocDescription)); fmt::format_to(std::back_inserter(retmsg), " while reserving '{}'", AllocDescription);
if (!m_message_diag.IsEmpty()) if (!m_message_diag.empty())
retmsg.Write(L":\n%s", WX_STR(m_message_diag)); fmt::format_to(std::back_inserter(retmsg), ":\n{}", m_message_diag);
return retmsg; return retmsg;
} }
wxString Exception::VirtualMemoryMapConflict::FormatDisplayMessage() const std::string Exception::VirtualMemoryMapConflict::FormatDisplayMessage() const
{ {
FastFormatUnicode retmsg; std::string retmsg;
retmsg.Write(L"%s", retmsg = "There is not enough virtual memory available, or necessary virtual memory mappings have already been reserved by other processes, services, or DLLs.";
pxE(L"There is not enough virtual memory available, or necessary virtual memory mappings have already been reserved by other processes, services, or DLLs."));
if (!m_message_diag.IsEmpty()) if (!m_message_diag.empty())
retmsg.Write(L"\n\n%s", WX_STR(m_message_diag)); fmt::format_to(std::back_inserter(retmsg), "\n\n{}", m_message_diag);
return retmsg; return retmsg;
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
wxString Exception::CancelEvent::FormatDiagnosticMessage() const std::string Exception::CancelEvent::FormatDiagnosticMessage() const
{ {
return L"Action canceled: " + m_message_diag; return "Action canceled: " + m_message_diag;
} }
wxString Exception::CancelEvent::FormatDisplayMessage() const std::string Exception::CancelEvent::FormatDisplayMessage() const
{ {
return L"Action canceled: " + m_message_diag; return "Action canceled: " + m_message_diag;
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::BadStream (implementations) // Exception::BadStream (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
wxString Exception::BadStream::FormatDiagnosticMessage() const std::string Exception::BadStream::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retval; std::string retval;
_formatDiagMsg(retval); _formatDiagMsg(retval);
return retval; return retval;
} }
wxString Exception::BadStream::FormatDisplayMessage() const std::string Exception::BadStream::FormatDisplayMessage() const
{ {
FastFormatUnicode retval; std::string retval;
_formatUserMsg(retval); _formatUserMsg(retval);
return retval; return retval;
} }
void Exception::BadStream::_formatDiagMsg(FastFormatUnicode& dest) const void Exception::BadStream::_formatDiagMsg(std::string& dest) const
{ {
dest.Write(L"Path: "); fmt::format_to(std::back_inserter(dest), "Path: ");
if (!StreamName.IsEmpty()) if (!StreamName.empty())
dest.Write(L"%s", WX_STR(StreamName)); fmt::format_to(std::back_inserter(dest), "{}", StreamName);
else else
dest.Write(L"[Unnamed or unknown]"); dest += "[Unnamed or unknown]";
if (!m_message_diag.IsEmpty()) if (!m_message_diag.empty())
dest.Write(L"\n%s", WX_STR(m_message_diag)); fmt::format_to(std::back_inserter(dest), "\n{}", m_message_diag);
} }
void Exception::BadStream::_formatUserMsg(FastFormatUnicode& dest) const void Exception::BadStream::_formatUserMsg(std::string& dest) const
{ {
dest.Write(_("Path: ")); fmt::format_to(std::back_inserter(dest), "Path: ");
if (!StreamName.IsEmpty()) if (!StreamName.empty())
dest.Write(L"%s", WX_STR(StreamName)); fmt::format_to(std::back_inserter(dest), "{}", StreamName);
else else
dest.Write(_("[Unnamed or unknown]")); dest += "[Unnamed or unknown]";
if (!m_message_user.IsEmpty()) if (!m_message_user.empty())
dest.Write(L"\n%s", WX_STR(m_message_user)); fmt::format_to(std::back_inserter(dest), "\n{}", m_message_user);
} }
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::CannotCreateStream (implementations) // Exception::CannotCreateStream (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
wxString Exception::CannotCreateStream::FormatDiagnosticMessage() const std::string Exception::CannotCreateStream::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write("File could not be created."); retval = "File could not be created.";
_formatDiagMsg(retval); _formatDiagMsg(retval);
return retval; return retval;
} }
wxString Exception::CannotCreateStream::FormatDisplayMessage() const std::string Exception::CannotCreateStream::FormatDisplayMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write(_("A file could not be created.")); retval = "A file could not be created.\n";
retval.Write("\n");
_formatUserMsg(retval); _formatUserMsg(retval);
return retval; return retval;
} }
@ -313,19 +313,18 @@ wxString Exception::CannotCreateStream::FormatDisplayMessage() const
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::FileNotFound (implementations) // Exception::FileNotFound (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
wxString Exception::FileNotFound::FormatDiagnosticMessage() const std::string Exception::FileNotFound::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write("File not found.\n"); retval = "File not found.\n";
_formatDiagMsg(retval); _formatDiagMsg(retval);
return retval; return retval;
} }
wxString Exception::FileNotFound::FormatDisplayMessage() const std::string Exception::FileNotFound::FormatDisplayMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write(_("File not found.")); retval = "File not found.\n";
retval.Write("\n");
_formatUserMsg(retval); _formatUserMsg(retval);
return retval; return retval;
} }
@ -333,19 +332,18 @@ wxString Exception::FileNotFound::FormatDisplayMessage() const
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::AccessDenied (implementations) // Exception::AccessDenied (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
wxString Exception::AccessDenied::FormatDiagnosticMessage() const std::string Exception::AccessDenied::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write("Permission denied to file.\n"); retval = "Permission denied to file.\n";
_formatDiagMsg(retval); _formatDiagMsg(retval);
return retval; return retval;
} }
wxString Exception::AccessDenied::FormatDisplayMessage() const std::string Exception::AccessDenied::FormatDisplayMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write(_("Permission denied while trying to open file, likely due to insufficient user account rights.")); retval = "Permission denied while trying to open file, likely due to insufficient user account rights.\n";
retval.Write("\n");
_formatUserMsg(retval); _formatUserMsg(retval);
return retval; return retval;
} }
@ -353,19 +351,18 @@ wxString Exception::AccessDenied::FormatDisplayMessage() const
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::EndOfStream (implementations) // Exception::EndOfStream (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
wxString Exception::EndOfStream::FormatDiagnosticMessage() const std::string Exception::EndOfStream::FormatDiagnosticMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write("Unexpected end of file or stream.\n"); retval = "Unexpected end of file or stream.\n";
_formatDiagMsg(retval); _formatDiagMsg(retval);
return retval; return retval;
} }
wxString Exception::EndOfStream::FormatDisplayMessage() const std::string Exception::EndOfStream::FormatDisplayMessage() const
{ {
FastFormatUnicode retval; std::string retval;
retval.Write(_("Unexpected end of file or stream encountered. File is probably truncated or corrupted.")); retval = "Unexpected end of file or stream encountered. File is probably truncated or corrupted.\n";
retval.Write("\n");
_formatUserMsg(retval); _formatUserMsg(retval);
return retval; return retval;
} }
@ -376,35 +373,35 @@ wxString Exception::EndOfStream::FormatDisplayMessage() const
// Translates an Errno code into an exception. // Translates an Errno code into an exception.
// Throws an exception based on the given error code (usually taken from ANSI C's errno) // Throws an exception based on the given error code (usually taken from ANSI C's errno)
BaseException* Exception::FromErrno(const wxString& streamname, int errcode) BaseException* Exception::FromErrno(std::string streamname, int errcode)
{ {
pxAssumeDev(errcode != 0, "Invalid NULL error code? (errno)"); pxAssumeDev(errcode != 0, "Invalid NULL error code? (errno)");
switch (errcode) switch (errcode)
{ {
case EINVAL: case EINVAL:
pxFailDev(L"Invalid argument"); pxFailDev("Invalid argument");
return &(new Exception::BadStream(streamname))->SetDiagMsg(L"Invalid argument? (likely caused by an unforgivable programmer error!)"); return &(new Exception::BadStream(streamname))->SetDiagMsg("Invalid argument? (likely caused by an unforgivable programmer error!)");
case EACCES: // Access denied! case EACCES: // Access denied!
return new Exception::AccessDenied(streamname); return new Exception::AccessDenied(streamname);
case EMFILE: // Too many open files! case EMFILE: // Too many open files!
return &(new Exception::CannotCreateStream(streamname))->SetDiagMsg(L"Too many open files"); // File handle allocation failure return &(new Exception::CannotCreateStream(streamname))->SetDiagMsg("Too many open files"); // File handle allocation failure
case EEXIST: case EEXIST:
return &(new Exception::CannotCreateStream(streamname))->SetDiagMsg(L"File already exists"); return &(new Exception::CannotCreateStream(streamname))->SetDiagMsg("File already exists");
case ENOENT: // File not found! case ENOENT: // File not found!
return new Exception::FileNotFound(streamname); return new Exception::FileNotFound(streamname);
case EPIPE: case EPIPE:
return &(new Exception::BadStream(streamname))->SetDiagMsg(L"Broken pipe"); return &(new Exception::BadStream(streamname))->SetDiagMsg("Broken pipe");
case EBADF: case EBADF:
return &(new Exception::BadStream(streamname))->SetDiagMsg(L"Bad file number"); return &(new Exception::BadStream(streamname))->SetDiagMsg("Bad file number");
default: default:
return &(new Exception::BadStream(streamname))->SetDiagMsg(pxsFmt(L"General file/stream error [errno: %d]", errcode)); return &(new Exception::BadStream(streamname))->SetDiagMsg(fmt::format("General file/stream error [errno: {}]", errcode));
} }
} }

View File

@ -16,9 +16,9 @@
#pragma once #pragma once
#include <memory> #include <memory>
#include <wx/string.h> #include <stdexcept>
#include "common/Assertions.h" #include "common/Assertions.h"
#include "common/Dependencies.h" #include "common/Pcsx2Defs.h"
// Because wxTrap isn't available on Linux builds of wxWidgets (non-Debug, typically) // Because wxTrap isn't available on Linux builds of wxWidgets (non-Debug, typically)
void pxTrap(); void pxTrap();
@ -69,7 +69,7 @@ namespace Exception
class BaseException; class BaseException;
int MakeNewType(); int MakeNewType();
BaseException* FromErrno(const wxString& streamname, int errcode); BaseException* FromErrno(std::string streamname, int errcode);
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// BaseException // BaseException
@ -91,29 +91,29 @@ namespace Exception
class BaseException class BaseException
{ {
protected: protected:
wxString m_message_diag; // (untranslated) a "detailed" message of what disastrous thing has occurred! std::string m_message_diag; // (untranslated) a "detailed" message of what disastrous thing has occurred!
wxString m_message_user; // (translated) a "detailed" message of what disastrous thing has occurred! std::string m_message_user; // (translated) a "detailed" message of what disastrous thing has occurred!
public: public:
virtual ~BaseException() = default; virtual ~BaseException() = default;
const wxString& DiagMsg() const { return m_message_diag; } const std::string& DiagMsg() const { return m_message_diag; }
const wxString& UserMsg() const { return m_message_user; } const std::string& UserMsg() const { return m_message_user; }
wxString& DiagMsg() { return m_message_diag; } std::string& DiagMsg() { return m_message_diag; }
wxString& UserMsg() { return m_message_user; } std::string& UserMsg() { return m_message_user; }
BaseException& SetBothMsgs(const wxChar* msg_diag); BaseException& SetBothMsgs(const char* msg_diag);
BaseException& SetDiagMsg(const wxString& msg_diag); BaseException& SetDiagMsg(std::string msg_diag);
BaseException& SetUserMsg(const wxString& msg_user); BaseException& SetUserMsg(std::string msg_user);
// Returns a message suitable for diagnostic / logging purposes. // Returns a message suitable for diagnostic / logging purposes.
// This message is always in English, and includes a full stack trace. // This message is always in English, and includes a full stack trace.
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
// Returns a message suitable for end-user display. // Returns a message suitable for end-user display.
// This message is usually meant for display in a user popup or such. // This message is usually meant for display in a user popup or such.
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
virtual void Rethrow() const = 0; virtual void Rethrow() const = 0;
virtual BaseException* Clone() const = 0; virtual BaseException* Clone() const = 0;
@ -135,14 +135,14 @@ namespace Exception
class Ps2Generic class Ps2Generic
{ {
protected: protected:
wxString m_message; // a "detailed" message of what disastrous thing has occurred! std::string m_message; // a "detailed" message of what disastrous thing has occurred!
public: public:
virtual ~Ps2Generic() = default; virtual ~Ps2Generic() = default;
virtual u32 GetPc() const = 0; virtual u32 GetPc() const = 0;
virtual bool IsDelaySlot() const = 0; virtual bool IsDelaySlot() const = 0;
virtual wxString& Message() { return m_message; } virtual std::string& Message() { return m_message; }
virtual void Rethrow() const = 0; virtual void Rethrow() const = 0;
virtual Ps2Generic* Clone() const = 0; virtual Ps2Generic* Clone() const = 0;
@ -181,21 +181,21 @@ public: \
#define DEFINE_EXCEPTION_MESSAGES(classname) \ #define DEFINE_EXCEPTION_MESSAGES(classname) \
public: \ public: \
classname& SetBothMsgs(const wxChar* msg_diag) \ classname& SetBothMsgs(const char* msg_diag) \
{ \ { \
BaseException::SetBothMsgs(msg_diag); \ BaseException::SetBothMsgs(msg_diag); \
return *this; \ return *this; \
} \ } \
\ \
classname& SetDiagMsg(const wxString& msg_diag) \ classname& SetDiagMsg(std::string msg_diag) \
{ \ { \
m_message_diag = msg_diag; \ m_message_diag = msg_diag; \
return *this; \ return *this; \
} \ } \
\ \
classname& SetUserMsg(const wxString& msg_user) \ classname& SetUserMsg(std::string msg_user) \
{ \ { \
m_message_user = msg_user; \ m_message_user = std::move(msg_user); \
return *this; \ return *this; \
} }
@ -221,8 +221,8 @@ public: \
bool IsSilent; bool IsSilent;
RuntimeError() { IsSilent = false; } RuntimeError() { IsSilent = false; }
RuntimeError(const std::runtime_error& ex, const wxString& prefix = wxEmptyString); RuntimeError(const std::runtime_error& ex, const char* prefix = nullptr);
RuntimeError(const std::exception& ex, const wxString& prefix = wxEmptyString); RuntimeError(const std::exception& ex, const char* prefix = nullptr);
}; };
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
@ -236,17 +236,17 @@ public: \
// an App message loop we'll still want it to be handled in a reasonably graceful manner. // an App message loop we'll still want it to be handled in a reasonably graceful manner.
class CancelEvent : public RuntimeError class CancelEvent : public RuntimeError
{ {
DEFINE_RUNTIME_EXCEPTION(CancelEvent, RuntimeError, pxLt("No reason given.")) DEFINE_RUNTIME_EXCEPTION(CancelEvent, RuntimeError, "No reason given.")
public: public:
explicit CancelEvent(const wxString& logmsg) explicit CancelEvent(std::string logmsg)
{ {
m_message_diag = logmsg; m_message_diag = std::move(logmsg);
// overridden message formatters only use the diagnostic version... // overridden message formatters only use the diagnostic version...
} }
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
}; };
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
@ -261,21 +261,21 @@ public: \
// //
class OutOfMemory : public RuntimeError class OutOfMemory : public RuntimeError
{ {
DEFINE_RUNTIME_EXCEPTION(OutOfMemory, RuntimeError, wxEmptyString) DEFINE_RUNTIME_EXCEPTION(OutOfMemory, RuntimeError, "")
public: public:
wxString AllocDescription; std::string AllocDescription;
public: public:
OutOfMemory(const wxString& allocdesc); OutOfMemory(std::string allocdesc);
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
}; };
class ParseError : public RuntimeError class ParseError : public RuntimeError
{ {
DEFINE_RUNTIME_EXCEPTION(ParseError, RuntimeError, pxL("Parse error")); DEFINE_RUNTIME_EXCEPTION(ParseError, RuntimeError, "Parse error");
}; };
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
@ -288,18 +288,18 @@ public: \
// we'd really like to have access to. // we'd really like to have access to.
class VirtualMemoryMapConflict : public OutOfMemory class VirtualMemoryMapConflict : public OutOfMemory
{ {
DEFINE_RUNTIME_EXCEPTION(VirtualMemoryMapConflict, OutOfMemory, wxEmptyString) DEFINE_RUNTIME_EXCEPTION(VirtualMemoryMapConflict, OutOfMemory, "")
VirtualMemoryMapConflict(const wxString& allocdesc); VirtualMemoryMapConflict(std::string allocdesc);
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
}; };
class HardwareDeficiency : public RuntimeError class HardwareDeficiency : public RuntimeError
{ {
public: public:
DEFINE_RUNTIME_EXCEPTION(HardwareDeficiency, RuntimeError, pxL("Your machine's hardware is incapable of running PCSX2. Sorry dood.")); DEFINE_RUNTIME_EXCEPTION(HardwareDeficiency, RuntimeError, "Your machine's hardware is incapable of running PCSX2. Sorry dood.");
}; };
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
@ -308,21 +308,21 @@ public: \
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
#define DEFINE_STREAM_EXCEPTION_ACCESSORS(classname) \ #define DEFINE_STREAM_EXCEPTION_ACCESSORS(classname) \
virtual classname& SetStreamName(const wxString& name) \ virtual classname& SetStreamName(std::string name) \
{ \ { \
StreamName = name; \ StreamName = std::move(name); \
return *this; \ return *this; \
} \ } \
\ \
virtual classname& SetStreamName(const char* name) \ virtual classname& SetStreamName(const char* name) \
{ \ { \
StreamName = fromUTF8(name); \ StreamName = name; \
return *this; \ return *this; \
} }
#define DEFINE_STREAM_EXCEPTION(classname, parent) \ #define DEFINE_STREAM_EXCEPTION(classname, parent) \
DEFINE_RUNTIME_EXCEPTION(classname, parent, wxEmptyString) \ DEFINE_RUNTIME_EXCEPTION(classname, parent, "") \
classname(const wxString& filename) \ classname(std::string filename) \
{ \ { \
StreamName = filename; \ StreamName = filename; \
} \ } \
@ -337,14 +337,14 @@ public: \
DEFINE_STREAM_EXCEPTION(BadStream, RuntimeError) DEFINE_STREAM_EXCEPTION(BadStream, RuntimeError)
public: public:
wxString StreamName; // name of the stream (if applicable) std::string StreamName; // name of the stream (if applicable)
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
protected: protected:
void _formatDiagMsg(FastFormatUnicode& dest) const; void _formatDiagMsg(std::string& dest) const;
void _formatUserMsg(FastFormatUnicode& dest) const; void _formatUserMsg(std::string& dest) const;
}; };
// A generic exception for odd-ball stream creation errors. // A generic exception for odd-ball stream creation errors.
@ -353,8 +353,8 @@ public: \
{ {
DEFINE_STREAM_EXCEPTION(CannotCreateStream, BadStream) DEFINE_STREAM_EXCEPTION(CannotCreateStream, BadStream)
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
}; };
// Exception thrown when an attempt to open a non-existent file is made. // Exception thrown when an attempt to open a non-existent file is made.
@ -365,8 +365,8 @@ public: \
public: public:
DEFINE_STREAM_EXCEPTION(FileNotFound, CannotCreateStream) DEFINE_STREAM_EXCEPTION(FileNotFound, CannotCreateStream)
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
}; };
class AccessDenied : public CannotCreateStream class AccessDenied : public CannotCreateStream
@ -374,8 +374,8 @@ public: \
public: public:
DEFINE_STREAM_EXCEPTION(AccessDenied, CannotCreateStream) DEFINE_STREAM_EXCEPTION(AccessDenied, CannotCreateStream)
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
}; };
// EndOfStream can be used either as an error, or used just as a shortcut for manual // EndOfStream can be used either as an error, or used just as a shortcut for manual
@ -386,11 +386,11 @@ public: \
public: public:
DEFINE_STREAM_EXCEPTION(EndOfStream, BadStream) DEFINE_STREAM_EXCEPTION(EndOfStream, BadStream)
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
}; };
#ifdef __WXMSW__ #ifdef _WIN32
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Exception::WinApiError // Exception::WinApiError
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
@ -405,9 +405,9 @@ public: \
public: public:
WinApiError(); WinApiError();
wxString GetMsgFromWindows() const; std::string GetMsgFromWindows() const;
virtual wxString FormatDisplayMessage() const; virtual std::string FormatDisplayMessage() const;
virtual wxString FormatDiagnosticMessage() const; virtual std::string FormatDiagnosticMessage() const;
}; };
#endif #endif
} // namespace Exception } // namespace Exception

View File

@ -21,6 +21,7 @@
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstring>
#ifdef __APPLE__ #ifdef __APPLE__
#include <stdlib.h> #include <stdlib.h>
#else #else

View File

@ -17,6 +17,8 @@
#include "common/Console.h" #include "common/Console.h"
#include "ContextEGL.h" #include "ContextEGL.h"
#include <algorithm>
#include <cstring>
#include <optional> #include <optional>
#include <vector> #include <vector>

View File

@ -16,7 +16,7 @@
#pragma once #pragma once
#include <atomic> #include <atomic>
#include <wx/string.h> #include <string>
#include "common/Pcsx2Defs.h" #include "common/Pcsx2Defs.h"
// This macro is actually useful for about any and every possible application of C++ // This macro is actually useful for about any and every possible application of C++
@ -81,7 +81,7 @@ public:
bool CanExecute() const { return m_exec && m_read; } bool CanExecute() const { return m_exec && m_read; }
bool IsNone() const { return !m_read && !m_write; } bool IsNone() const { return !m_read && !m_write; }
wxString ToString() const; std::string ToString() const;
}; };
static __fi PageProtectionMode PageAccess_None() static __fi PageProtectionMode PageAccess_None()
@ -161,6 +161,6 @@ extern u32 ShortSpin();
/// Number of ns to spin for before sleeping a thread /// Number of ns to spin for before sleeping a thread
extern const u32 SPIN_TIME_NS; extern const u32 SPIN_TIME_NS;
extern wxString GetOSVersionString(); extern std::string GetOSVersionString();
void ScreensaverAllow(bool allow); void ScreensaverAllow(bool allow);

View File

@ -14,15 +14,18 @@
*/ */
#if !defined(_WIN32) #if !defined(_WIN32)
#include <cstdio>
#include <sys/mman.h> #include <sys/mman.h>
#include <signal.h> #include <signal.h>
#include <errno.h> #include <errno.h>
#include <unistd.h> #include <unistd.h>
#include "fmt/core.h"
#include "common/PageFaultSource.h" #include "common/PageFaultSource.h"
#include "common/Assertions.h"
#include "common/Console.h" #include "common/Console.h"
#include "common/Exceptions.h" #include "common/Exceptions.h"
#include "common/StringHelpers.h"
// Apple uses the MAP_ANON define instead of MAP_ANONYMOUS, but they mean // Apple uses the MAP_ANON define instead of MAP_ANONYMOUS, but they mean
// the same thing. // the same thing.
@ -66,10 +69,8 @@ static void SysPageFaultSignalFilter(int signal, siginfo_t* siginfo, void*)
if (Source_PageFault->WasHandled()) if (Source_PageFault->WasHandled())
return; return;
if (!wxThread::IsMain()) std::fprintf(stderr, "Unhandled page fault @ 0x%08x", siginfo->si_addr);
{ pxFailRel("Unhandled page fault");
pxFailRel(pxsFmt("Unhandled page fault @ 0x%08x", siginfo->si_addr));
}
// Bad mojo! Completely invalid address. // Bad mojo! Completely invalid address.
// Instigate a trap if we're in a debugger, and if not then do a SIGKILL. // Instigate a trap if we're in a debugger, and if not then do a SIGKILL.
@ -95,25 +96,12 @@ void _platform_InstallSignalHandler()
#endif #endif
} }
static __ri void PageSizeAssertionTest(size_t size)
{
pxAssertMsg((__pagesize == getpagesize()), pxsFmt(
"Internal system error: Operating system pagesize does not match compiled pagesize.\n\t"
L"\tOS Page Size: 0x%x (%d), Compiled Page Size: 0x%x (%u)",
getpagesize(), getpagesize(), __pagesize, __pagesize));
pxAssertDev((size & (__pagesize - 1)) == 0, pxsFmt(
L"Memory block size must be a multiple of the target platform's page size.\n"
L"\tPage Size: 0x%x (%u), Block Size: 0x%x (%u)",
__pagesize, __pagesize, size, size));
}
// returns FALSE if the mprotect call fails with an ENOMEM. // returns FALSE if the mprotect call fails with an ENOMEM.
// Raises assertions on other types of POSIX errors (since those typically reflect invalid object // Raises assertions on other types of POSIX errors (since those typically reflect invalid object
// or memory states). // or memory states).
static bool _memprotect(void* baseaddr, size_t size, const PageProtectionMode& mode) static bool _memprotect(void* baseaddr, size_t size, const PageProtectionMode& mode)
{ {
PageSizeAssertionTest(size); pxAssertDev((size & (__pagesize - 1)) == 0, "Size is page aligned");
uint lnxmode = 0; uint lnxmode = 0;
@ -132,13 +120,13 @@ static bool _memprotect(void* baseaddr, size_t size, const PageProtectionMode& m
switch (errno) switch (errno)
{ {
case EINVAL: case EINVAL:
pxFailDev(pxsFmt(L"mprotect returned EINVAL @ 0x%08X -> 0x%08X (mode=%s)", pxFailDev(fmt::format("mprotect returned EINVAL @ 0x{:X} -> 0x{:X} (mode={})",
baseaddr, (uptr)baseaddr + size, WX_STR(mode.ToString()))); baseaddr, (uptr)baseaddr + size, mode.ToString()).c_str());
break; break;
case EACCES: case EACCES:
pxFailDev(pxsFmt(L"mprotect returned EACCES @ 0x%08X -> 0x%08X (mode=%s)", pxFailDev(fmt::format("mprotect returned EACCES @ 0x{:X} -> 0x{:X} (mode={})",
baseaddr, (uptr)baseaddr + size, WX_STR(mode.ToString()))); baseaddr, (uptr)baseaddr + size, mode.ToString()).c_str());
break; break;
case ENOMEM: case ENOMEM:
@ -150,7 +138,7 @@ static bool _memprotect(void* baseaddr, size_t size, const PageProtectionMode& m
void* HostSys::MmapReservePtr(void* base, size_t size) void* HostSys::MmapReservePtr(void* base, size_t size)
{ {
PageSizeAssertionTest(size); pxAssertDev((size & (__pagesize - 1)) == 0, "Size is page aligned");
// On linux a reserve-without-commit is performed by using mmap on a read-only // On linux a reserve-without-commit is performed by using mmap on a read-only
// or anonymous source, with PROT_NONE (no-access) permission. Since the mapping // or anonymous source, with PROT_NONE (no-access) permission. Since the mapping
@ -172,21 +160,16 @@ bool HostSys::MmapCommitPtr(void* base, size_t size, const PageProtectionMode& m
if (_memprotect(base, size, mode)) if (_memprotect(base, size, mode))
return true; return true;
if (!pxDoOutOfMemory) return false;
return false;
pxDoOutOfMemory(size);
return _memprotect(base, size, mode);
} }
void HostSys::MmapResetPtr(void* base, size_t size) void HostSys::MmapResetPtr(void* base, size_t size)
{ {
PageSizeAssertionTest(size); pxAssertDev((size & (__pagesize - 1)) == 0, "Size is page aligned");
void* result = mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); void* result = mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
pxAssertRel((uptr)result == (uptr)base, pxsFmt( pxAssertRel((uptr)result == (uptr)base, "Virtual memory decommit failed");
"Virtual memory decommit failed: memory at 0x%08X -> 0x%08X could not be remapped.",
base, (uptr)base + size));
} }
void* HostSys::MmapReserve(uptr base, size_t size) void* HostSys::MmapReserve(uptr base, size_t size)
@ -206,7 +189,7 @@ void HostSys::MmapReset(uptr base, size_t size)
void* HostSys::Mmap(uptr base, size_t size) void* HostSys::Mmap(uptr base, size_t size)
{ {
PageSizeAssertionTest(size); pxAssertDev((size & (__pagesize - 1)) == 0, "Size is page aligned");
// MAP_ANONYMOUS - means we have no associated file handle (or device). // MAP_ANONYMOUS - means we have no associated file handle (or device).
@ -224,9 +207,9 @@ void HostSys::MemProtect(void* baseaddr, size_t size, const PageProtectionMode&
{ {
if (!_memprotect(baseaddr, size, mode)) if (!_memprotect(baseaddr, size, mode))
{ {
throw Exception::OutOfMemory(L"MemProtect") throw Exception::OutOfMemory("MemProtect")
.SetDiagMsg(pxsFmt(L"mprotect failed @ 0x%08X -> 0x%08X (mode=%s)", .SetDiagMsg(fmt::format("mprotect failed @ 0x{:X} -> 0x{:X} (mode={})",
baseaddr, (uptr)baseaddr + size, WX_STR(mode.ToString()))); baseaddr, (uptr)baseaddr + size, mode.ToString()));
} }
} }
#endif #endif

View File

@ -18,9 +18,9 @@
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#include <sys/time.h> #include <sys/time.h>
#include <wx/utils.h>
#include "common/Pcsx2Types.h" #include "common/Pcsx2Types.h"
#include "common/General.h"
// Returns 0 on failure (not supported by the operating system). // Returns 0 on failure (not supported by the operating system).
u64 GetPhysicalMemory() u64 GetPhysicalMemory()
@ -51,12 +51,12 @@ u64 GetCPUTicks()
return (static_cast<u64>(ts.tv_sec) * 1000000000ULL) + ts.tv_nsec; return (static_cast<u64>(ts.tv_sec) * 1000000000ULL) + ts.tv_nsec;
} }
wxString GetOSVersionString() std::string GetOSVersionString()
{ {
#if defined(__linux__) #if defined(__linux__)
return wxGetLinuxDistributionInfo().Description; return "Linux";
#else // freebsd #else // freebsd
return wxGetOsDescription(); return "Other Unix";
#endif #endif
} }

View File

@ -27,9 +27,10 @@
#include "EventSource.h" #include "EventSource.h"
#include "General.h" #include "General.h"
#include "Assertions.h" #include "Assertions.h"
#include "Dependencies.h"
#include <atomic> #include <atomic>
#include <memory>
#include <mutex> #include <mutex>
#include <string>
struct PageFaultInfo struct PageFaultInfo
{ {
@ -135,7 +136,7 @@ class VirtualMemoryManager
{ {
DeclareNoncopyableObject(VirtualMemoryManager); DeclareNoncopyableObject(VirtualMemoryManager);
wxString m_name; std::string m_name;
uptr m_baseptr; uptr m_baseptr;
@ -149,7 +150,7 @@ public:
// If upper_bounds is nonzero and the OS fails to allocate memory that is below it, // If upper_bounds is nonzero and the OS fails to allocate memory that is below it,
// calls to IsOk() will return false and Alloc() will always return null pointers // calls to IsOk() will return false and Alloc() will always return null pointers
// strict indicates that the allocation should quietly fail if the memory can't be mapped at `base` // strict indicates that the allocation should quietly fail if the memory can't be mapped at `base`
VirtualMemoryManager(const wxString& name, uptr base, size_t size, uptr upper_bounds = 0, bool strict = false); VirtualMemoryManager(std::string name, uptr base, size_t size, uptr upper_bounds = 0, bool strict = false);
~VirtualMemoryManager(); ~VirtualMemoryManager();
void* GetBase() const { return (void*)m_baseptr; } void* GetBase() const { return (void*)m_baseptr; }
@ -195,7 +196,7 @@ class VirtualMemoryReserve
DeclareNoncopyableObject(VirtualMemoryReserve); DeclareNoncopyableObject(VirtualMemoryReserve);
protected: protected:
wxString m_name; std::string m_name;
// Where the memory came from (so we can return it) // Where the memory came from (so we can return it)
VirtualMemoryManagerPtr m_allocator; VirtualMemoryManagerPtr m_allocator;
@ -228,7 +229,7 @@ protected:
virtual size_t GetSize(size_t requestedSize); virtual size_t GetSize(size_t requestedSize);
public: public:
VirtualMemoryReserve(const wxString& name, size_t size = 0); VirtualMemoryReserve(std::string name, size_t size = 0);
virtual ~VirtualMemoryReserve() virtual ~VirtualMemoryReserve()
{ {
Release(); Release();
@ -260,7 +261,7 @@ public:
virtual void AllowModification(); virtual void AllowModification();
bool IsOk() const { return m_baseptr != NULL; } bool IsOk() const { return m_baseptr != NULL; }
const wxString& GetName() const { return m_name; } const std::string& GetName() const { return m_name; }
uptr GetReserveSizeInBytes() const { return m_pages_reserved * __pagesize; } uptr GetReserveSizeInBytes() const { return m_pages_reserved * __pagesize; }
uptr GetReserveSizeInPages() const { return m_pages_reserved; } uptr GetReserveSizeInPages() const { return m_pages_reserved; }

View File

@ -15,8 +15,9 @@
#pragma once #pragma once
#include "common/Pcsx2Defs.h"
#include <wx/filename.h> #include <wx/filename.h>
#include "common/StringHelpers.h"
#include "ghc/filesystem.h" #include "ghc/filesystem.h"
@ -43,7 +44,7 @@ public:
: wxFileName(src) : wxFileName(src)
{ {
} }
explicit wxDirName(const char* src) { Assign(fromUTF8(src)); } explicit wxDirName(const char* src) { Assign(wxString(src, wxMBConvUTF8())); }
explicit wxDirName(const wxString& src) { Assign(src); } explicit wxDirName(const wxString& src) { Assign(src); }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -187,14 +188,14 @@ public:
} }
wxDirName& operator=(const char* dirname) wxDirName& operator=(const char* dirname)
{ {
Assign(fromUTF8(dirname)); Assign(wxString(dirname, wxMBConvUTF8()));
return *this; return *this;
} }
wxFileName operator+(const wxFileName& right) const { return Combine(right); } wxFileName operator+(const wxFileName& right) const { return Combine(right); }
wxDirName operator+(const wxDirName& right) const { return Combine(right); } wxDirName operator+(const wxDirName& right) const { return Combine(right); }
wxFileName operator+(const wxString& right) const { return Combine(wxFileName(right)); } wxFileName operator+(const wxString& right) const { return Combine(wxFileName(right)); }
wxFileName operator+(const char* right) const { return Combine(wxFileName(fromUTF8(right))); } wxFileName operator+(const char* right) const { return Combine(wxFileName(wxString(right, wxMBConvUTF8()))); }
bool operator==(const wxDirName& filename) const { return SameAs(filename); } bool operator==(const wxDirName& filename) const { return SameAs(filename); }
bool operator!=(const wxDirName& filename) const { return !SameAs(filename); } bool operator!=(const wxDirName& filename) const { return !SameAs(filename); }

View File

@ -14,6 +14,8 @@
*/ */
#include "common/Path.h" #include "common/Path.h"
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include <wx/file.h> #include <wx/file.h>
#include <wx/utils.h> #include <wx/utils.h>
@ -24,7 +26,7 @@
wxFileName wxDirName::Combine(const wxFileName& right) const wxFileName wxDirName::Combine(const wxFileName& right) const
{ {
pxAssertMsg(IsDir(), L"Warning: Malformed directory name detected during wxDirName concatenation."); pxAssertMsg(IsDir(), "Warning: Malformed directory name detected during wxDirName concatenation.");
if (right.IsAbsolute()) if (right.IsAbsolute())
return right; return right;
@ -39,7 +41,7 @@ wxFileName wxDirName::Combine(const wxFileName& right) const
wxDirName wxDirName::Combine(const wxDirName& right) const wxDirName wxDirName::Combine(const wxDirName& right) const
{ {
pxAssertMsg(IsDir() && right.IsDir(), L"Warning: Malformed directory name detected during wDirName concatenation."); pxAssertMsg(IsDir() && right.IsDir(), "Warning: Malformed directory name detected during wDirName concatenation.");
wxDirName result(right); wxDirName result(right);
result.Normalize(wxPATH_NORM_ENV_VARS | wxPATH_NORM_DOTS | wxPATH_NORM_ABSOLUTE, GetPath()); result.Normalize(wxPATH_NORM_ENV_VARS | wxPATH_NORM_DOTS | wxPATH_NORM_ABSOLUTE, GetPath());
@ -48,25 +50,25 @@ wxDirName wxDirName::Combine(const wxDirName& right) const
wxDirName& wxDirName::Normalize(int flags, const wxString& cwd) wxDirName& wxDirName::Normalize(int flags, const wxString& cwd)
{ {
pxAssertMsg(IsDir(), L"Warning: Malformed directory name detected during wDirName normalization."); pxAssertMsg(IsDir(), "Warning: Malformed directory name detected during wDirName normalization.");
if (!wxFileName::Normalize(flags, cwd)) if (!wxFileName::Normalize(flags, cwd))
throw Exception::ParseError().SetDiagMsg(L"wxDirName::Normalize operation failed."); throw Exception::ParseError().SetDiagMsg("wxDirName::Normalize operation failed.");
return *this; return *this;
} }
wxDirName& wxDirName::MakeRelativeTo(const wxString& pathBase) wxDirName& wxDirName::MakeRelativeTo(const wxString& pathBase)
{ {
pxAssertMsg(IsDir(), L"Warning: Malformed directory name detected during wDirName normalization."); pxAssertMsg(IsDir(), "Warning: Malformed directory name detected during wDirName normalization.");
if (!wxFileName::MakeRelativeTo(pathBase)) if (!wxFileName::MakeRelativeTo(pathBase))
throw Exception::ParseError().SetDiagMsg(L"wxDirName::MakeRelativeTo operation failed."); throw Exception::ParseError().SetDiagMsg("wxDirName::MakeRelativeTo operation failed.");
return *this; return *this;
} }
wxDirName& wxDirName::MakeAbsolute(const wxString& cwd) wxDirName& wxDirName::MakeAbsolute(const wxString& cwd)
{ {
pxAssertMsg(IsDir(), L"Warning: Malformed directory name detected during wDirName normalization."); pxAssertMsg(IsDir(), "Warning: Malformed directory name detected during wDirName normalization.");
if (!wxFileName::MakeAbsolute(cwd)) if (!wxFileName::MakeAbsolute(cwd))
throw Exception::ParseError().SetDiagMsg(L"wxDirName::MakeAbsolute operation failed."); throw Exception::ParseError().SetDiagMsg("wxDirName::MakeAbsolute operation failed.");
return *this; return *this;
} }

View File

@ -188,3 +188,144 @@ static const int __pagesize = PCSX2_PAGESIZE;
#endif #endif
#define ASSERT assert #define ASSERT assert
//////////////////////////////////////////////////////////////////////////////////////////
// Safe deallocation macros -- checks pointer validity (non-null) when needed, and sets
// pointer to null after deallocation.
#define safe_delete(ptr) \
((void)(delete (ptr)), (ptr) = NULL)
#define safe_delete_array(ptr) \
((void)(delete[](ptr)), (ptr) = NULL)
// No checks for NULL -- wxWidgets says it's safe to skip NULL checks and it runs on
// just about every compiler and libc implementation of any recentness.
#define safe_free(ptr) \
((void)(free(ptr), !!0), (ptr) = NULL)
//((void) (( ( (ptr) != NULL ) && (free( ptr ), !!0) ), (ptr) = NULL))
#define safe_fclose(ptr) \
((void)((((ptr) != NULL) && (fclose(ptr), !!0)), (ptr) = NULL))
// --------------------------------------------------------------------------------------
// ImplementEnumOperators (macro)
// --------------------------------------------------------------------------------------
// This macro implements ++/-- operators for any conforming enumeration. In order for an
// enum to conform, it must have _FIRST and _COUNT members defined, and must have a full
// compliment of sequential members (no custom assignments) --- looking like so:
//
// enum Dummy {
// Dummy_FIRST,
// Dummy_Item = Dummy_FIRST,
// Dummy_Crap,
// Dummy_COUNT
// };
//
// The macro also defines utility functions for bounds checking enumerations:
// EnumIsValid(value); // returns TRUE if the enum value is between FIRST and COUNT.
// EnumAssert(value);
//
// It also defines a *prototype* for converting the enumeration to a string. Note that this
// method is not implemented! You must implement it yourself if you want to use it:
// EnumToString(value);
//
#define ImplementEnumOperators(enumName) \
static __fi enumName& operator++(enumName& src) \
{ \
src = (enumName)((int)src + 1); \
return src; \
} \
\
static __fi enumName& operator--(enumName& src) \
{ \
src = (enumName)((int)src - 1); \
return src; \
} \
\
static __fi enumName operator++(enumName& src, int) \
{ \
enumName orig = src; \
src = (enumName)((int)src + 1); \
return orig; \
} \
\
static __fi enumName operator--(enumName& src, int) \
{ \
enumName orig = src; \
src = (enumName)((int)src - 1); \
return orig; \
} \
\
static __fi bool operator<(const enumName& left, const pxEnumEnd_t&) { return (int)left < enumName##_COUNT; } \
static __fi bool operator!=(const enumName& left, const pxEnumEnd_t&) { return (int)left != enumName##_COUNT; } \
static __fi bool operator==(const enumName& left, const pxEnumEnd_t&) { return (int)left == enumName##_COUNT; } \
\
static __fi bool EnumIsValid(enumName id) \
{ \
return ((int)id >= enumName##_FIRST) && ((int)id < enumName##_COUNT); \
} \
\
extern const char* EnumToString(enumName id)
class pxEnumEnd_t
{
};
static const pxEnumEnd_t pxEnumEnd = {};
// --------------------------------------------------------------------------------------
// DeclareNoncopyableObject
// --------------------------------------------------------------------------------------
// This macro provides an easy and clean method for ensuring objects are not copyable.
// Simply add the macro to the head or tail of your class declaration, and attempts to
// copy the class will give you a moderately obtuse compiler error that will have you
// scratching your head for 20 minutes.
//
// (... but that's probably better than having a weird invalid object copy having you
// scratch your head for a day).
//
// Programmer's notes:
// * We intentionally do NOT provide implementations for these methods, which should
// never be referenced anyway.
// * I've opted for macro form over multi-inherited class form (Boost style), because
// the errors generated by the macro are considerably less voodoo. The Boost-style
// The macro reports the exact class that causes the copy failure, while Boost's class
// approach just reports an error in whatever "NoncopyableObject" is inherited.
//
// * This macro is the same as wxWidgets' DECLARE_NO_COPY_CLASS macro. This one is free
// of wx dependencies though, and has a nicer typeset. :)
//
#ifndef DeclareNoncopyableObject
#define DeclareNoncopyableObject(classname) \
public: \
classname(const classname&) = delete; \
classname& operator=(const classname&) = delete
#endif
// --------------------------------------------------------------------------------------
// Handy Human-readable constants for common immediate values (_16kb -> _4gb)
static constexpr sptr _1kb = 1024 * 1;
static constexpr sptr _4kb = _1kb * 4;
static constexpr sptr _16kb = _1kb * 16;
static constexpr sptr _32kb = _1kb * 32;
static constexpr sptr _64kb = _1kb * 64;
static constexpr sptr _128kb = _1kb * 128;
static constexpr sptr _256kb = _1kb * 256;
static constexpr s64 _1mb = 1024 * 1024;
static constexpr s64 _8mb = _1mb * 8;
static constexpr s64 _16mb = _1mb * 16;
static constexpr s64 _32mb = _1mb * 32;
static constexpr s64 _64mb = _1mb * 64;
static constexpr s64 _256mb = _1mb * 256;
static constexpr s64 _1gb = _1mb * 1024;
static constexpr s64 _4gb = _1gb * 4;
// Disable some spammy warnings which wx appeared to disable.
// We probably should fix these at some point.
#ifdef _MSC_VER
#pragma warning(disable: 4244) // warning C4244: 'initializing': conversion from 'uptr' to 'uint', possible loss of data
#pragma warning(disable: 4267) // warning C4267: 'initializing': conversion from 'size_t' to 'uint', possible loss of data
#endif

View File

@ -17,16 +17,6 @@
#include <cstdint> #include <cstdint>
// --------------------------------------------------------------------------------------
// Forward declarations
// --------------------------------------------------------------------------------------
// Forward declarations for wxWidgets-supporting features.
// If you aren't linking against wxWidgets libraries, then functions that
// depend on these types will not be usable (they will yield linker errors).
class wxString;
class FastFormatAscii;
class FastFormatUnicode;
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// Basic Atomic Types // Basic Atomic Types
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
@ -99,17 +89,6 @@ union u128
{ {
return (lo != right.lo) || (hi != right.hi); return (lo != right.lo) || (hi != right.hi);
} }
// In order for the following ToString() and WriteTo methods to be available, you must
// be linking to both wxWidgets and the pxWidgets extension library. If you are not
// using them, then you will need to provide your own implementations of these methods.
wxString ToString() const;
wxString ToString64() const;
wxString ToString8() const;
void WriteTo(FastFormatAscii& dest) const;
void WriteTo8(FastFormatAscii& dest) const;
void WriteTo64(FastFormatAscii& dest) const;
}; };
struct s128 struct s128

View File

@ -14,8 +14,7 @@
*/ */
#include "common/Perf.h" #include "common/Perf.h"
#include "common/Pcsx2Types.h" #include "common/Pcsx2Defs.h"
#include "common/Dependencies.h"
#ifdef __unix__ #ifdef __unix__
#include <unistd.h> #include <unistd.h>
#endif #endif

View File

@ -18,6 +18,3 @@
#include <csignal> #include <csignal>
#include <cerrno> #include <cerrno>
#include <cstdio> #include <cstdio>
#include <wx/string.h>
#include <wx/gdicmn.h>

View File

@ -24,10 +24,12 @@
#define NOMINMAX #define NOMINMAX
#endif #endif
// Win8.1 is our minimum at the moment.
#define _WIN32_WINNT 0x0603 // Windows 8.1
#include <windows.h> #include <windows.h>
#include <VersionHelpers.h> #include <VersionHelpers.h>
#include <ShTypes.h> #include <ShTypes.h>
#include <timeapi.h> #include <timeapi.h>
#include <wx/msw/wrapwin.h>
#endif #endif

View File

@ -15,7 +15,7 @@
#pragma once #pragma once
#include "common/Dependencies.h" #include "common/Pcsx2Defs.h"
// pxUSE_SECURE_MALLOC - enables bounds checking on scoped malloc allocations. // pxUSE_SECURE_MALLOC - enables bounds checking on scoped malloc allocations.
@ -43,7 +43,7 @@ public:
static const int DefaultChunkSize = 0x1000 * sizeof(T); static const int DefaultChunkSize = 0x1000 * sizeof(T);
public: public:
wxString Name; // user-assigned block name std::string Name; // user-assigned block name
int ChunkSize; int ChunkSize;
protected: protected:
@ -51,7 +51,7 @@ protected:
int m_size; // size of the allocation of memory int m_size; // size of the allocation of memory
protected: protected:
SafeArray(const wxChar* name, T* allocated_mem, int initSize); SafeArray(std::string name, T* allocated_mem, int initSize);
virtual T* _virtual_realloc(int newsize); virtual T* _virtual_realloc(int newsize);
// A safe array index fetcher. Asserts if the index is out of bounds (dev and debug // A safe array index fetcher. Asserts if the index is out of bounds (dev and debug
@ -61,8 +61,8 @@ protected:
public: public:
virtual ~SafeArray(); virtual ~SafeArray();
explicit SafeArray(const wxChar* name = L"Unnamed"); explicit SafeArray(std::string name = "Unnamed");
explicit SafeArray(int initialSize, const wxChar* name = L"Unnamed"); explicit SafeArray(int initialSize, std::string name = "Unnamed");
void Dispose(); void Dispose();
void ExactAlloc(int newsize); void ExactAlloc(int newsize);
@ -124,7 +124,7 @@ public:
static const int DefaultChunkSize = 0x80 * sizeof(T); static const int DefaultChunkSize = 0x80 * sizeof(T);
public: public:
wxString Name; // user-assigned block name std::string Name; // user-assigned block name
int ChunkSize; // assigned DefaultChunkSize on init, reconfigurable at any time. int ChunkSize; // assigned DefaultChunkSize on init, reconfigurable at any time.
protected: protected:
@ -140,8 +140,8 @@ protected:
public: public:
virtual ~SafeList(); virtual ~SafeList();
explicit SafeList(const wxChar* name = L"Unnamed"); explicit SafeList(const char* name = "Unnamed");
explicit SafeList(int initialSize, const wxChar* name = L"Unnamed"); explicit SafeList(int initialSize, const char* name = "Unnamed");
virtual SafeList<T>* Clone() const; virtual SafeList<T>* Clone() const;
void Remove(int index); void Remove(int index);
@ -207,11 +207,11 @@ public:
virtual ~SafeAlignedArray(); virtual ~SafeAlignedArray();
explicit SafeAlignedArray(const wxChar* name = L"Unnamed") explicit SafeAlignedArray(std::string name = "Unnamed")
: SafeArray<T>::SafeArray(name) : SafeArray<T>::SafeArray(name)
{ {
} }
explicit SafeAlignedArray(int initialSize, const wxChar* name = L"Unnamed"); explicit SafeAlignedArray(int initialSize, std::string name = "Unnamed");
virtual SafeAlignedArray<T, Alignment>* Clone() const; virtual SafeAlignedArray<T, Alignment>* Clone() const;
}; };

View File

@ -15,16 +15,20 @@
#pragma once #pragma once
#include "common/AlignedMalloc.h"
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include "common/SafeArray.h" #include "common/SafeArray.h"
#include "common/StringHelpers.h"
#include "fmt/core.h"
// Internal constructor for use by derived classes. This allows a derived class to // Internal constructor for use by derived classes. This allows a derived class to
// use its own memory allocation (with an aligned memory, for example). // use its own memory allocation (with an aligned memory, for example).
// Throws: // Throws:
// Exception::OutOfMemory if the allocated_mem pointer is NULL. // Exception::OutOfMemory if the allocated_mem pointer is NULL.
template <typename T> template <typename T>
SafeArray<T>::SafeArray(const wxChar* name, T* allocated_mem, int initSize) SafeArray<T>::SafeArray(std::string name, T* allocated_mem, int initSize)
: Name(name) : Name(std::move(name))
{ {
ChunkSize = DefaultChunkSize; ChunkSize = DefaultChunkSize;
m_ptr = allocated_mem; m_ptr = allocated_mem;
@ -32,7 +36,7 @@ SafeArray<T>::SafeArray(const wxChar* name, T* allocated_mem, int initSize)
if (m_ptr == NULL) if (m_ptr == NULL)
throw Exception::OutOfMemory(name) throw Exception::OutOfMemory(name)
.SetDiagMsg(wxsFormat(L"Called from 'SafeArray::ctor' [size=%d]", initSize)); .SetDiagMsg(fmt::format("Called from 'SafeArray::ctor' [size={}]", initSize));
} }
template <typename T> template <typename T>
@ -63,8 +67,8 @@ SafeArray<T>::~SafeArray()
} }
template <typename T> template <typename T>
SafeArray<T>::SafeArray(const wxChar* name) SafeArray<T>::SafeArray(std::string name)
: Name(name) : Name(std::move(name))
{ {
ChunkSize = DefaultChunkSize; ChunkSize = DefaultChunkSize;
m_ptr = NULL; m_ptr = NULL;
@ -72,8 +76,8 @@ SafeArray<T>::SafeArray(const wxChar* name)
} }
template <typename T> template <typename T>
SafeArray<T>::SafeArray(int initialSize, const wxChar* name) SafeArray<T>::SafeArray(int initialSize, std::string name)
: Name(name) : Name(std::move(name))
{ {
ChunkSize = DefaultChunkSize; ChunkSize = DefaultChunkSize;
m_ptr = (initialSize == 0) ? NULL : (T*)malloc(initialSize * sizeof(T)); m_ptr = (initialSize == 0) ? NULL : (T*)malloc(initialSize * sizeof(T));
@ -81,7 +85,7 @@ SafeArray<T>::SafeArray(int initialSize, const wxChar* name)
if ((initialSize != 0) && (m_ptr == NULL)) if ((initialSize != 0) && (m_ptr == NULL))
throw Exception::OutOfMemory(name) throw Exception::OutOfMemory(name)
.SetDiagMsg(wxsFormat(L"Called from 'SafeArray::ctor' [size=%d]", initialSize)); .SetDiagMsg(fmt::format("Called from 'SafeArray::ctor' [size={}]", initialSize));
} }
// Clears the contents of the array to zero, and frees all memory allocations. // Clears the contents of the array to zero, and frees all memory allocations.
@ -95,7 +99,7 @@ void SafeArray<T>::Dispose()
template <typename T> template <typename T>
T* SafeArray<T>::_getPtr(uint i) const T* SafeArray<T>::_getPtr(uint i) const
{ {
IndexBoundsAssumeDev(WX_STR(Name), i, m_size); pxAssumeDev(i < static_cast<uint>(m_size), "Array index in bounds");
return &m_ptr[i]; return &m_ptr[i];
} }
@ -110,7 +114,7 @@ void SafeArray<T>::ExactAlloc(int newsize)
m_ptr = _virtual_realloc(newsize); m_ptr = _virtual_realloc(newsize);
if (m_ptr == NULL) if (m_ptr == NULL)
throw Exception::OutOfMemory(Name) throw Exception::OutOfMemory(Name)
.SetDiagMsg(wxsFormat(L"Called from 'SafeArray::ExactAlloc' [oldsize=%d] [newsize=%d]", m_size, newsize)); .SetDiagMsg(fmt::format("Called from 'SafeArray::ExactAlloc' [oldsize={}] [newsize={}]", m_size, newsize));
m_size = newsize; m_size = newsize;
} }
@ -147,9 +151,9 @@ SafeAlignedArray<T, Alignment>::~SafeAlignedArray()
} }
template <typename T, uint Alignment> template <typename T, uint Alignment>
SafeAlignedArray<T, Alignment>::SafeAlignedArray(int initialSize, const wxChar* name) SafeAlignedArray<T, Alignment>::SafeAlignedArray(int initialSize, std::string name)
: SafeArray<T>::SafeArray( : SafeArray<T>::SafeArray(
name, std::move(name),
(T*)_aligned_malloc(initialSize * sizeof(T), Alignment), (T*)_aligned_malloc(initialSize * sizeof(T), Alignment),
initialSize) initialSize)
{ {
@ -180,7 +184,7 @@ SafeList<T>::~SafeList()
} }
template <typename T> template <typename T>
SafeList<T>::SafeList(const wxChar* name) SafeList<T>::SafeList(const char* name)
: Name(name) : Name(name)
{ {
ChunkSize = DefaultChunkSize; ChunkSize = DefaultChunkSize;
@ -190,7 +194,7 @@ SafeList<T>::SafeList(const wxChar* name)
} }
template <typename T> template <typename T>
SafeList<T>::SafeList(int initialSize, const wxChar* name) SafeList<T>::SafeList(int initialSize, const char* name)
: Name(name) : Name(name)
{ {
ChunkSize = DefaultChunkSize; ChunkSize = DefaultChunkSize;
@ -200,7 +204,7 @@ SafeList<T>::SafeList(int initialSize, const wxChar* name)
if (m_ptr == NULL) if (m_ptr == NULL)
throw Exception::OutOfMemory(Name) throw Exception::OutOfMemory(Name)
.SetDiagMsg(wxsFormat(L"called from 'SafeList::ctor' [length=%d]", m_length)); .SetDiagMsg(fmt::format("called from 'SafeList::ctor' [length={}]", m_length));
for (int i = 0; i < m_allocsize; ++i) for (int i = 0; i < m_allocsize; ++i)
{ {
@ -211,7 +215,7 @@ SafeList<T>::SafeList(int initialSize, const wxChar* name)
template <typename T> template <typename T>
T* SafeList<T>::_getPtr(uint i) const T* SafeList<T>::_getPtr(uint i) const
{ {
IndexBoundsAssumeDev(WX_STR(Name), i, m_length); pxAssumeDev(i < m_length, "Index in bounds");
return &m_ptr[i]; return &m_ptr[i];
} }
@ -226,7 +230,7 @@ void SafeList<T>::MakeRoomFor(int blockSize)
m_ptr = _virtual_realloc(newalloc); m_ptr = _virtual_realloc(newalloc);
if (m_ptr == NULL) if (m_ptr == NULL)
throw Exception::OutOfMemory(Name) throw Exception::OutOfMemory(Name)
.SetDiagMsg(wxsFormat(L"Called from 'SafeList::MakeRoomFor' [oldlen=%d] [newlen=%d]", m_length, blockSize)); .SetDiagMsg(fmt::format("Called from 'SafeList::MakeRoomFor' [oldlen={}] [newlen={}]", m_length, blockSize));
for (; m_allocsize < newalloc; ++m_allocsize) for (; m_allocsize < newalloc; ++m_allocsize)
{ {
@ -266,7 +270,7 @@ T& SafeList<T>::AddNew(const T& src)
template <typename T> template <typename T>
void SafeList<T>::Remove(int index) void SafeList<T>::Remove(int index)
{ {
IndexBoundsAssumeDev(Name.c_str(), index, m_length); pxAssert(index < m_length);
int copylen = m_length - index; int copylen = m_length - index;
if (copylen > 0) if (copylen > 0)

View File

@ -17,11 +17,6 @@
#include "SettingsInterface.h" #include "SettingsInterface.h"
// TODO(Stenzek): Remove when wx goes bye bye.
#include <wx/gdicmn.h>
#include "Path.h"
// Helper class which loads or saves depending on the derived class. // Helper class which loads or saves depending on the derived class.
class SettingsWrapper class SettingsWrapper
{ {

View File

@ -21,6 +21,8 @@
#include <sstream> #include <sstream>
#include <algorithm> #include <algorithm>
#include "fmt/core.h"
#ifdef _WIN32 #ifdef _WIN32
#include "RedtapeWindows.h" #include "RedtapeWindows.h"
#endif #endif
@ -321,6 +323,25 @@ namespace StringUtil
return true; return true;
} }
void AppendUTF16CharacterToUTF8(std::string& s, u16 ch)
{
if (ch & 0xf800)
{
s.push_back(static_cast<char>(static_cast<u8>(0xe0 | static_cast<u8>(ch >> 12))));
s.push_back(static_cast<char>(static_cast<u8>(0x80 | static_cast<u8>(((ch >> 6) & 0x3f)))));
s.push_back(static_cast<char>(static_cast<u8>(0x80 | static_cast<u8>((ch & 0x3f)))));
}
else if (ch & 0xff80)
{
s.push_back(static_cast<char>(static_cast<u8>(0xc0 | static_cast<u8>((ch >> 6)))));
s.push_back(static_cast<char>(static_cast<u8>(0x80 | static_cast<u8>((ch & 0x3f)))));
}
else
{
s.push_back(static_cast<char>(static_cast<u8>(ch)));
}
}
std::wstring UTF8StringToWideString(const std::string_view& str) std::wstring UTF8StringToWideString(const std::string_view& str)
{ {
std::wstring ret; std::wstring ret;
@ -402,4 +423,15 @@ namespace StringUtil
return true; return true;
#endif #endif
} }
std::string U128ToString(const u128& u)
{
return fmt::format("0x{:08X}.{:08X}.{:08X}.{:08X}", u._u32[0], u._u32[1], u._u32[2], u._u32[3]);
}
std::string& AppendU128ToString(const u128& u, std::string& s)
{
fmt::format_to(std::back_inserter(s), "0x{:08X}.{:08X}.{:08X}.{:08X}", u._u32[0], u._u32[1], u._u32[2], u._u32[3]);
return s;
}
} // namespace StringUtil } // namespace StringUtil

View File

@ -174,6 +174,9 @@ namespace StringUtil
/// Parses an assignment string (Key = Value) into its two components. /// Parses an assignment string (Key = Value) into its two components.
bool ParseAssignmentString(const std::string_view& str, std::string_view* key, std::string_view* value); bool ParseAssignmentString(const std::string_view& str, std::string_view* key, std::string_view* value);
/// Appends a UTF-16/UTF-32 codepoint to a UTF-8 string.
void AppendUTF16CharacterToUTF8(std::string& s, u16 ch);
/// Strided memcpy/memcmp. /// Strided memcpy/memcmp.
static inline void StrideMemCpy(void* dst, std::size_t dst_stride, const void* src, std::size_t src_stride, static inline void StrideMemCpy(void* dst, std::size_t dst_stride, const void* src, std::size_t src_stride,
std::size_t copy_size, std::size_t count) std::size_t copy_size, std::size_t count)
@ -244,4 +247,8 @@ namespace StringUtil
/// Converts the specified wide string to a UTF-8 string. /// Converts the specified wide string to a UTF-8 string.
std::string WideStringToUTF8String(const std::wstring_view& str); std::string WideStringToUTF8String(const std::wstring_view& str);
bool WideStringToUTF8String(std::string& dest, const std::wstring_view& str); bool WideStringToUTF8String(std::string& dest, const std::wstring_view& str);
/// Converts unsigned 128-bit data to string.
std::string U128ToString(const u128& u);
std::string& AppendU128ToString(const u128& u, std::string& s);
} // namespace StringUtil } // namespace StringUtil

View File

@ -16,6 +16,8 @@
#pragma once #pragma once
#include "Console.h" #include "Console.h"
#include "common/Assertions.h"
#include "common/StringUtil.h"
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// TraceLogDescriptor // TraceLogDescriptor
@ -26,15 +28,15 @@
struct TraceLogDescriptor struct TraceLogDescriptor
{ {
// short name, alphanumerics only: used for saving/loading options. // short name, alphanumerics only: used for saving/loading options.
const wxChar* ShortName; const char* ShortName;
// Standard UI name for this log source. Used in menus, options dialogs. // Standard UI name for this log source. Used in menus, options dialogs.
const wxChar* Name; const char* Name;
// Length description for use as a tooltip or menu item description. // Length description for use as a tooltip or menu item description.
const wxChar* Description; const char* Description;
wxString GetShortName() const const char* GetShortName() const
{ {
pxAssumeDev(Name, "Tracelog descriptors require a valid name!"); pxAssumeDev(Name, "Tracelog descriptors require a valid name!");
return ShortName ? ShortName : Name; return ShortName ? ShortName : Name;
@ -90,18 +92,18 @@ public:
// Provides a categorical identifier, typically in "group.subgroup.subgroup" form. // Provides a categorical identifier, typically in "group.subgroup.subgroup" form.
// (use periods in favor of colons, since they do not require escape characters when // (use periods in favor of colons, since they do not require escape characters when
// written to ini/config files). // written to ini/config files).
virtual wxString GetCategory() const { return wxEmptyString; } virtual std::string GetCategory() const { return std::string(); }
// This method should be used to determine if a log should be generated or not. // This method should be used to determine if a log should be generated or not.
// See the class overview comments for details on how and why this method should // See the class overview comments for details on how and why this method should
// be used. // be used.
virtual bool IsActive() const { return Enabled; } virtual bool IsActive() const { return Enabled; }
virtual wxString GetShortName() const { return m_Descriptor->GetShortName(); } virtual const char* GetShortName() const { return m_Descriptor->GetShortName(); }
virtual const wxChar* GetName() const { return m_Descriptor->Name; } virtual const char* GetName() const { return m_Descriptor->Name; }
virtual const wxChar* GetDescription() const virtual const char* GetDescription() const
{ {
return (m_Descriptor->Description != NULL) ? pxGetTranslation(m_Descriptor->Description) : wxEmptyString; return (m_Descriptor->Description != NULL) ? m_Descriptor->Description : "";
} }
virtual bool HasDescription() const { return m_Descriptor->Description != NULL; } virtual bool HasDescription() const { return m_Descriptor->Description != NULL; }
@ -133,14 +135,14 @@ public:
bool WriteV(const char* fmt, va_list list) const bool WriteV(const char* fmt, va_list list) const
{ {
FastFormatAscii ascii; std::string ascii;
ApplyPrefix(ascii); ApplyPrefix(ascii);
ascii.WriteV(fmt, list); ascii += StringUtil::StdStringFromFormatV(fmt, list);
DoWrite(ascii); DoWrite(ascii.c_str());
return false; return false;
} }
virtual void ApplyPrefix(FastFormatAscii& ascii) const {} virtual void ApplyPrefix(std::string& ascii) const {}
virtual void DoWrite(const char* fmt) const = 0; virtual void DoWrite(const char* fmt) const = 0;
}; };
@ -181,26 +183,6 @@ public:
return false; return false;
} }
bool Write(const wxChar* fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(fmt, list);
va_end(list);
return false;
}
bool Write(const wxString fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(fmt.wx_str(), list);
va_end(list);
return false;
}
// Writes to the console using the specified color. This overrides the default color setting // Writes to the console using the specified color. This overrides the default color setting
// for this log. // for this log.
bool Write(ConsoleColors color, const char* fmt, ...) const bool Write(ConsoleColors color, const char* fmt, ...) const
@ -213,68 +195,7 @@ public:
return false; return false;
} }
bool Write(ConsoleColors color, const wxChar* fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(color, fmt, list);
va_end(list);
return false;
}
// Writes to the console using bold yellow text -- overrides the log source's default
// color settings.
bool Warn(const wxChar* fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(Color_StrongYellow, fmt, list);
va_end(list);
return false;
}
bool Warn(const wxString fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(Color_StrongYellow, fmt.wx_str(), list);
va_end(list);
return false;
}
// Writes to the console using bold red text -- overrides the log source's default
// color settings.
bool Error(const wxChar* fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(Color_StrongRed, fmt, list);
va_end(list);
return false;
}
bool Error(const wxString fmt, ...) const
{
va_list list;
va_start(list, fmt);
WriteV(Color_StrongRed, fmt.wx_str(), list);
va_end(list);
return false;
}
bool WriteV(const char* fmt, va_list list) const; bool WriteV(const char* fmt, va_list list) const;
bool WriteV(const wxChar* fmt, va_list list) const;
bool WriteV(ConsoleColors color, const char* fmt, va_list list) const; bool WriteV(ConsoleColors color, const char* fmt, va_list list) const;
bool WriteV(ConsoleColors color, const wxChar* fmt, va_list list) const;
virtual void DoWrite(const wxChar* msg) const
{
Console.DoWriteLn(msg);
}
}; };

View File

@ -18,6 +18,10 @@
#include "common/MemsetFast.inl" #include "common/MemsetFast.inl"
#include "common/Console.h" #include "common/Console.h"
#include "fmt/core.h"
#include <cinttypes>
template class EventSource<IEventListener_PageFault>; template class EventSource<IEventListener_PageFault>;
SrcType_PageFault* Source_PageFault = NULL; SrcType_PageFault* Source_PageFault = NULL;
@ -73,8 +77,8 @@ static size_t pageAlign(size_t size)
// VirtualMemoryManager (implementations) // VirtualMemoryManager (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
VirtualMemoryManager::VirtualMemoryManager(const wxString& name, uptr base, size_t size, uptr upper_bounds, bool strict) VirtualMemoryManager::VirtualMemoryManager(std::string name, uptr base, size_t size, uptr upper_bounds, bool strict)
: m_name(name) : m_name(std::move(name))
, m_baseptr(0) , m_baseptr(0)
, m_pageuse(nullptr) , m_pageuse(nullptr)
, m_pages_reserved(0) , m_pages_reserved(0)
@ -89,8 +93,8 @@ VirtualMemoryManager::VirtualMemoryManager(const wxString& name, uptr base, size
if (!m_baseptr || (upper_bounds != 0 && (((uptr)m_baseptr + reserved_bytes) > upper_bounds))) if (!m_baseptr || (upper_bounds != 0 && (((uptr)m_baseptr + reserved_bytes) > upper_bounds)))
{ {
DevCon.Warning(L"%s: host memory @ %ls -> %ls is unavailable; attempting to map elsewhere...", DevCon.Warning("%s: host memory @ 0x%016" PRIXPTR " -> 0x%016" PRIXPTR " is unavailable; attempting to map elsewhere...",
WX_STR(m_name), pxsPtr(base), pxsPtr(base + size)); m_name.c_str(), base, base + size);
SafeSysMunmap(m_baseptr, reserved_bytes); SafeSysMunmap(m_baseptr, reserved_bytes);
@ -117,15 +121,15 @@ VirtualMemoryManager::VirtualMemoryManager(const wxString& name, uptr base, size
m_pageuse = new std::atomic<bool>[m_pages_reserved](); m_pageuse = new std::atomic<bool>[m_pages_reserved]();
FastFormatUnicode mbkb; std::string mbkb;
uint mbytes = reserved_bytes / _1mb; uint mbytes = reserved_bytes / _1mb;
if (mbytes) if (mbytes)
mbkb.Write("[%umb]", mbytes); mbkb = fmt::format("[{}mb]", mbytes);
else else
mbkb.Write("[%ukb]", reserved_bytes / 1024); mbkb = fmt::format("[{}kb]", reserved_bytes / 1024);
DevCon.WriteLn(Color_Gray, L"%-32s @ %ls -> %ls %ls", WX_STR(m_name), DevCon.WriteLn(Color_Gray, "%-32s @ 0x%016" PRIXPTR " -> 0x%016" PRIXPTR " %s", m_name.c_str(),
pxsPtr(m_baseptr), pxsPtr((uptr)m_baseptr + reserved_bytes), mbkb.c_str()); m_baseptr, (uptr)m_baseptr + reserved_bytes, mbkb.c_str());
} }
VirtualMemoryManager::~VirtualMemoryManager() VirtualMemoryManager::~VirtualMemoryManager()
@ -231,8 +235,8 @@ void* VirtualMemoryBumpAllocator::Alloc(size_t size)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// VirtualMemoryReserve (implementations) // VirtualMemoryReserve (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
VirtualMemoryReserve::VirtualMemoryReserve(const wxString& name, size_t size) VirtualMemoryReserve::VirtualMemoryReserve(std::string name, size_t size)
: m_name(name) : m_name(std::move(name))
{ {
m_defsize = size; m_defsize = size;
@ -283,15 +287,15 @@ void* VirtualMemoryReserve::Assign(VirtualMemoryManagerPtr allocator, void* base
if (!m_baseptr) if (!m_baseptr)
return nullptr; return nullptr;
FastFormatUnicode mbkb; std::string mbkb;
uint mbytes = reserved_bytes / _1mb; uint mbytes = reserved_bytes / _1mb;
if (mbytes) if (mbytes)
mbkb.Write("[%umb]", mbytes); mbkb = fmt::format("[{}mb]", mbytes);
else else
mbkb.Write("[%ukb]", reserved_bytes / 1024); mbkb = fmt::format("[{}kb]", reserved_bytes / 1024);
DevCon.WriteLn(Color_Gray, L"%-32s @ %ls -> %ls %ls", WX_STR(m_name), DevCon.WriteLn(Color_Gray, "%-32s @ 0x%016" PRIXPTR " -> 0x%016" PRIXPTR " %s", m_name.c_str(),
pxsPtr(m_baseptr), pxsPtr((uptr)m_baseptr + reserved_bytes), mbkb.c_str()); m_baseptr, (uptr)m_baseptr + reserved_bytes, mbkb.c_str());
return m_baseptr; return m_baseptr;
} }
@ -365,16 +369,16 @@ bool VirtualMemoryReserve::TryResize(uint newsize)
uint toReservePages = newPages - m_pages_reserved; uint toReservePages = newPages - m_pages_reserved;
uint toReserveBytes = toReservePages * __pagesize; uint toReserveBytes = toReservePages * __pagesize;
DevCon.WriteLn(L"%-32s is being expanded by %u pages.", WX_STR(m_name), toReservePages); DevCon.WriteLn("%-32s is being expanded by %u pages.", m_name.c_str(), toReservePages);
if (!m_allocator->AllocAtAddress(GetPtrEnd(), toReserveBytes)) if (!m_allocator->AllocAtAddress(GetPtrEnd(), toReserveBytes))
{ {
Console.Warning("%-32s could not be passively resized due to virtual memory conflict!", WX_STR(m_name)); Console.Warning("%-32s could not be passively resized due to virtual memory conflict!", m_name.c_str());
Console.Indent().Warning("(attempted to map memory @ %08p -> %08p)", m_baseptr, (uptr)m_baseptr + toReserveBytes); Console.Indent().Warning("(attempted to map memory @ %08p -> %08p)", m_baseptr, (uptr)m_baseptr + toReserveBytes);
return false; return false;
} }
DevCon.WriteLn(Color_Gray, L"%-32s @ %08p -> %08p [%umb]", WX_STR(m_name), DevCon.WriteLn(Color_Gray, "%-32s @ %08p -> %08p [%umb]", m_name.c_str(),
m_baseptr, (uptr)m_baseptr + toReserveBytes, toReserveBytes / _1mb); m_baseptr, (uptr)m_baseptr + toReserveBytes, toReserveBytes / _1mb);
} }
else if (newPages < m_pages_reserved) else if (newPages < m_pages_reserved)
@ -385,11 +389,11 @@ bool VirtualMemoryReserve::TryResize(uint newsize)
uint toRemovePages = m_pages_reserved - newPages; uint toRemovePages = m_pages_reserved - newPages;
uint toRemoveBytes = toRemovePages * __pagesize; uint toRemoveBytes = toRemovePages * __pagesize;
DevCon.WriteLn(L"%-32s is being shrunk by %u pages.", WX_STR(m_name), toRemovePages); DevCon.WriteLn("%-32s is being shrunk by %u pages.", m_name.c_str(), toRemovePages);
m_allocator->Free(GetPtrEnd() - toRemoveBytes, toRemoveBytes); m_allocator->Free(GetPtrEnd() - toRemoveBytes, toRemoveBytes);
DevCon.WriteLn(Color_Gray, L"%-32s @ %08p -> %08p [%umb]", WX_STR(m_name), DevCon.WriteLn(Color_Gray, "%-32s @ %08p -> %08p [%umb]", m_name.c_str(),
m_baseptr, GetPtrEnd(), GetReserveSizeInBytes() / _1mb); m_baseptr, GetPtrEnd(), GetReserveSizeInBytes() / _1mb);
} }
@ -400,21 +404,21 @@ bool VirtualMemoryReserve::TryResize(uint newsize)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
// PageProtectionMode (implementations) // PageProtectionMode (implementations)
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
wxString PageProtectionMode::ToString() const std::string PageProtectionMode::ToString() const
{ {
wxString modeStr; std::string modeStr;
if (m_read) if (m_read)
modeStr += L"Read"; modeStr += "Read";
if (m_write) if (m_write)
modeStr += L"Write"; modeStr += "Write";
if (m_exec) if (m_exec)
modeStr += L"Exec"; modeStr += "Exec";
if (modeStr.IsEmpty()) if (modeStr.empty())
return L"NoAccess"; return "NoAccess";
if (modeStr.Length() <= 5) if (modeStr.length() <= 5)
modeStr += L"Only"; modeStr += "Only";
return modeStr; return modeStr;
} }

View File

@ -18,6 +18,9 @@
#include "common/RedtapeWindows.h" #include "common/RedtapeWindows.h"
#include "common/PageFaultSource.h" #include "common/PageFaultSource.h"
#include "common/Console.h" #include "common/Console.h"
#include "common/Exceptions.h"
#include "common/StringUtil.h"
#include "common/AlignedMalloc.h"
static long DoSysPageFaultExceptionFilter(EXCEPTION_POINTERS* eps) static long DoSysPageFaultExceptionFilter(EXCEPTION_POINTERS* eps)
{ {
@ -97,14 +100,11 @@ bool HostSys::MmapCommitPtr(void* base, size_t size, const PageProtectionMode& m
} }
else if (errcode != ERROR_NOT_ENOUGH_MEMORY && errcode != ERROR_OUTOFMEMORY) else if (errcode != ERROR_NOT_ENOUGH_MEMORY && errcode != ERROR_OUTOFMEMORY)
{ {
pxFailDev(L"VirtualAlloc COMMIT failed: " + Exception::WinApiError().GetMsgFromWindows()); pxFailDev(("VirtualAlloc COMMIT failed: " + Exception::WinApiError().GetMsgFromWindows()).c_str());
return false; return false;
} }
if (!pxDoOutOfMemory) return false;
return false;
pxDoOutOfMemory(size);
return VirtualAlloc(base, size, MEM_COMMIT, ConvertToWinApi(mode)) != NULL;
} }
void HostSys::MmapResetPtr(void* base, size_t size) void HostSys::MmapResetPtr(void* base, size_t size)
@ -144,10 +144,7 @@ void HostSys::Munmap(uptr base, size_t size)
void HostSys::MemProtect(void* baseaddr, size_t size, const PageProtectionMode& mode) void HostSys::MemProtect(void* baseaddr, size_t size, const PageProtectionMode& mode)
{ {
pxAssertDev(((size & (__pagesize - 1)) == 0), pxsFmt( pxAssert((size & (__pagesize - 1)) == 0);
L"Memory block size must be a multiple of the target platform's page size.\n"
L"\tPage Size: 0x%04x (%d), Block Size: 0x%04x (%d)",
__pagesize, __pagesize, size, size));
DWORD OldProtect; // enjoy my uselessness, yo! DWORD OldProtect; // enjoy my uselessness, yo!
if (!VirtualProtect(baseaddr, size, ConvertToWinApi(mode), &OldProtect)) if (!VirtualProtect(baseaddr, size, ConvertToWinApi(mode), &OldProtect))
@ -155,10 +152,10 @@ void HostSys::MemProtect(void* baseaddr, size_t size, const PageProtectionMode&
Exception::WinApiError apiError; Exception::WinApiError apiError;
apiError.SetDiagMsg( apiError.SetDiagMsg(
pxsFmt(L"VirtualProtect failed @ 0x%08X -> 0x%08X (mode=%s)", StringUtil::StdStringFromFormat("VirtualProtect failed @ 0x%08X -> 0x%08X (mode=%s)",
baseaddr, (uptr)baseaddr + size, mode.ToString().c_str())); baseaddr, (uptr)baseaddr + size, mode.ToString().c_str()));
pxFailDev(apiError.FormatDiagnosticMessage()); pxFailDev(apiError.FormatDiagnosticMessage().c_str());
} }
} }
#endif #endif

View File

@ -15,11 +15,12 @@
#if defined(_WIN32) #if defined(_WIN32)
#include <wx/string.h>
#include "common/Pcsx2Defs.h" #include "common/Pcsx2Defs.h"
#include "common/RedtapeWindows.h" #include "common/RedtapeWindows.h"
#include "common/Exceptions.h" #include "common/Exceptions.h"
#include "common/Dependencies.h" #include "common/StringUtil.h"
#include "fmt/core.h"
#pragma comment(lib, "User32.lib") #pragma comment(lib, "User32.lib")
@ -52,27 +53,26 @@ u64 GetPhysicalMemory()
// Calculates the Windows OS Version and processor architecture, and returns it as a // Calculates the Windows OS Version and processor architecture, and returns it as a
// human-readable string. :) // human-readable string. :)
wxString GetOSVersionString() std::string GetOSVersionString()
{ {
wxString retval; std::string retval;
SYSTEM_INFO si; SYSTEM_INFO si;
GetNativeSystemInfo(&si); GetNativeSystemInfo(&si);
if (!IsWindows8Point1OrGreater()) if (!IsWindows8Point1OrGreater())
return L"Unsupported Operating System!"; {
retval = "Unsupported Operating System!";
}
else
{
retval = "Microsoft ";
retval += L"Microsoft "; if (IsWindows10OrGreater())
retval += IsWindowsServer() ? "Windows Server 2016" : "Windows 10";
if (IsWindows10OrGreater()) else // IsWindows8Point1OrGreater()
retval += IsWindowsServer() ? L"Windows Server 2016" : L"Windows 10"; retval += IsWindowsServer() ? "Windows Server 2012 R2" : "Windows 8.1";
else // IsWindows8Point1OrGreater() }
retval += IsWindowsServer() ? L"Windows Server 2012 R2" : L"Windows 8.1";
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
retval += L", 64-bit";
else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
retval += L", 32-bit";
return retval; return retval;
} }
@ -83,30 +83,30 @@ wxString GetOSVersionString()
Exception::WinApiError::WinApiError() Exception::WinApiError::WinApiError()
{ {
ErrorId = GetLastError(); ErrorId = GetLastError();
m_message_diag = L"Unspecified Windows API error."; m_message_diag = "Unspecified Windows API error.";
} }
wxString Exception::WinApiError::GetMsgFromWindows() const std::string Exception::WinApiError::GetMsgFromWindows() const
{ {
if (!ErrorId) if (!ErrorId)
return L"No valid error number was assigned to this exception!"; return "No valid error number was assigned to this exception!";
const DWORD BUF_LEN = 2048; const DWORD BUF_LEN = 2048;
TCHAR t_Msg[BUF_LEN]; wchar_t t_Msg[BUF_LEN];
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, ErrorId, 0, t_Msg, BUF_LEN, 0)) if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, 0, ErrorId, 0, t_Msg, BUF_LEN, 0))
return wxsFormat(L"Win32 Error #%d: %s", ErrorId, t_Msg); return fmt::format("Win32 Error #{}: {}", ErrorId, StringUtil::WideStringToUTF8String(t_Msg));
return wxsFormat(L"Win32 Error #%d (no text msg available)", ErrorId); return fmt::format("Win32 Error #{} (no text msg available)", ErrorId);
} }
wxString Exception::WinApiError::FormatDisplayMessage() const std::string Exception::WinApiError::FormatDisplayMessage() const
{ {
return m_message_user + L"\n\n" + GetMsgFromWindows(); return m_message_user + "\n\n" + GetMsgFromWindows();
} }
wxString Exception::WinApiError::FormatDiagnosticMessage() const std::string Exception::WinApiError::FormatDiagnosticMessage() const
{ {
return m_message_diag + L"\n\t" + GetMsgFromWindows(); return m_message_diag + "\n\t" + GetMsgFromWindows();
} }
void ScreensaverAllow(bool allow) void ScreensaverAllow(bool allow)

View File

@ -45,6 +45,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
#include <atomic> #include <atomic>
#include "AlignedMalloc.h"
template <typename T, size_t max_size> template <typename T, size_t max_size>
class ringbuffer_base class ringbuffer_base

View File

@ -55,7 +55,6 @@
<ClCompile Include="D3D12\Texture.cpp" /> <ClCompile Include="D3D12\Texture.cpp" />
<ClCompile Include="D3D12\Util.cpp" /> <ClCompile Include="D3D12\Util.cpp" />
<ClCompile Include="Exceptions.cpp" /> <ClCompile Include="Exceptions.cpp" />
<ClCompile Include="FastFormatString.cpp" />
<ClCompile Include="FastJmp.cpp"> <ClCompile Include="FastJmp.cpp">
<ExcludedFromBuild>true</ExcludedFromBuild> <ExcludedFromBuild>true</ExcludedFromBuild>
</ClCompile> </ClCompile>
@ -67,7 +66,6 @@
<ClCompile Include="FileSystem.cpp" /> <ClCompile Include="FileSystem.cpp" />
<ClCompile Include="MD5Digest.cpp" /> <ClCompile Include="MD5Digest.cpp" />
<ClCompile Include="ProgressCallback.cpp" /> <ClCompile Include="ProgressCallback.cpp" />
<ClCompile Include="pxTranslate.cpp" />
<ClCompile Include="StackWalker.cpp" /> <ClCompile Include="StackWalker.cpp" />
<ClCompile Include="StringUtil.cpp" /> <ClCompile Include="StringUtil.cpp" />
<ClCompile Include="SettingsWrapper.cpp" /> <ClCompile Include="SettingsWrapper.cpp" />
@ -89,7 +87,6 @@
<ClCompile Include="PrecompiledHeader.cpp"> <ClCompile Include="PrecompiledHeader.cpp">
<PrecompiledHeader>Create</PrecompiledHeader> <PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile> </ClCompile>
<ClCompile Include="StringHelpers.cpp" />
<ClCompile Include="Linux\LnxHostSys.cpp" /> <ClCompile Include="Linux\LnxHostSys.cpp" />
<ClCompile Include="Linux\LnxMisc.cpp" /> <ClCompile Include="Linux\LnxMisc.cpp" />
<ClCompile Include="Linux\LnxThreads.cpp" /> <ClCompile Include="Linux\LnxThreads.cpp" />
@ -130,7 +127,6 @@
<ClInclude Include="D3D12\StreamBuffer.h" /> <ClInclude Include="D3D12\StreamBuffer.h" />
<ClInclude Include="D3D12\Texture.h" /> <ClInclude Include="D3D12\Texture.h" />
<ClInclude Include="D3D12\Util.h" /> <ClInclude Include="D3D12\Util.h" />
<ClInclude Include="EmbeddedImage.h" />
<ClInclude Include="boost_spsc_queue.hpp" /> <ClInclude Include="boost_spsc_queue.hpp" />
<ClInclude Include="FastJmp.h" /> <ClInclude Include="FastJmp.h" />
<ClInclude Include="GL\Context.h" /> <ClInclude Include="GL\Context.h" />
@ -149,7 +145,6 @@
<ClInclude Include="SettingsWrapper.h" /> <ClInclude Include="SettingsWrapper.h" />
<ClInclude Include="Assertions.h" /> <ClInclude Include="Assertions.h" />
<ClInclude Include="Console.h" /> <ClInclude Include="Console.h" />
<ClInclude Include="Dependencies.h" />
<ClInclude Include="EventSource.h" /> <ClInclude Include="EventSource.h" />
<ClInclude Include="Exceptions.h" /> <ClInclude Include="Exceptions.h" />
<ClInclude Include="General.h" /> <ClInclude Include="General.h" />
@ -159,7 +154,6 @@
<ClInclude Include="PrecompiledHeader.h" /> <ClInclude Include="PrecompiledHeader.h" />
<ClInclude Include="RedtapeWindows.h" /> <ClInclude Include="RedtapeWindows.h" />
<ClInclude Include="SafeArray.h" /> <ClInclude Include="SafeArray.h" />
<ClInclude Include="StringHelpers.h" />
<ClInclude Include="Timer.h" /> <ClInclude Include="Timer.h" />
<ClInclude Include="Vulkan\Builders.h" /> <ClInclude Include="Vulkan\Builders.h" />
<ClInclude Include="Vulkan\Context.h" /> <ClInclude Include="Vulkan\Context.h" />

View File

@ -16,9 +16,6 @@
<ClCompile Include="Exceptions.cpp"> <ClCompile Include="Exceptions.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="FastFormatString.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="emitter\fpu.cpp"> <ClCompile Include="emitter\fpu.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
@ -61,18 +58,12 @@
<ClCompile Include="PrecompiledHeader.cpp"> <ClCompile Include="PrecompiledHeader.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="pxTranslate.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Semaphore.cpp"> <ClCompile Include="Semaphore.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="emitter\simd.cpp"> <ClCompile Include="emitter\simd.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="StringHelpers.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="VirtualMemory.cpp"> <ClCompile Include="VirtualMemory.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
@ -216,15 +207,9 @@
<ClInclude Include="emitter\cpudetect_internal.h"> <ClInclude Include="emitter\cpudetect_internal.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="Dependencies.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="emitter\implement\dwshift.h"> <ClInclude Include="emitter\implement\dwshift.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="EmbeddedImage.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="EventSource.h"> <ClInclude Include="EventSource.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
@ -321,9 +306,6 @@
<ClInclude Include="emitter\implement\xchg.h"> <ClInclude Include="emitter\implement\xchg.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="StringHelpers.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="FastJmp.h"> <ClInclude Include="FastJmp.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>

View File

@ -141,20 +141,20 @@ s64 x86capabilities::_CPUSpeedHz(u64 time) const
return (s64)newCycleCount; return (s64)newCycleCount;
} }
wxString x86capabilities::GetTypeName() const const char* x86capabilities::GetTypeName() const
{ {
switch (TypeID) switch (TypeID)
{ {
case 0: case 0:
return L"Standard OEM"; return "Standard OEM";
case 1: case 1:
return L"Overdrive"; return "Overdrive";
case 2: case 2:
return L"Dual"; return "Dual";
case 3: case 3:
return L"Reserved"; return "Reserved";
default: default:
return L"Unknown"; return "Unknown";
} }
} }

View File

@ -27,6 +27,7 @@
#include "common/emitter/legacy_internal.h" #include "common/emitter/legacy_internal.h"
#include "common/Console.h" #include "common/Console.h"
#include <cassert>
emitterT void ModRM(uint mod, uint reg, uint rm) emitterT void ModRM(uint mod, uint reg, uint rm)
{ {

View File

@ -15,7 +15,7 @@
#pragma once #pragma once
#include "common/Dependencies.h" #include "common/Pcsx2Defs.h"
enum x86VendorType enum x86VendorType
{ {
@ -114,7 +114,7 @@ public:
void Identify(); void Identify();
void CountCores(); void CountCores();
wxString GetTypeName() const; const char* GetTypeName() const;
static u32 CachedMHz(); static u32 CachedMHz();
u32 CalculateMHz() const; u32 CalculateMHz() const;

View File

@ -30,6 +30,7 @@
#include "common/emitter/internal.h" #include "common/emitter/internal.h"
#include "common/emitter/tools.h" #include "common/emitter/tools.h"
#include <functional>
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Notes on Thread Local Storage: // Notes on Thread Local Storage:
@ -707,7 +708,7 @@ const xRegister32
else if (Index.IsEmpty()) else if (Index.IsEmpty())
Index = src; Index = src;
else else
pxAssumeDev(false, L"x86Emitter: address modifiers cannot have more than two index registers."); // oops, only 2 regs allowed per ModRm! pxAssumeDev(false, "x86Emitter: address modifiers cannot have more than two index registers."); // oops, only 2 regs allowed per ModRm!
return *this; return *this;
} }
@ -732,7 +733,7 @@ const xRegister32
Factor += src.Factor; Factor += src.Factor;
} }
else else
pxAssumeDev(false, L"x86Emitter: address modifiers cannot have more than two index registers."); // oops, only 2 regs allowed per ModRm! pxAssumeDev(false, "x86Emitter: address modifiers cannot have more than two index registers."); // oops, only 2 regs allowed per ModRm!
return *this; return *this;
} }

View File

@ -1,51 +0,0 @@
/* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// --------------------------------------------------------------------------------------
// Forward Declarations Section
// --------------------------------------------------------------------------------------
class wxOutputStream;
class wxFileOutputStream;
class wxFFileOutputStream;
class wxStreamBase;
class wxInputStream;
class wxFileInputStream;
class wxFFileInputStream;
class wxPoint;
class wxRect;
class wxSize;
class pxInputStream;
class pxOutputStream;
extern const wxSize wxDefaultSize;
extern const wxPoint wxDefaultPosition;
namespace Threading
{
class Mutex;
class Semaphore;
class pxThread;
} // namespace Threading
namespace Exception
{
class BaseException;
}

View File

@ -15,6 +15,8 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include "DisplayWidget.h" #include "DisplayWidget.h"
#include "EmuThread.h" #include "EmuThread.h"
#include "MainWindow.h" #include "MainWindow.h"

View File

@ -15,6 +15,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
#include "pcsx2/Frontend/GameList.h" #include "pcsx2/Frontend/GameList.h"

View File

@ -23,6 +23,7 @@
#include <QtWidgets/QStyle> #include <QtWidgets/QStyle>
#include <QtWidgets/QStyleFactory> #include <QtWidgets/QStyleFactory>
#include "common/Assertions.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include "pcsx2/CDVD/CDVDaccess.h" #include "pcsx2/CDVD/CDVDaccess.h"

View File

@ -542,9 +542,9 @@ static HANDLE s_old_console_stdin = NULL;
static HANDLE s_old_console_stdout = NULL; static HANDLE s_old_console_stdout = NULL;
static HANDLE s_old_console_stderr = NULL; static HANDLE s_old_console_stderr = NULL;
static void ConsoleWinQt_SetTitle(const wxString& title) static void ConsoleWinQt_SetTitle(const char* title)
{ {
SetConsoleTitleW(title.wc_str()); SetConsoleTitleW(StringUtil::UTF8StringToWideString(title).c_str());
} }
static void ConsoleWinQt_DoSetColor(ConsoleColors color) static void ConsoleWinQt_DoSetColor(ConsoleColors color)
@ -593,31 +593,37 @@ static void ConsoleWinQt_Newline()
WriteConsoleW(s_console_handle, L"\n", 1, &written, nullptr); WriteConsoleW(s_console_handle, L"\n", 1, &written, nullptr);
} }
static void ConsoleWinQt_DoWrite(const wxString& fmt) static void ConsoleWinQt_DoWrite(const char* fmt)
{ {
if (!s_console_handle) if (!s_console_handle)
return; return;
// TODO: Put this on the stack.
std::wstring wfmt(StringUtil::UTF8StringToWideString(fmt));
if (s_debugger_attached) if (s_debugger_attached)
OutputDebugStringW(fmt.wc_str()); OutputDebugStringW(wfmt.c_str());
DWORD written; DWORD written;
WriteConsoleW(s_console_handle, fmt.wc_str(), static_cast<DWORD>(fmt.size()), &written, nullptr); WriteConsoleW(s_console_handle, wfmt.c_str(), static_cast<DWORD>(wfmt.length()), &written, nullptr);
} }
static void ConsoleWinQt_DoWriteLn(const wxString& fmt) static void ConsoleWinQt_DoWriteLn(const char* fmt)
{ {
if (!s_console_handle) if (!s_console_handle)
return; return;
// TODO: Put this on the stack.
std::wstring wfmt(StringUtil::UTF8StringToWideString(fmt));
if (s_debugger_attached) if (s_debugger_attached)
{ {
OutputDebugStringW(fmt.wc_str()); OutputDebugStringW(wfmt.c_str());
OutputDebugStringW(L"\n"); OutputDebugStringW(L"\n");
} }
DWORD written; DWORD written;
WriteConsoleW(s_console_handle, fmt.wc_str(), static_cast<DWORD>(fmt.size()), &written, nullptr); WriteConsoleW(s_console_handle, wfmt.c_str(), static_cast<DWORD>(wfmt.length()), &written, nullptr);
WriteConsoleW(s_console_handle, L"\n", 1, &written, nullptr); WriteConsoleW(s_console_handle, L"\n", 1, &written, nullptr);
} }

View File

@ -22,6 +22,7 @@
#include <memory> #include <memory>
class INISettingsInterface; class INISettingsInterface;
class SettingsInterface;
namespace GameList namespace GameList
{ {

View File

@ -16,6 +16,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "AsyncFileReader.h" #include "AsyncFileReader.h"
#include "IsoFileFormats.h" #include "IsoFileFormats.h"
#include "common/Assertions.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include <errno.h> #include <errno.h>

View File

@ -230,8 +230,8 @@ static void cdvdNVM(u8* buffer, int offset, size_t bytes, bool read)
ret = std::fwrite(buffer, 1, bytes, fp.get()); ret = std::fwrite(buffer, 1, bytes, fp.get());
if (ret != bytes) if (ret != bytes)
Console.Error(L"Failed to %s %s. Did only %zu/%zu bytes", Console.Error("Failed to %s %s. Did only %zu/%zu bytes",
read ? L"read from" : L"write to", nvmfile.c_str(), ret, bytes); read ? "read from" : "write to", nvmfile.c_str(), ret, bytes);
} }
static void cdvdReadNVM(u8* dst, int offset, int bytes) static void cdvdReadNVM(u8* dst, int offset, int bytes)
@ -639,7 +639,7 @@ static void cdvdUpdateReady(u8 NewReadyStatus)
s32 cdvdCtrlTrayOpen() s32 cdvdCtrlTrayOpen()
{ {
DevCon.WriteLn(Color_Green, L"Open virtual disk tray"); DevCon.WriteLn(Color_Green, "Open virtual disk tray");
// If we switch using a source change we need to pretend it's a new disc // If we switch using a source change we need to pretend it's a new disc
if (CDVDsys_GetSourceType() == CDVD_SourceType::Disc) if (CDVDsys_GetSourceType() == CDVD_SourceType::Disc)
@ -660,7 +660,7 @@ s32 cdvdCtrlTrayOpen()
{ {
cdvd.Tray.cdvdActionSeconds = 3; cdvd.Tray.cdvdActionSeconds = 3;
cdvd.Tray.trayState = CDVD_DISC_EJECT; cdvd.Tray.trayState = CDVD_DISC_EJECT;
DevCon.WriteLn(Color_Green, L"Simulating ejected media"); DevCon.WriteLn(Color_Green, "Simulating ejected media");
} }
return 0; // needs to be 0 for success according to homebrew test "CDVD" return 0; // needs to be 0 for success according to homebrew test "CDVD"
@ -668,11 +668,11 @@ s32 cdvdCtrlTrayOpen()
s32 cdvdCtrlTrayClose() s32 cdvdCtrlTrayClose()
{ {
DevCon.WriteLn(Color_Green, L"Close virtual disk tray"); DevCon.WriteLn(Color_Green, "Close virtual disk tray");
if (!g_GameStarted && g_SkipBiosHack) if (!g_GameStarted && g_SkipBiosHack)
{ {
DevCon.WriteLn(Color_Green, L"Media already loaded (fast boot)"); DevCon.WriteLn(Color_Green, "Media already loaded (fast boot)");
cdvdUpdateReady(CDVD_DRIVE_READY); cdvdUpdateReady(CDVD_DRIVE_READY);
cdvdUpdateStatus(CDVD_STATUS_PAUSE); cdvdUpdateStatus(CDVD_STATUS_PAUSE);
cdvd.Tray.trayState = CDVD_DISC_ENGAGED; cdvd.Tray.trayState = CDVD_DISC_ENGAGED;
@ -680,7 +680,7 @@ s32 cdvdCtrlTrayClose()
} }
else else
{ {
DevCon.WriteLn(Color_Green, L"Detecting media"); DevCon.WriteLn(Color_Green, "Detecting media");
cdvdUpdateReady(CDVD_DRIVE_BUSY); cdvdUpdateReady(CDVD_DRIVE_BUSY);
cdvdUpdateStatus(CDVD_STATUS_SEEK); cdvdUpdateStatus(CDVD_STATUS_SEEK);
cdvd.Tray.trayState = CDVD_DISC_DETECTING; cdvd.Tray.trayState = CDVD_DISC_DETECTING;
@ -914,7 +914,7 @@ void cdvdNewDiskCB()
// If not ejected but we've swapped source pretend it got ejected // If not ejected but we've swapped source pretend it got ejected
if ((g_GameStarted || !g_SkipBiosHack) && cdvd.Tray.trayState != CDVD_DISC_EJECT) if ((g_GameStarted || !g_SkipBiosHack) && cdvd.Tray.trayState != CDVD_DISC_EJECT)
{ {
DevCon.WriteLn(Color_Green, L"Ejecting media"); DevCon.WriteLn(Color_Green, "Ejecting media");
cdvdUpdateStatus(CDVD_STATUS_TRAY_OPEN); cdvdUpdateStatus(CDVD_STATUS_TRAY_OPEN);
cdvdUpdateReady(CDVD_DRIVE_BUSY); cdvdUpdateReady(CDVD_DRIVE_BUSY);
cdvd.Tray.trayState = CDVD_DISC_EJECT; cdvd.Tray.trayState = CDVD_DISC_EJECT;
@ -926,7 +926,7 @@ void cdvdNewDiskCB()
} }
else if (cdvd.Type > 0) else if (cdvd.Type > 0)
{ {
DevCon.WriteLn(Color_Green, L"Seeking new media"); DevCon.WriteLn(Color_Green, "Seeking new media");
cdvdUpdateReady(CDVD_DRIVE_BUSY); cdvdUpdateReady(CDVD_DRIVE_BUSY);
cdvdUpdateStatus(CDVD_STATUS_SEEK); cdvdUpdateStatus(CDVD_STATUS_SEEK);
cdvd.Spinning = true; cdvd.Spinning = true;
@ -1390,7 +1390,7 @@ void cdvdUpdateTrayState()
cdvdCtrlTrayClose(); cdvdCtrlTrayClose();
break; break;
case CDVD_DISC_DETECTING: case CDVD_DISC_DETECTING:
DevCon.WriteLn(Color_Green, L"Seeking new disc"); DevCon.WriteLn(Color_Green, "Seeking new disc");
cdvd.Tray.trayState = CDVD_DISC_SEEKING; cdvd.Tray.trayState = CDVD_DISC_SEEKING;
cdvd.Tray.cdvdActionSeconds = 2; cdvd.Tray.cdvdActionSeconds = 2;
cdvd.Spinning = true; cdvd.Spinning = true;
@ -1401,7 +1401,7 @@ void cdvdUpdateTrayState()
cdvdUpdateReady(CDVD_DRIVE_READY); cdvdUpdateReady(CDVD_DRIVE_READY);
if (CDVDsys_GetSourceType() != CDVD_SourceType::NoDisc) if (CDVDsys_GetSourceType() != CDVD_SourceType::NoDisc)
{ {
DevCon.WriteLn(Color_Green, L"Media ready to read"); DevCon.WriteLn(Color_Green, "Media ready to read");
cdvdUpdateStatus(CDVD_STATUS_PAUSE); cdvdUpdateStatus(CDVD_STATUS_PAUSE);
} }
else else
@ -1871,7 +1871,7 @@ static void cdvdWrite04(u8 rt)
cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.ReadMode, cdvd.NCMDParam[10], cdvd.SpindlCtrl); cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.ReadMode, cdvd.NCMDParam[10], cdvd.SpindlCtrl);
if (EmuConfig.CdvdVerboseReads) if (EmuConfig.CdvdVerboseReads)
Console.WriteLn(Color_Gray, L"CDRead: Reading Sector %07d (%03d Blocks of Size %d) at Speed=%dx(%s) Spindle=%x", Console.WriteLn(Color_Gray, "CDRead: Reading Sector %07d (%03d Blocks of Size %d) at Speed=%dx(%s) Spindle=%x",
cdvd.SeekToSector, cdvd.nSectors, cdvd.BlockSize, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.SpindlCtrl); cdvd.SeekToSector, cdvd.nSectors, cdvd.BlockSize, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.SpindlCtrl);
cdvd.ReadTime = cdvdBlockReadTime((CDVD_MODE_TYPE)cdvdIsDVD()); cdvd.ReadTime = cdvdBlockReadTime((CDVD_MODE_TYPE)cdvdIsDVD());
@ -1970,7 +1970,7 @@ static void cdvdWrite04(u8 rt)
cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.ReadMode, cdvd.NCMDParam[10], cdvd.SpindlCtrl); cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.ReadMode, cdvd.NCMDParam[10], cdvd.SpindlCtrl);
if (EmuConfig.CdvdVerboseReads) if (EmuConfig.CdvdVerboseReads)
Console.WriteLn(Color_Gray, L"CdAudioRead: Reading Sector %07d (%03d Blocks of Size %d) at Speed=%dx(%s) Spindle=%x", Console.WriteLn(Color_Gray, "CdAudioRead: Reading Sector %07d (%03d Blocks of Size %d) at Speed=%dx(%s) Spindle=%x",
cdvd.Sector, cdvd.nSectors, cdvd.BlockSize, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.SpindlCtrl); cdvd.Sector, cdvd.nSectors, cdvd.BlockSize, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.SpindlCtrl);
cdvd.ReadTime = cdvdBlockReadTime(MODE_CDROM); cdvd.ReadTime = cdvdBlockReadTime(MODE_CDROM);
@ -2066,7 +2066,7 @@ static void cdvdWrite04(u8 rt)
cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.ReadMode, cdvd.NCMDParam[10], cdvd.SpindlCtrl); cdvd.Sector, cdvd.SeekToSector, cdvd.nSectors, cdvd.RetryCnt, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.ReadMode, cdvd.NCMDParam[10], cdvd.SpindlCtrl);
if (EmuConfig.CdvdVerboseReads) if (EmuConfig.CdvdVerboseReads)
Console.WriteLn(Color_Gray, L"DvdRead: Reading Sector %07d (%03d Blocks of Size %d) at Speed=%dx(%s) SpindleCtrl=%x", Console.WriteLn(Color_Gray, "DvdRead: Reading Sector %07d (%03d Blocks of Size %d) at Speed=%dx(%s) SpindleCtrl=%x",
cdvd.SeekToSector, cdvd.nSectors, cdvd.BlockSize, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.SpindlCtrl); cdvd.SeekToSector, cdvd.nSectors, cdvd.BlockSize, cdvd.Speed, (cdvd.SpindlCtrl & CDVD_SPINDLE_CAV) ? L"CAV" : L"CLV", cdvd.SpindlCtrl);
cdvd.ReadTime = cdvdBlockReadTime(MODE_DVDROM); cdvd.ReadTime = cdvdBlockReadTime(MODE_DVDROM);

View File

@ -32,6 +32,8 @@
#include "IsoFS/IsoFSCDVD.h" #include "IsoFS/IsoFSCDVD.h"
#include "IsoFileFormats.h" #include "IsoFileFormats.h"
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
#include "DebugTools/SymbolMap.h" #include "DebugTools/SymbolMap.h"
@ -39,13 +41,6 @@
CDVD_API* CDVD = NULL; CDVD_API* CDVD = NULL;
const wxChar* CDVD_SourceLabels[] =
{
L"ISO",
L"Disc",
L"NoDisc",
NULL};
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// diskTypeCached // diskTypeCached
// Internal disc type cache, to reduce the overhead of disc type checks, which are // Internal disc type cache, to reduce the overhead of disc type checks, which are

View File

@ -154,8 +154,6 @@ extern CDVD_API CDVDapi_Iso;
extern CDVD_API CDVDapi_Disc; extern CDVD_API CDVDapi_Disc;
extern CDVD_API CDVDapi_NoDisc; extern CDVD_API CDVDapi_NoDisc;
extern const wxChar* CDVD_SourceLabels[];
extern void CDVDsys_ChangeSource(CDVD_SourceType type); extern void CDVDsys_ChangeSource(CDVD_SourceType type);
extern void CDVDsys_SetFile(CDVD_SourceType srctype, std::string newfile); extern void CDVDsys_SetFile(CDVD_SourceType srctype, std::string newfile);
extern const std::string& CDVDsys_GetFile(CDVD_SourceType srctype); extern const std::string& CDVDsys_GetFile(CDVD_SourceType srctype);

View File

@ -18,6 +18,8 @@
#include "CDVD/CDVD.h" #include "CDVD/CDVD.h"
#include <condition_variable> #include <condition_variable>
#include <mutex>
#include <thread>
void (*newDiscCB)(); void (*newDiscCB)();

View File

@ -24,6 +24,7 @@
#include "IsoFileFormats.h" #include "IsoFileFormats.h"
#include "AsyncFileReader.h" #include "AsyncFileReader.h"
#include "CDVD/CDVD.h" #include "CDVD/CDVD.h"
#include "common/Exceptions.h"
#include <cstring> #include <cstring>
#include <array> #include <array>

View File

@ -16,6 +16,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "ChdFileReader.h" #include "ChdFileReader.h"
#include "common/Assertions.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
@ -114,7 +115,7 @@ bool ChdFileReader::Open2(std::string fileName)
if (error != CHDERR_NONE) if (error != CHDERR_NONE)
{ {
Console.Error(L"CDVD: chd_open return error: %s", chd_error_string(error)); Console.Error("CDVD: chd_open return error: %s", chd_error_string(error));
return false; return false;
} }
@ -131,7 +132,7 @@ bool ChdFileReader::Open2(std::string fileName)
error = chd_open_wrapper(chds[d].c_str(), &fp, CHD_OPEN_READ, parent, &child); error = chd_open_wrapper(chds[d].c_str(), &fp, CHD_OPEN_READ, parent, &child);
if (error != CHDERR_NONE) if (error != CHDERR_NONE)
{ {
Console.Error(L"CDVD: chd_open return error: %s", chd_error_string(error)); Console.Error("CDVD: chd_open return error: %s", chd_error_string(error));
if (parent) if (parent)
chd_close(parent); chd_close(parent);
return false; return false;
@ -175,7 +176,7 @@ int ChdFileReader::ReadChunk(void* dst, s64 chunkID)
chd_error error = chd_read(ChdFile, chunkID, dst); chd_error error = chd_read(ChdFile, chunkID, dst);
if (error != CHDERR_NONE) if (error != CHDERR_NONE)
{ {
Console.Error(L"CDVD: chd_read returned error: %s", chd_error_string(error)); Console.Error("CDVD: chd_read returned error: %s", chd_error_string(error));
return 0; return 0;
} }

View File

@ -20,6 +20,7 @@
#include "CsoFileReader.h" #include "CsoFileReader.h"
#include "GzippedFileReader.h" #include "GzippedFileReader.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include <algorithm>
#include <cctype> #include <cctype>
// CompressedFileReader factory. // CompressedFileReader factory.

View File

@ -114,7 +114,7 @@ static wxString INDEX_TEMPLATE_KEY(L"$(f)");
// then it's relative to base (not to cwd) // then it's relative to base (not to cwd)
// No checks are performed if the result file name can be created. // No checks are performed if the result file name can be created.
// If this proves useful, we can move it into Path:: . Right now there's no need. // If this proves useful, we can move it into Path:: . Right now there's no need.
static wxString ApplyTemplate(const wxString& name, const wxDirName& base, static wxString ApplyTemplate(const std::string& name, const wxDirName& base,
const std::string& fileTemplate, const std::string& filename, const std::string& fileTemplate, const std::string& filename,
bool canEndWithKey) bool canEndWithKey)
{ {
@ -127,9 +127,9 @@ static wxString ApplyTemplate(const wxString& name, const wxDirName& base,
|| first != tem.rfind(key) // more than one instance || first != tem.rfind(key) // more than one instance
|| !canEndWithKey && first == tem.length() - key.length()) || !canEndWithKey && first == tem.length() - key.length())
{ {
Console.Error(L"Invalid %s template '%s'.\n" Console.Error("Invalid %s template '%s'.\n"
L"Template must contain exactly one '%s' and must not end with it. Abotring.", "Template must contain exactly one '%s' and must not end with it. Abotring.",
WX_STR(name), WX_STR(tem), WX_STR(key)); name.c_str(), tem.ToUTF8().data(), key.ToUTF8().data());
return L""; return L"";
} }
@ -181,7 +181,7 @@ static std::string iso2indexname(const std::string& isoname)
const wxDirName& appRoot = EmuFolders::DataRoot; const wxDirName& appRoot = EmuFolders::DataRoot;
#endif #endif
//TestTemplate(appRoot, isoname, false); //TestTemplate(appRoot, isoname, false);
return StringUtil::wxStringToUTF8String(ApplyTemplate(L"gzip index", appRoot, EmuConfig.GzipIsoIndexTemplate, isoname, false)); return StringUtil::wxStringToUTF8String(ApplyTemplate("gzip index", appRoot, EmuConfig.GzipIsoIndexTemplate, isoname, false));
} }
GzippedFileReader::GzippedFileReader(void) GzippedFileReader::GzippedFileReader(void)
@ -258,7 +258,7 @@ void GzippedFileReader::AsyncPrefetchChunk(s64 start)
{ {
if (hOverlappedFile == INVALID_HANDLE_VALUE || asyncInProgress) if (hOverlappedFile == INVALID_HANDLE_VALUE || asyncInProgress)
{ {
Console.Warning(L"Unexpected file handle or progress state. Aborting prefetch."); Console.Warning("Unexpected file handle or progress state. Aborting prefetch.");
return; return;
} }
@ -384,7 +384,7 @@ int GzippedFileReader::ReadSync(void* pBuffer, uint sector, uint count)
int bytesToRead = count * m_blocksize; int bytesToRead = count * m_blocksize;
int res = _ReadSync(pBuffer, offset, bytesToRead); int res = _ReadSync(pBuffer, offset, bytesToRead);
if (res < 0) if (res < 0)
Console.Error(L"Error: iso-gzip read unsuccessful."); Console.Error("Error: iso-gzip read unsuccessful.");
return res; return res;
} }
@ -486,7 +486,7 @@ int GzippedFileReader::_ReadSync(void* pBuffer, s64 offset, uint bytesToRead)
int duration = NOW() - s; int duration = NOW() - s;
if (duration > 10) if (duration > 10)
Console.WriteLn(Color_Gray, L"gunzip: chunk #%5d-%2d : %1.2f MB - %d ms", Console.WriteLn(Color_Gray, "gunzip: chunk #%5d-%2d : %1.2f MB - %d ms",
(int)(offset / 4 / 1024 / 1024), (int)(offset / 4 / 1024 / 1024),
(int)(offset % (4 * 1024 * 1024) / GZFILE_READ_CHUNK_SIZE), (int)(offset % (4 * 1024 * 1024) / GZFILE_READ_CHUNK_SIZE),
(float)size / 1024 / 1024, (float)size / 1024 / 1024,

View File

@ -16,6 +16,11 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "IsoFileFormats.h" #include "IsoFileFormats.h"
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include "Config.h"
#include "fmt/core.h"
#include <errno.h> #include <errno.h>
@ -42,10 +47,8 @@ int InputIsoFile::ReadSync(u8* dst, uint lsn)
{ {
if (lsn >= m_blocks) if (lsn >= m_blocks)
{ {
FastFormatUnicode msg; std::string msg(fmt::format("isoFile error: Block index is past the end of file! ({} >= {}).", lsn, m_blocks));
msg.Write("isoFile error: Block index is past the end of file! (%u >= %u).", lsn, m_blocks); pxAssertDev(false, msg.c_str());
pxAssertDev(false, msg);
Console.Error(msg.c_str()); Console.Error(msg.c_str());
return -1; return -1;
} }
@ -248,8 +251,8 @@ bool InputIsoFile::Open(std::string srcfile, bool testOnly)
if (!detected) if (!detected)
throw Exception::BadStream() throw Exception::BadStream()
.SetUserMsg(_("Unrecognized ISO image file format")) .SetUserMsg("Unrecognized ISO image file format")
.SetDiagMsg(L"ISO mounting failed: PCSX2 is unable to identify the ISO image type."); .SetDiagMsg("ISO mounting failed: PCSX2 is unable to identify the ISO image type.");
if (!isBlockdump && !isCompressed) if (!isBlockdump && !isCompressed)
{ {

View File

@ -19,6 +19,8 @@
#include "IsoFS.h" #include "IsoFS.h"
#include "IsoFile.h" #include "IsoFile.h"
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
@ -159,7 +161,7 @@ int IsoDirectory::GetIndexOf(const std::string_view& fileName) const
return i; return i;
} }
throw Exception::FileNotFound(StringUtil::UTF8StringToWideString(fileName)); throw Exception::FileNotFound(std::string(fileName));
} }
const IsoFileDescriptor& IsoDirectory::GetEntry(const std::string_view& fileName) const const IsoFileDescriptor& IsoDirectory::GetEntry(const std::string_view& fileName) const
@ -189,7 +191,7 @@ IsoFileDescriptor IsoDirectory::FindFile(const std::string_view& filePath) const
{ {
info = dir->GetEntry(parts[index]); info = dir->GetEntry(parts[index]);
if (info.IsFile()) if (info.IsFile())
throw Exception::FileNotFound(StringUtil::UTF8StringToWxString(filePath)); throw Exception::FileNotFound(std::string(filePath));
deleteme.reset(new IsoDirectory(internalReader, info)); deleteme.reset(new IsoDirectory(internalReader, info));
dir = deleteme.get(); dir = deleteme.get();

View File

@ -15,10 +15,14 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include "common/Exceptions.h"
#include "IsoFS.h" #include "IsoFS.h"
#include "IsoFile.h" #include "IsoFile.h"
#include <cstdio>
IsoFile::IsoFile(SectorSource& reader, const std::string_view& filename) IsoFile::IsoFile(SectorSource& reader, const std::string_view& filename)
: internalReader(reader) : internalReader(reader)
, fileEntry(IsoDirectory(reader).FindFile(filename)) , fileEntry(IsoDirectory(reader).FindFile(filename))
@ -74,19 +78,19 @@ u32 IsoFile::seek(u32 absoffset)
// Returns the new offset in the file. Out-of-bounds seeks are automatically truncated at 0 // Returns the new offset in the file. Out-of-bounds seeks are automatically truncated at 0
// and fileLength. // and fileLength.
u32 IsoFile::seek(s64 offset, wxSeekMode ref_position) u32 IsoFile::seek(s64 offset, int mode)
{ {
switch (ref_position) switch (mode)
{ {
case wxFromStart: case SEEK_SET:
pxAssertDev(offset >= 0 && offset <= (s64)ULONG_MAX, "Invalid seek position from start."); pxAssertDev(offset >= 0 && offset <= (s64)ULONG_MAX, "Invalid seek position from start.");
return seek(offset); return seek(offset);
case wxFromCurrent: case SEEK_CUR:
// truncate negative values to zero, and positive values to 4gb // truncate negative values to zero, and positive values to 4gb
return seek(std::min(std::max<s64>(0, (s64)currentOffset + offset), (s64)ULONG_MAX)); return seek(std::min(std::max<s64>(0, (s64)currentOffset + offset), (s64)ULONG_MAX));
case wxFromEnd: case SEEK_END:
// truncate negative values to zero, and positive values to 4gb // truncate negative values to zero, and positive values to 4gb
return seek(std::min(std::max<s64>(0, (s64)fileEntry.size + offset), (s64)ULONG_MAX)); return seek(std::min(std::max<s64>(0, (s64)fileEntry.size + offset), (s64)ULONG_MAX));

View File

@ -44,7 +44,7 @@ public:
virtual ~IsoFile() = default; virtual ~IsoFile() = default;
u32 seek(u32 absoffset); u32 seek(u32 absoffset);
u32 seek(s64 offset, wxSeekMode ref_position); u32 seek(s64 offset, int mode);
void reset(); void reset();
s32 skip(s32 n); s32 skip(s32 n);

View File

@ -16,9 +16,12 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "IsoFileFormats.h" #include "IsoFileFormats.h"
#include "common/Exceptions.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
#include "fmt/core.h"
#include <errno.h> #include <errno.h>
OutputIsoFile::OutputIsoFile() OutputIsoFile::OutputIsoFile()
@ -55,7 +58,7 @@ void OutputIsoFile::Create(std::string filename, int version)
if (!m_outstream) if (!m_outstream)
{ {
Console.Error("(OutputIsoFile::Create) Unable to open the file '%s' for writing: %d", m_filename.c_str(), errno); Console.Error("(OutputIsoFile::Create) Unable to open the file '%s' for writing: %d", m_filename.c_str(), errno);
ScopedExcept ex(Exception::FromErrno(StringUtil::UTF8StringToWxString(filename), errno)); ScopedExcept ex(Exception::FromErrno(filename, errno));
ex->Rethrow(); ex->Rethrow();
} }
@ -123,12 +126,12 @@ void OutputIsoFile::WriteBuffer(const void* src, size_t size)
int err = errno; int err = errno;
if (!err) if (!err)
{ {
throw Exception::BadStream(StringUtil::UTF8StringToWxString(m_filename)) throw Exception::BadStream(m_filename)
.SetDiagMsg(pxsFmt(L"An error occurred while writing %u bytes to file", size)); .SetDiagMsg(fmt::format("An error occurred while writing {} bytes to file", size));
} }
ScopedExcept ex(Exception::FromErrno(StringUtil::UTF8StringToWxString(m_filename), err)); ScopedExcept ex(Exception::FromErrno(m_filename, err));
ex->SetDiagMsg(pxsFmt(L"An error occurred while writing %u bytes to file: %s", size, WX_STR(ex->DiagMsg()))); ex->SetDiagMsg(fmt::format("An error occurred while writing {} bytes to file: {}", size, ex->DiagMsg()));
ex->Rethrow(); ex->Rethrow();
} }
} }

View File

@ -1116,6 +1116,7 @@ set(pcsx2GuiSources
gui/Debugger/DebugEvents.cpp gui/Debugger/DebugEvents.cpp
gui/DriveList.cpp gui/DriveList.cpp
gui/ExecutorThread.cpp gui/ExecutorThread.cpp
gui/FastFormatString.cpp
gui/FrameForGS.cpp gui/FrameForGS.cpp
gui/GlobalCommands.cpp gui/GlobalCommands.cpp
gui/IniInterface.cpp gui/IniInterface.cpp
@ -1143,9 +1144,11 @@ set(pcsx2GuiSources
gui/pxCheckBox.cpp gui/pxCheckBox.cpp
gui/pxRadioPanel.cpp gui/pxRadioPanel.cpp
gui/pxStaticText.cpp gui/pxStaticText.cpp
gui/pxTranslate.cpp
gui/pxWindowTextWriter.cpp gui/pxWindowTextWriter.cpp
gui/RecentIsoList.cpp gui/RecentIsoList.cpp
gui/Saveslots.cpp gui/Saveslots.cpp
gui/StringHelpers.cpp
gui/SysCoreThread.cpp gui/SysCoreThread.cpp
gui/SysState.cpp gui/SysState.cpp
gui/SysThreadBase.cpp gui/SysThreadBase.cpp
@ -1201,6 +1204,7 @@ set(pcsx2GuiHeaders
gui/pxStaticText.h gui/pxStaticText.h
gui/RecentIsoList.h gui/RecentIsoList.h
gui/Saveslots.h gui/Saveslots.h
gui/StringHelpers.h
gui/SysThreads.h gui/SysThreads.h
gui/ThreadingDialogs.h gui/ThreadingDialogs.h
gui/ThreadingDialogs.cpp gui/ThreadingDialogs.cpp
@ -1387,11 +1391,6 @@ set(pcsx2SystemHeaders
set(pcsx2UtilitiesSources set(pcsx2UtilitiesSources
Utilities/FileUtils.cpp) Utilities/FileUtils.cpp)
# Utilities headers
set(pcsx2UtilitiesHeaders
Utilities/AsciiFile.h)
# Windows sources # Windows sources
set(pcsx2WindowsSources set(pcsx2WindowsSources
CDVD/Windows/DriveUtility.cpp CDVD/Windows/DriveUtility.cpp
@ -1520,7 +1519,7 @@ target_sources(PCSX2 PRIVATE
${pcsx2ps2Headers} ${pcsx2ps2Headers}
${pcsx2SystemHeaders} ${pcsx2SystemHeaders}
${pcsx2UtilitiesSources} ${pcsx2UtilitiesSources}
${pcsx2UtilitiesHeaders}) )
# gui sources when not doing a qt build # gui sources when not doing a qt build
if (NOT PCSX2_CORE) if (NOT PCSX2_CORE)

View File

@ -31,5 +31,7 @@ extern s64 PSXCLK; /* 36.864 Mhz */
#include "SaveState.h" #include "SaveState.h"
#include "DebugTools/Debug.h" #include "DebugTools/Debug.h"
extern wxString ShiftJIS_ConvertString( const char* src ); #include <string>
extern wxString ShiftJIS_ConvertString( const char* src, int maxlen );
extern std::string ShiftJIS_ConvertString( const char* src );
extern std::string ShiftJIS_ConvertString( const char* src, int maxlen );

View File

@ -802,9 +802,6 @@ struct Pcsx2Config
void LoadSave(SettingsWrapper& wrap); void LoadSave(SettingsWrapper& wrap);
GamefixOptions& DisableAll(); GamefixOptions& DisableAll();
void Set(const wxString& list, bool enabled = true);
void Clear(const wxString& list) { Set(list, false); }
bool Get(GamefixId id) const; bool Get(GamefixId id) const;
void Set(GamefixId id, bool enabled = true); void Set(GamefixId id, bool enabled = true);
void Clear(GamefixId id) { Set(id, false); } void Clear(GamefixId id) { Set(id, false); }

View File

@ -22,6 +22,7 @@
#include <condition_variable> #include <condition_variable>
#include <fstream> #include <fstream>
#include "common/Path.h"
#include "DEV9/SimpleQueue.h" #include "DEV9/SimpleQueue.h"
class ATA class ATA

View File

@ -15,6 +15,8 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include "ATA.h" #include "ATA.h"
#include "DEV9/DEV9.h" #include "DEV9/DEV9.h"
#ifndef PCSX2_CORE #ifndef PCSX2_CORE

View File

@ -15,6 +15,8 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include "ATA.h" #include "ATA.h"
#include "DEV9/DEV9.h" #include "DEV9/DEV9.h"

View File

@ -18,6 +18,8 @@
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include "common/Path.h"
class HddCreate class HddCreate
{ {
public: public:

View File

@ -16,6 +16,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "HddCreateWx.h" #include "HddCreateWx.h"
#include "gui/App.h"
void HddCreateWx::Init() void HddCreateWx::Init()
{ {

View File

@ -15,6 +15,8 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#ifdef _WIN32 #ifdef _WIN32
#include "common/RedtapeWindows.h" #include "common/RedtapeWindows.h"
#include <Winioctl.h> #include <Winioctl.h>

View File

@ -15,6 +15,8 @@
#pragma once #pragma once
#include <memory>
namespace PacketReader namespace PacketReader
{ {
class Payload class Payload

View File

@ -16,6 +16,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#ifdef _WIN32 #ifdef _WIN32
#include "common/RedtapeWindows.h"
#include <iphlpapi.h> #include <iphlpapi.h>
#include <icmpapi.h> #include <icmpapi.h>
#elif defined(__POSIX__) #elif defined(__POSIX__)
@ -36,6 +37,7 @@
#ifdef __linux__ #ifdef __linux__
#include <linux/errqueue.h> #include <linux/errqueue.h>
#endif #endif
#include <unistd.h>
#endif #endif
#include "ICMP_Session.h" #include "ICMP_Session.h"
@ -898,4 +900,4 @@ namespace Sessions
for (size_t i = 0; i < pings.size(); i++) for (size_t i = 0; i < pings.size(); i++)
delete pings[i]; delete pings[i];
} }
} // namespace Sessions } // namespace Sessions

View File

@ -17,6 +17,13 @@
#include "TCP_Session.h" #include "TCP_Session.h"
#ifdef _WIN32
#include "common/RedtapeWindows.h"
#include <winsock2.h>
#else
#include <unistd.h>
#endif
using namespace PacketReader; using namespace PacketReader;
using namespace PacketReader::IP; using namespace PacketReader::IP;
using namespace PacketReader::IP::TCP; using namespace PacketReader::IP::TCP;

View File

@ -15,6 +15,8 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#ifdef __POSIX__ #ifdef __POSIX__
#define SOCKET_ERROR -1 #define SOCKET_ERROR -1
#include <errno.h> #include <errno.h>
@ -22,6 +24,13 @@
#include <netinet/in.h> #include <netinet/in.h>
#endif #endif
#ifdef _WIN32
#include "common/RedtapeWindows.h"
#include <winsock2.h>
#else
#include <unistd.h>
#endif
#include "UDP_FixedPort.h" #include "UDP_FixedPort.h"
#include "DEV9/PacketReader/IP/UDP/UDP_Packet.h" #include "DEV9/PacketReader/IP/UDP/UDP_Packet.h"

View File

@ -15,6 +15,8 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#ifdef __POSIX__ #ifdef __POSIX__
#define SOCKET_ERROR -1 #define SOCKET_ERROR -1
#include <errno.h> #include <errno.h>
@ -22,6 +24,13 @@
#include <netinet/in.h> #include <netinet/in.h>
#endif #endif
#ifdef _WIN32
#include "common/RedtapeWindows.h"
#include <winsock2.h>
#else
#include <unistd.h>
#endif
#include "UDP_Session.h" #include "UDP_Session.h"
#include "DEV9/PacketReader/IP/UDP/UDP_Packet.h" #include "DEV9/PacketReader/IP/UDP/UDP_Packet.h"

View File

@ -15,6 +15,10 @@
#pragma once #pragma once
#include <atomic>
#include "common/Assertions.h"
//Designed to allow one thread to queue data to another thread //Designed to allow one thread to queue data to another thread
template <class T> template <class T>
class SimpleQueue class SimpleQueue

View File

@ -18,6 +18,8 @@
#include "common/RedtapeWindows.h" #include "common/RedtapeWindows.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
#include "fmt/core.h"
#include <stdio.h> #include <stdio.h>
#include <windows.h> #include <windows.h>
#include <winsock2.h> #include <winsock2.h>
@ -355,7 +357,7 @@ bool TAPGetWin32Adapter(const std::string& name, PIP_ADAPTER_ADDRESSES adapter,
//We must be bridged //We must be bridged
Console.WriteLn("DEV9: Current adapter is probably bridged"); Console.WriteLn("DEV9: Current adapter is probably bridged");
Console.WriteLn(L"DEV9: Adapter Display name: %s", pAdapterInfo->FriendlyName); Console.WriteLn(fmt::format("DEV9: Adapter Display name: {}", StringUtil::WideStringToUTF8String(pAdapterInfo->FriendlyName)));
//We will need to find the bridge adapter that out adapter is //We will need to find the bridge adapter that out adapter is
//as the IP information of the tap adapter is null //as the IP information of the tap adapter is null
@ -407,7 +409,7 @@ bool TAPGetWin32Adapter(const std::string& name, PIP_ADAPTER_ADDRESSES adapter,
PIP_ADAPTER_ADDRESSES potentialAdapter = FindAdapterViaIndex(AdapterInfoReduced.get(), row.HigherLayerInterfaceIndex); PIP_ADAPTER_ADDRESSES potentialAdapter = FindAdapterViaIndex(AdapterInfoReduced.get(), row.HigherLayerInterfaceIndex);
if (potentialAdapter != nullptr) if (potentialAdapter != nullptr)
{ {
Console.WriteLn(L"DEV9: %s is possible bridge (Check 1 passed)", potentialAdapter->Description); Console.WriteLn(fmt::format("DEV9: {} is possible bridge (Check 1 passed)", StringUtil::WideStringToUTF8String(potentialAdapter->Description)));
potentialBridges.push_back(row.HigherLayerInterfaceIndex); potentialBridges.push_back(row.HigherLayerInterfaceIndex);
} }
else else
@ -491,7 +493,7 @@ bool TAPGetWin32Adapter(const std::string& name, PIP_ADAPTER_ADDRESSES adapter,
wil::unique_cotaskmem_string dispName; wil::unique_cotaskmem_string dispName;
hr = component->GetDisplayName(dispName.put()); hr = component->GetDisplayName(dispName.put());
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
Console.WriteLn(L"DEV9: %s is possible bridge (Check 2 passed)", dispName); Console.WriteLn(fmt::format("DEV9: {} is possible bridge (Check 2 passed)", StringUtil::WideStringToUTF8String(dispName.get())));
//Check if adapter has the ms_bridge component bound to it. //Check if adapter has the ms_bridge component bound to it.
auto bindings = bridge.try_query<INetCfgComponentBindings>(); auto bindings = bridge.try_query<INetCfgComponentBindings>();
@ -504,7 +506,7 @@ bool TAPGetWin32Adapter(const std::string& name, PIP_ADAPTER_ADDRESSES adapter,
hr = component->GetDisplayName(dispName.put()); hr = component->GetDisplayName(dispName.put());
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
Console.WriteLn(L"DEV9: %s is bridge (Check 3 passed)", dispName); Console.WriteLn(fmt::format("DEV9: {} is bridge (Check 3 passed)", StringUtil::WideStringToUTF8String(dispName.get())));
bridgeAdapter = cAdapterInfo; bridgeAdapter = cAdapterInfo;
break; break;

View File

@ -31,6 +31,8 @@
#include <ifaddrs.h> #include <ifaddrs.h>
#endif #endif
#include "Config.h"
#include "PacketReader/IP/IP_Address.h" #include "PacketReader/IP/IP_Address.h"
#include "InternalServers/DHCP_Server.h" #include "InternalServers/DHCP_Server.h"
#include "InternalServers/DNS_Logger.h" #include "InternalServers/DNS_Logger.h"

View File

@ -14,6 +14,8 @@
*/ */
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include <memory> #include <memory>
#ifdef _WIN32 #ifdef _WIN32

View File

@ -14,6 +14,7 @@
*/ */
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/Assertions.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
#ifdef __POSIX__ #ifdef __POSIX__

View File

@ -129,5 +129,5 @@ void FlatFileReader::Close(void)
uint FlatFileReader::GetBlockCount(void) const uint FlatFileReader::GetBlockCount(void) const
{ {
return (int)(Path::GetFileSize(m_filename) / m_blocksize); return (int)(FileSystem::GetPathFileSize(m_filename.c_str()) / m_blocksize);
} }

View File

@ -86,13 +86,13 @@ class SysTraceLog_EE : public SysTraceLog
public: public:
SysTraceLog_EE( const SysTraceLogDescriptor* desc ) : _parent( desc ) {} SysTraceLog_EE( const SysTraceLogDescriptor* desc ) : _parent( desc ) {}
void ApplyPrefix( FastFormatAscii& ascii ) const override; void ApplyPrefix( std::string& ascii ) const override;
bool IsActive() const override bool IsActive() const override
{ {
return SysTraceLog::IsActive() && EmuConfig.Trace.EE.m_EnableAll; return SysTraceLog::IsActive() && EmuConfig.Trace.EE.m_EnableAll;
} }
wxString GetCategory() const override { return L"EE"; } std::string GetCategory() const override { return "EE"; }
}; };
class SysTraceLog_VIFcode : public SysTraceLog_EE class SysTraceLog_VIFcode : public SysTraceLog_EE
@ -102,7 +102,7 @@ class SysTraceLog_VIFcode : public SysTraceLog_EE
public: public:
SysTraceLog_VIFcode( const SysTraceLogDescriptor* desc ) : _parent( desc ) {} SysTraceLog_VIFcode( const SysTraceLogDescriptor* desc ) : _parent( desc ) {}
void ApplyPrefix( FastFormatAscii& ascii ) const override; void ApplyPrefix(std::string& ascii ) const override;
}; };
class SysTraceLog_EE_Disasm : public SysTraceLog_EE class SysTraceLog_EE_Disasm : public SysTraceLog_EE
@ -117,7 +117,7 @@ public:
return _parent::IsActive() && EmuConfig.Trace.EE.m_EnableDisasm; return _parent::IsActive() && EmuConfig.Trace.EE.m_EnableDisasm;
} }
wxString GetCategory() const override { return _parent::GetCategory() + L".Disasm"; } std::string GetCategory() const override { return _parent::GetCategory() + ".Disasm"; }
}; };
class SysTraceLog_EE_Registers : public SysTraceLog_EE class SysTraceLog_EE_Registers : public SysTraceLog_EE
@ -132,7 +132,7 @@ public:
return _parent::IsActive() && EmuConfig.Trace.EE.m_EnableRegisters; return _parent::IsActive() && EmuConfig.Trace.EE.m_EnableRegisters;
} }
wxString GetCategory() const override { return _parent::GetCategory() + L".Registers"; } std::string GetCategory() const override { return _parent::GetCategory() + ".Registers"; }
}; };
class SysTraceLog_EE_Events : public SysTraceLog_EE class SysTraceLog_EE_Events : public SysTraceLog_EE
@ -147,7 +147,7 @@ public:
return _parent::IsActive() && EmuConfig.Trace.EE.m_EnableEvents; return _parent::IsActive() && EmuConfig.Trace.EE.m_EnableEvents;
} }
wxString GetCategory() const override { return _parent::GetCategory() + L".Events"; } std::string GetCategory() const override { return _parent::GetCategory() + ".Events"; }
}; };
@ -158,13 +158,13 @@ class SysTraceLog_IOP : public SysTraceLog
public: public:
SysTraceLog_IOP( const SysTraceLogDescriptor* desc ) : _parent( desc ) {} SysTraceLog_IOP( const SysTraceLogDescriptor* desc ) : _parent( desc ) {}
void ApplyPrefix( FastFormatAscii& ascii ) const override; void ApplyPrefix( std::string& ascii ) const override;
bool IsActive() const override bool IsActive() const override
{ {
return SysTraceLog::IsActive() && EmuConfig.Trace.IOP.m_EnableAll; return SysTraceLog::IsActive() && EmuConfig.Trace.IOP.m_EnableAll;
} }
wxString GetCategory() const override { return L"IOP"; } std::string GetCategory() const override { return "IOP"; }
}; };
class SysTraceLog_IOP_Disasm : public SysTraceLog_IOP class SysTraceLog_IOP_Disasm : public SysTraceLog_IOP
@ -178,7 +178,7 @@ public:
return _parent::IsActive() && EmuConfig.Trace.IOP.m_EnableDisasm; return _parent::IsActive() && EmuConfig.Trace.IOP.m_EnableDisasm;
} }
wxString GetCategory() const override { return _parent::GetCategory() + L".Disasm"; } std::string GetCategory() const override { return _parent::GetCategory() + ".Disasm"; }
}; };
class SysTraceLog_IOP_Registers : public SysTraceLog_IOP class SysTraceLog_IOP_Registers : public SysTraceLog_IOP
@ -192,7 +192,7 @@ public:
return _parent::IsActive() && EmuConfig.Trace.IOP.m_EnableRegisters; return _parent::IsActive() && EmuConfig.Trace.IOP.m_EnableRegisters;
} }
wxString GetCategory() const override { return _parent::GetCategory() + L".Registers"; } std::string GetCategory() const override { return _parent::GetCategory() + ".Registers"; }
}; };
class SysTraceLog_IOP_Events : public SysTraceLog_IOP class SysTraceLog_IOP_Events : public SysTraceLog_IOP
@ -206,7 +206,7 @@ public:
return _parent::IsActive() && EmuConfig.Trace.IOP.m_EnableEvents; return _parent::IsActive() && EmuConfig.Trace.IOP.m_EnableEvents;
} }
wxString GetCategory() const override { return _parent::GetCategory() + L".Events"; } std::string GetCategory() const override { return _parent::GetCategory() + ".Events"; }
}; };
// -------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------
@ -226,10 +226,10 @@ class ConsoleLogFromVM : public BaseTraceLogSource
public: public:
ConsoleLogFromVM( const TraceLogDescriptor* desc ) : _parent( desc ) {} ConsoleLogFromVM( const TraceLogDescriptor* desc ) : _parent( desc ) {}
bool Write( const wxString &msg ) const bool Write( const char* msg ) const
{ {
ConsoleColorScope cs(conColor); ConsoleColorScope cs(conColor);
Console.WriteRaw( msg ); Console.WriteRaw(msg);
// Buffered output isn't compatible with the testsuite. The end of test // Buffered output isn't compatible with the testsuite. The end of test
// doesn't always get flushed. Let's just flush all the output if EE/IOP // doesn't always get flushed. Let's just flush all the output if EE/IOP
@ -241,7 +241,7 @@ public:
bool Write(const std::string& msg) const bool Write(const std::string& msg) const
{ {
return Write(fromUTF8(msg)); return Write(msg.c_str());
} }
}; };
@ -347,13 +347,6 @@ extern void __Log( const char* fmt, ... );
# define SysTraceActive(trace) (false) # define SysTraceActive(trace) (false)
#endif #endif
#ifdef __WXMAC__
// Not available on OSX, apparently always double buffered window.
# define SetDoubleBuffered(x)
// TODO OSX OsxKeyCodes.cpp pending
#endif
#define macTrace(trace) SysTraceActive(trace) && SysTrace.trace.Write #define macTrace(trace) SysTraceActive(trace) && SysTrace.trace.Write
#define SIF_LOG macTrace(SIF) #define SIF_LOG macTrace(SIF)

View File

@ -27,6 +27,8 @@
#include "IopMem.h" #include "IopMem.h"
#include "SymbolMap.h" #include "SymbolMap.h"
#include "common/StringUtil.h"
#ifndef PCSX2_CORE #ifndef PCSX2_CORE
#include "gui/SysThreads.h" #include "gui/SysThreads.h"
#endif #endif
@ -506,7 +508,7 @@ u128 R5900DebugInterface::getRegister(int cat, int num)
return result; return result;
} }
wxString R5900DebugInterface::getRegisterString(int cat, int num) std::string R5900DebugInterface::getRegisterString(int cat, int num)
{ {
switch (cat) switch (cat)
{ {
@ -514,15 +516,11 @@ wxString R5900DebugInterface::getRegisterString(int cat, int num)
case EECAT_CP0: case EECAT_CP0:
case EECAT_FCR: case EECAT_FCR:
case EECAT_VU0F: case EECAT_VU0F:
return getRegister(cat, num).ToString(); return StringUtil::U128ToString(getRegister(cat, num));
case EECAT_FPR: case EECAT_FPR:
{ return StringUtil::StdStringFromFormat("%f", fpuRegs.fpr[num].f);
char str[64];
sprintf(str, "%f", fpuRegs.fpr[num].f);
return wxString(str, wxConvUTF8);
}
default: default:
return L""; return {};
} }
} }
@ -829,14 +827,14 @@ u128 R3000DebugInterface::getRegister(int cat, int num)
return u128::From32(value); return u128::From32(value);
} }
wxString R3000DebugInterface::getRegisterString(int cat, int num) std::string R3000DebugInterface::getRegisterString(int cat, int num)
{ {
switch (cat) switch (cat)
{ {
case IOPCAT_GPR: case IOPCAT_GPR:
return getRegister(cat, num).ToString(); return StringUtil::U128ToString(getRegister(cat, num));
default: default:
return L"Invalid"; return "Invalid";
} }
} }

View File

@ -18,6 +18,8 @@
#include "ExpressionParser.h" #include "ExpressionParser.h"
#include "SymbolMap.h" #include "SymbolMap.h"
#include <string>
enum enum
{ {
EECAT_GPR, EECAT_GPR,
@ -66,7 +68,7 @@ public:
virtual RegisterType getRegisterType(int cat) = 0; virtual RegisterType getRegisterType(int cat) = 0;
virtual const char* getRegisterName(int cat, int num) = 0; virtual const char* getRegisterName(int cat, int num) = 0;
virtual u128 getRegister(int cat, int num) = 0; virtual u128 getRegister(int cat, int num) = 0;
virtual wxString getRegisterString(int cat, int num) = 0; virtual std::string getRegisterString(int cat, int num) = 0;
virtual u128 getHI() = 0; virtual u128 getHI() = 0;
virtual u128 getLO() = 0; virtual u128 getLO() = 0;
virtual u32 getPC() = 0; virtual u32 getPC() = 0;
@ -107,7 +109,7 @@ public:
RegisterType getRegisterType(int cat) override; RegisterType getRegisterType(int cat) override;
const char* getRegisterName(int cat, int num) override; const char* getRegisterName(int cat, int num) override;
u128 getRegister(int cat, int num) override; u128 getRegister(int cat, int num) override;
wxString getRegisterString(int cat, int num) override; std::string getRegisterString(int cat, int num) override;
u128 getHI() override; u128 getHI() override;
u128 getLO() override; u128 getLO() override;
u32 getPC() override; u32 getPC() override;
@ -141,7 +143,7 @@ public:
RegisterType getRegisterType(int cat) override; RegisterType getRegisterType(int cat) override;
const char* getRegisterName(int cat, int num) override; const char* getRegisterName(int cat, int num) override;
u128 getRegister(int cat, int num) override; u128 getRegister(int cat, int num) override;
wxString getRegisterString(int cat, int num) override; std::string getRegisterString(int cat, int num) override;
u128 getHI() override; u128 getHI() override;
u128 getLO() override; u128 getLO() override;
u32 getPC() override; u32 getPC() override;

View File

@ -14,6 +14,7 @@
*/ */
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/FileSystem.h"
#include "SymbolMap.h" #include "SymbolMap.h"
#include <algorithm> #include <algorithm>
@ -47,7 +48,7 @@ void SymbolMap::Clear() {
bool SymbolMap::LoadNocashSym(const char *filename) { bool SymbolMap::LoadNocashSym(const char *filename) {
std::lock_guard<std::recursive_mutex> guard(m_lock); std::lock_guard<std::recursive_mutex> guard(m_lock);
FILE *f = wxFopen(filename, "r"); FILE *f = FileSystem::OpenCFile(filename, "r");
if (!f) if (!f)
return false; return false;

View File

@ -273,7 +273,7 @@ static __ri void DmaExec( void (*func)(), u32 mem, u32 value )
static bool warned; //Check if the warning has already been output to console, to prevent constant spam. static bool warned; //Check if the warning has already been output to console, to prevent constant spam.
if (!warned) if (!warned)
{ {
DevCon.Warning(L"%s CHCR.MOD set to 3, assuming 1 (chain)", ChcrName(mem)); DevCon.Warning("%s CHCR.MOD set to 3, assuming 1 (chain)", ChcrName(mem));
warned = true; warned = true;
} }
reg.chcr.MOD = 0x1; reg.chcr.MOD = 0x1;

View File

@ -23,7 +23,9 @@
#include "DebugTools/SymbolMap.h" #include "DebugTools/SymbolMap.h"
#include "Config.h" #include "Config.h"
#include "Utilities/AsciiFile.h" #include "common/FileSystem.h"
#include "fmt/core.h"
using namespace R5900; using namespace R5900;
@ -209,22 +211,24 @@ void iDumpBlock(u32 ee_pc, u32 ee_size, uptr x86_pc, u32 x86_size)
DbgCon.WriteLn( Color_Gray, "dump block %x:%x (x86:0x%x)", ee_pc, ee_end, x86_pc ); DbgCon.WriteLn( Color_Gray, "dump block %x:%x (x86:0x%x)", ee_pc, ee_end, x86_pc );
EmuFolders::Logs.Mkdir(); EmuFolders::Logs.Mkdir();
wxString dump_filename = Path::Combine(EmuFolders::Logs, wxsFormat(L"R5900dump_%.8X:%.8X.txt", ee_pc, ee_end) ); std::string dump_filename(Path::CombineStdString(EmuFolders::Logs, fmt::format("R5900dump_{:.8X}:{:.8X}.txt", ee_pc, ee_end) ));
AsciiFile eff( dump_filename, L"w" ); std::FILE* eff = FileSystem::OpenCFile(dump_filename.c_str(), "w");
if (!eff)
return;
// Print register content to detect the memory access type. Warning value are taken // Print register content to detect the memory access type. Warning value are taken
// during the call of this function. There aren't the real value of the block. // during the call of this function. There aren't the real value of the block.
eff.Printf("Dump register data: 0x%x\n", (uptr)&cpuRegs.GPR.r[0].UL[0]); std::fprintf(eff, "Dump register data: 0x%p\n", &cpuRegs.GPR.r[0].UL[0]);
for (int reg = 0; reg < 32; reg++) { for (int reg = 0; reg < 32; reg++) {
// Only lower 32 bits (enough for address) // Only lower 32 bits (enough for address)
eff.Printf("\t%2s <= 0x%08x_%08x\n", R5900::GPR_REG[reg], cpuRegs.GPR.r[reg].UL[1],cpuRegs.GPR.r[reg].UL[0]); std::fprintf(eff, "\t%2s <= 0x%08x_%08x\n", R5900::GPR_REG[reg], cpuRegs.GPR.r[reg].UL[1],cpuRegs.GPR.r[reg].UL[0]);
} }
eff.Printf("\n"); std::fprintf(eff, "\n");
if (!R5900SymbolMap.GetLabelString(ee_pc).empty()) if (!R5900SymbolMap.GetLabelString(ee_pc).empty())
{ {
eff.Printf( "%s\n", R5900SymbolMap.GetLabelString(ee_pc).c_str() ); std::fprintf(eff, "%s\n", R5900SymbolMap.GetLabelString(ee_pc).c_str() );
} }
for ( u32 i = ee_pc; i < ee_end; i += 4 ) for ( u32 i = ee_pc; i < ee_end; i += 4 )
@ -232,29 +236,31 @@ void iDumpBlock(u32 ee_pc, u32 ee_size, uptr x86_pc, u32 x86_size)
std::string output; std::string output;
//TLB Issue disR5900Fasm( output, memRead32( i ), i, false ); //TLB Issue disR5900Fasm( output, memRead32( i ), i, false );
disR5900Fasm( output, psMu32(i), i, false ); disR5900Fasm( output, psMu32(i), i, false );
eff.Printf( "0x%.X : %s\n", i, output.c_str() ); std::fprintf(eff, "0x%.X : %s\n", i, output.c_str() );
} }
// Didn't find (search) a better solution // Didn't find (search) a better solution
eff.Printf( "\nRaw x86 dump (https://www.onlinedisassembler.com/odaweb/):\n"); std::fprintf(eff, "\nRaw x86 dump (https://www.onlinedisassembler.com/odaweb/):\n");
u8* x86 = (u8*)x86_pc; u8* x86 = (u8*)x86_pc;
for (u32 i = 0; i < x86_size; i++) { for (u32 i = 0; i < x86_size; i++) {
eff.Printf("%.2X", x86[i]); std::fprintf(eff, "%.2X", x86[i]);
} }
eff.Printf("\n\n"); std::fprintf(eff, "\n\n");
eff.Close(); // Close the file so it can be appended by objdump std::fclose(eff); // Close the file so it can be appended by objdump
// handy but slow solution (system call) // handy but slow solution (system call)
#ifdef __linux__ #ifdef __linux__
wxString obj_filename = Path::Combine(EmuFolders::Logs, wxString(L"objdump_tmp.o")); std::string obj_filename(Path::CombineStdString(EmuFolders::Logs, "objdump_tmp.o"));
wxFFile objdump(obj_filename , L"wb"); std::FILE* objdump = FileSystem::OpenCFile(obj_filename.c_str(), "wb");
objdump.Write(x86, x86_size); if (!objdump)
objdump.Close(); return;
std::fwrite(x86, x86_size, 1, objdump);
std::fclose(objdump);
int status = std::system( int status = std::system(
wxsFormat( L"objdump -D -b binary -mi386 --disassembler-options=intel --no-show-raw-insn --adjust-vma=%d %s >> %s", fmt::format( "objdump -D -b binary -mi386 --disassembler-options=intel --no-show-raw-insn --adjust-vma=%d %s >> %s",
(u32) x86_pc, WX_STR(obj_filename), WX_STR(dump_filename)).mb_str() (u32) x86_pc, obj_filename, dump_filename).c_str()
); );
if (!WIFEXITED(status)) if (!WIFEXITED(status))
@ -273,25 +279,25 @@ void iDumpBlock( int startpc, u8 * ptr )
DbgCon.WriteLn( Color_Gray, "dump1 %x:%x, %x", startpc, pc, cpuRegs.cycle ); DbgCon.WriteLn( Color_Gray, "dump1 %x:%x, %x", startpc, pc, cpuRegs.cycle );
EmuFolders::Logs.Mkdir(); EmuFolders::Logs.Mkdir();
AsciiFile eff( std::FILE* eff = FileSystem::OpenCFile(Path::CombineStdString(EmuFolders::Logs, fmt::format("R5900dump{:.8X}.txt", startpc)).c_str(), "w");
Path::Combine( EmuFolders::Logs, wxsFormat(L"R5900dump%.8X.txt", startpc) ), L"w" if (!eff)
); return;
if (!R5900SymbolMap.GetLabelString(startpc).empty()) if (!R5900SymbolMap.GetLabelString(startpc).empty())
{ {
eff.Printf( "%s\n", R5900SymbolMap.GetLabelString(startpc).c_str() ); std::fprintf(eff, "%s\n", R5900SymbolMap.GetLabelString(startpc).c_str() );
} }
for ( uint i = startpc; i < s_nEndBlock; i += 4 ) for ( uint i = startpc; i < s_nEndBlock; i += 4 )
{ {
std::string output; std::string output;
disR5900Fasm( output, memRead32( i ), i, false ); disR5900Fasm( output, memRead32( i ), i, false );
eff.Printf( "%s\n", output.c_str() ); std::fprintf(eff, "%s\n", output.c_str() );
} }
// write the instruction info // write the instruction info
eff.Printf( "\n\nlive0 - %x, live2 - %x, lastuse - %x\nxmm - %x, used - %x\n", std::fprintf(eff, "\n\nlive0 - %x, live2 - %x, lastuse - %x\nxmm - %x, used - %x\n",
EEINST_LIVE0, EEINST_LIVE2, EEINST_LASTUSE, EEINST_XMM, EEINST_USED EEINST_LIVE0, EEINST_LIVE2, EEINST_LASTUSE, EEINST_XMM, EEINST_USED
); );
@ -313,17 +319,17 @@ void iDumpBlock( int startpc, u8 * ptr )
} }
} }
eff.Printf( " " ); std::fprintf(eff, " " );
for(uint i = 0; i < std::size(s_pInstCache->regs); ++i) { for(uint i = 0; i < std::size(s_pInstCache->regs); ++i) {
if( used[i] ) eff.Printf( "%2d ", i ); if( used[i] ) std::fprintf(eff, "%2d ", i );
} }
eff.Printf( "\n" ); std::fprintf(eff, "\n" );
for(uint i = 0; i < std::size(s_pInstCache->fpuregs); ++i) { for(uint i = 0; i < std::size(s_pInstCache->fpuregs); ++i) {
if( fpuused[i] ) eff.Printf( "%2d ", i ); if( fpuused[i] ) std::fprintf(eff, "%2d ", i );
} }
eff.Printf( "\n" ); std::fprintf(eff, "\n" );
eff.Printf( " " ); std::fprintf(eff, " " );
// TODO : Finish converting this over to wxWidgets wxFile stuff... // TODO : Finish converting this over to wxWidgets wxFile stuff...
/* /*

View File

@ -34,7 +34,7 @@ bool isPSXElf;
// All of ElfObjects functions. // All of ElfObjects functions.
ElfObject::ElfObject(std::string srcfile, IsoFile& isofile, bool isPSXElf) ElfObject::ElfObject(std::string srcfile, IsoFile& isofile, bool isPSXElf)
: data(isofile.getLength(), L"ELF headers") : data(isofile.getLength(), "ELF headers")
, filename(std::move(srcfile)) , filename(std::move(srcfile))
, header(*(ELF_HEADER*)data.GetPtr()) , header(*(ELF_HEADER*)data.GetPtr())
{ {
@ -44,7 +44,7 @@ ElfObject::ElfObject(std::string srcfile, IsoFile& isofile, bool isPSXElf)
} }
ElfObject::ElfObject(std::string srcfile, u32 hdrsize, bool isPSXElf) ElfObject::ElfObject(std::string srcfile, u32 hdrsize, bool isPSXElf)
: data(hdrsize, L"ELF headers") : data(hdrsize, "ELF headers")
, filename(std::move(srcfile)) , filename(std::move(srcfile))
, header(*(ELF_HEADER*)data.GetPtr()) , header(*(ELF_HEADER*)data.GetPtr())
{ {
@ -60,7 +60,7 @@ void ElfObject::initElfHeaders(bool isPSXElf)
return; return;
} }
DevCon.WriteLn( L"Initializing Elf: %d bytes", data.GetSizeInBytes()); DevCon.WriteLn("Initializing Elf: %d bytes", data.GetSizeInBytes());
if (header.e_phnum > 0) if (header.e_phnum > 0)
{ {
@ -157,40 +157,40 @@ std::pair<u32,u32> ElfObject::getTextRange()
void ElfObject::readIso(IsoFile& file) void ElfObject::readIso(IsoFile& file)
{ {
int rsize = file.read(data.GetPtr(), data.GetSizeInBytes()); int rsize = file.read(data.GetPtr(), data.GetSizeInBytes());
if (rsize < data.GetSizeInBytes()) throw Exception::EndOfStream(StringUtil::UTF8StringToWxString(filename)); if (rsize < data.GetSizeInBytes()) throw Exception::EndOfStream(filename);
} }
void ElfObject::readFile() void ElfObject::readFile()
{ {
int rsize = 0; int rsize = 0;
FILE *f = FileSystem::OpenCFile( filename.c_str(), "rb"); FILE *f = FileSystem::OpenCFile( filename.c_str(), "rb");
if (f == NULL) throw Exception::FileNotFound(StringUtil::UTF8StringToWxString(filename)); if (f == NULL) throw Exception::FileNotFound(filename);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
rsize = fread(data.GetPtr(), 1, data.GetSizeInBytes(), f); rsize = fread(data.GetPtr(), 1, data.GetSizeInBytes(), f);
fclose( f ); fclose( f );
if (rsize < data.GetSizeInBytes()) throw Exception::EndOfStream(StringUtil::UTF8StringToWxString(filename)); if (rsize < data.GetSizeInBytes()) throw Exception::EndOfStream(filename);
} }
static wxString GetMsg_InvalidELF() static std::string GetMsg_InvalidELF()
{ {
return return
_("Cannot load ELF binary image. The file may be corrupt or incomplete.") + "Cannot load ELF binary image. The file may be corrupt or incomplete."
wxString(L"\n\n") + "\n\n"
_("If loading from an ISO image, this error may be caused by an unsupported ISO image type or a bug in PCSX2 ISO image support."); "If loading from an ISO image, this error may be caused by an unsupported ISO image type or a bug in PCSX2 ISO image support.";
} }
void ElfObject::checkElfSize(s64 elfsize) void ElfObject::checkElfSize(s64 elfsize)
{ {
const wxChar* diagMsg = NULL; const char* diagMsg = NULL;
if (elfsize > 0xfffffff) diagMsg = L"Illegal ELF file size over 2GB!"; if (elfsize > 0xfffffff) diagMsg = "Illegal ELF file size over 2GB!";
else if (elfsize == -1) diagMsg = L"ELF file does not exist!"; else if (elfsize == -1) diagMsg = "ELF file does not exist!";
else if (elfsize == 0) diagMsg = L"Unexpected end of ELF file."; else if (elfsize == 0) diagMsg = "Unexpected end of ELF file.";
if (diagMsg) if (diagMsg)
throw Exception::BadStream(StringUtil::UTF8StringToWxString(filename)) throw Exception::BadStream(filename)
.SetDiagMsg(diagMsg) .SetDiagMsg(diagMsg)
.SetUserMsg(GetMsg_InvalidELF()); .SetUserMsg(GetMsg_InvalidELF());
} }

View File

@ -16,6 +16,8 @@
#ifndef __ELF_H__ #ifndef __ELF_H__
#define __ELF_H__ #define __ELF_H__
#include "common/SafeArray.h"
#include "common/SafeArray.inl"
#include "CDVD/IsoFS/IsoFSCDVD.h" #include "CDVD/IsoFS/IsoFSCDVD.h"
#include "CDVD/IsoFS/IsoFS.h" #include "CDVD/IsoFS/IsoFS.h"

View File

@ -60,7 +60,7 @@ void ReadFIFO_VIF1(mem128_t* out)
} }
} }
VIF_LOG("ReadFIFO/VIF1 -> %ls", WX_STR(out->ToString())); VIF_LOG("ReadFIFO/VIF1 -> 0x%08X.%08X.%08X.%08X", out->_u32[0], out->_u32[1], out->_u32[2], out->_u32[3]);
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -68,7 +68,7 @@ void ReadFIFO_VIF1(mem128_t* out)
// //
void WriteFIFO_VIF0(const mem128_t* value) void WriteFIFO_VIF0(const mem128_t* value)
{ {
VIF_LOG("WriteFIFO/VIF0 <- %ls", WX_STR(value->ToString())); VIF_LOG("WriteFIFO/VIF0 <- 0x%08X.%08X.%08X.%08X", value->_u32[0], value->_u32[1], value->_u32[2], value->_u32[3]);
vif0ch.qwc += 1; vif0ch.qwc += 1;
if (vif0.irqoffset.value != 0 && vif0.vifstalled.enabled) if (vif0.irqoffset.value != 0 && vif0.vifstalled.enabled)
@ -90,7 +90,7 @@ void WriteFIFO_VIF0(const mem128_t* value)
void WriteFIFO_VIF1(const mem128_t* value) void WriteFIFO_VIF1(const mem128_t* value)
{ {
VIF_LOG("WriteFIFO/VIF1 <- %ls", WX_STR(value->ToString())); VIF_LOG("WriteFIFO/VIF1 <- 0x%08X.%08X.%08X.%08X", value->_u32[0], value->_u32[1], value->_u32[2], value->_u32[3]);
if (vif1Regs.stat.FDR) if (vif1Regs.stat.FDR)
{ {

View File

@ -16,10 +16,12 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include <chrono> #include <chrono>
#include <cmath>
#include <deque> #include <deque>
#include <mutex> #include <mutex>
#include "common/StringHelpers.h" #include "fmt/core.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"
#include "imgui.h" #include "imgui.h"
@ -469,15 +471,15 @@ static void DrawOSDMessages()
} }
} }
static void FormatProcessorStat(FastFormatAscii& text, double usage, double time) static void FormatProcessorStat(std::string& text, double usage, double time)
{ {
// Some values, such as GPU (and even CPU to some extent) can be out of phase with the wall clock, // Some values, such as GPU (and even CPU to some extent) can be out of phase with the wall clock,
// which the processor time is divided by to get a utilization percentage. Let's clamp it at 100%, // which the processor time is divided by to get a utilization percentage. Let's clamp it at 100%,
// so that people don't get confused, and remove the decimal places when it's there while we're at it. // so that people don't get confused, and remove the decimal places when it's there while we're at it.
if (usage >= 99.95) if (usage >= 99.95)
text.Write("100%% (%.2fms)", time); fmt::format_to(std::back_inserter(text), "100% ({:.2f}ms)", time);
else else
text.Write("%.1f%% (%.2fms)", usage, time); fmt::format_to(std::back_inserter(text), "{:.1f}% ({:.2f}ms)", usage, time);
} }
static void DrawPerformanceOverlay() static void DrawPerformanceOverlay()
@ -489,10 +491,12 @@ static void DrawPerformanceOverlay()
float position_y = margin; float position_y = margin;
ImDrawList* dl = ImGui::GetBackgroundDrawList(); ImDrawList* dl = ImGui::GetBackgroundDrawList();
FastFormatAscii text; std::string text;
ImVec2 text_size; ImVec2 text_size;
bool first = true; bool first = true;
text.reserve(128);
#define DRAW_LINE(font, text, color) \ #define DRAW_LINE(font, text, color) \
do \ do \
{ \ { \
@ -521,33 +525,33 @@ static void DrawPerformanceOverlay()
switch (PerformanceMetrics::GetInternalFPSMethod()) switch (PerformanceMetrics::GetInternalFPSMethod())
{ {
case PerformanceMetrics::InternalFPSMethod::GSPrivilegedRegister: case PerformanceMetrics::InternalFPSMethod::GSPrivilegedRegister:
text.Write("G: %.2f [P] | V: %.2f", PerformanceMetrics::GetInternalFPS(), PerformanceMetrics::GetFPS()); fmt::format_to(std::back_inserter(text), "G: {:.2f} [P] | V: {:.2f}", PerformanceMetrics::GetInternalFPS(), PerformanceMetrics::GetFPS());
break; break;
case PerformanceMetrics::InternalFPSMethod::DISPFBBlit: case PerformanceMetrics::InternalFPSMethod::DISPFBBlit:
text.Write("G: %.2f [B] | V: %.2f", PerformanceMetrics::GetInternalFPS(), PerformanceMetrics::GetFPS()); fmt::format_to(std::back_inserter(text), "G: {:.2f} [B] | V: {:.2f}", PerformanceMetrics::GetInternalFPS(), PerformanceMetrics::GetFPS());
break; break;
case PerformanceMetrics::InternalFPSMethod::None: case PerformanceMetrics::InternalFPSMethod::None:
default: default:
text.Write("V: %.2f", PerformanceMetrics::GetFPS()); fmt::format_to(std::back_inserter(text), "V: {:.2f}", PerformanceMetrics::GetFPS());
break; break;
} }
first = false; first = false;
} }
if (GSConfig.OsdShowSpeed) if (GSConfig.OsdShowSpeed)
{ {
text.Write("%s%u%%", first ? "" : " | ", static_cast<u32>(std::round(speed))); fmt::format_to(std::back_inserter(text), "{}{}%", first ? "" : " | ", static_cast<u32>(std::round(speed)));
// We read the main config here, since MTGS doesn't get updated with speed toggles. // We read the main config here, since MTGS doesn't get updated with speed toggles.
if (EmuConfig.GS.LimitScalar == 0.0) if (EmuConfig.GS.LimitScalar == 0.0)
text.Write(" (Max)"); text += " (Max)";
else else
text.Write(" (%.0f%%)", EmuConfig.GS.LimitScalar * 100.0); fmt::format_to(std::back_inserter(text), " ({:.0f}%)", EmuConfig.GS.LimitScalar * 100.0);
first = false; first = false;
} }
if (!text.IsEmpty()) if (!text.empty())
{ {
ImU32 color; ImU32 color;
if (speed < 95.0f) if (speed < 95.0f)
@ -572,44 +576,42 @@ static void DrawPerformanceOverlay()
int width, height; int width, height;
GSgetInternalResolution(&width, &height); GSgetInternalResolution(&width, &height);
text.Clear(); text.clear();
text.Write("%dx%d %s %s", width, height, ReportVideoMode(), ReportInterlaceMode()); fmt::format_to(std::back_inserter(text), "{}x{} {} {}", width, height, ReportVideoMode(), ReportInterlaceMode());
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
} }
if (GSConfig.OsdShowCPU) if (GSConfig.OsdShowCPU)
{ {
text.Clear(); text.clear();
text.Write("%.2fms (%.2fms worst)", PerformanceMetrics::GetAverageFrameTime(), fmt::format_to(std::back_inserter(text), "{:.2f}ms ({:.2f}ms worst)", PerformanceMetrics::GetAverageFrameTime(),
PerformanceMetrics::GetWorstFrameTime()); PerformanceMetrics::GetWorstFrameTime());
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
text.Clear(); text.clear();
if (EmuConfig.Speedhacks.EECycleRate != 0 || EmuConfig.Speedhacks.EECycleSkip != 0) if (EmuConfig.Speedhacks.EECycleRate != 0 || EmuConfig.Speedhacks.EECycleSkip != 0)
text.Write("EE[%d/%d]: ", EmuConfig.Speedhacks.EECycleRate, EmuConfig.Speedhacks.EECycleSkip); fmt::format_to(std::back_inserter(text), "EE[{}/{}]: ", EmuConfig.Speedhacks.EECycleRate, EmuConfig.Speedhacks.EECycleSkip);
else else
text.Write("EE: "); text = "EE: ";
FormatProcessorStat(text, PerformanceMetrics::GetCPUThreadUsage(), PerformanceMetrics::GetCPUThreadAverageTime()); FormatProcessorStat(text, PerformanceMetrics::GetCPUThreadUsage(), PerformanceMetrics::GetCPUThreadAverageTime());
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
text.Clear(); text = "GS: ";
text.Write("GS: ");
FormatProcessorStat(text, PerformanceMetrics::GetGSThreadUsage(), PerformanceMetrics::GetGSThreadAverageTime()); FormatProcessorStat(text, PerformanceMetrics::GetGSThreadUsage(), PerformanceMetrics::GetGSThreadAverageTime());
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
const u32 gs_sw_threads = PerformanceMetrics::GetGSSWThreadCount(); const u32 gs_sw_threads = PerformanceMetrics::GetGSSWThreadCount();
for (u32 i = 0; i < gs_sw_threads; i++) for (u32 i = 0; i < gs_sw_threads; i++)
{ {
text.Clear(); text.clear();
text.Write("SW-%u: ", i); fmt::format_to(std::back_inserter(text), "SW-{}: ", i);
FormatProcessorStat(text, PerformanceMetrics::GetGSSWThreadUsage(i), PerformanceMetrics::GetGSSWThreadAverageTime(i)); FormatProcessorStat(text, PerformanceMetrics::GetGSSWThreadUsage(i), PerformanceMetrics::GetGSSWThreadAverageTime(i));
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
} }
if (THREAD_VU1) if (THREAD_VU1)
{ {
text.Clear(); text = "VU: ";
text.Write("VU: ");
FormatProcessorStat(text, PerformanceMetrics::GetVUThreadUsage(), PerformanceMetrics::GetVUThreadAverageTime()); FormatProcessorStat(text, PerformanceMetrics::GetVUThreadUsage(), PerformanceMetrics::GetVUThreadAverageTime());
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
} }
@ -617,8 +619,7 @@ static void DrawPerformanceOverlay()
if (GSConfig.OsdShowGPU) if (GSConfig.OsdShowGPU)
{ {
text.Clear(); text = "GPU: ";
text.Write("GPU: ");
FormatProcessorStat(text, PerformanceMetrics::GetGPUUsage(), PerformanceMetrics::GetGPUAverageTime()); FormatProcessorStat(text, PerformanceMetrics::GetGPUUsage(), PerformanceMetrics::GetGPUAverageTime());
DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255)); DRAW_LINE(s_fixed_font, text.c_str(), IM_COL32(255, 255, 255, 255));
} }

View File

@ -15,6 +15,7 @@
#pragma once #pragma once
#include "Frontend/InputSource.h" #include "Frontend/InputSource.h"
#include "common/RedtapeWindows.h"
#include <Xinput.h> #include <Xinput.h>
#include <array> #include <array>
#include <functional> #include <functional>

View File

@ -19,6 +19,7 @@
#include "Window/GSSetting.h" #include "Window/GSSetting.h"
#include "SaveState.h" #include "SaveState.h"
#include "pcsx2/Config.h" #include "pcsx2/Config.h"
#include "pcsx2/GS/config.h"
#include <map> #include <map>

View File

@ -15,6 +15,8 @@
#pragma once #pragma once
#include "common/AlignedMalloc.h"
template <int i> template <int i>
class GSAlignedClass class GSAlignedClass
{ {

View File

@ -16,6 +16,7 @@
#pragma once #pragma once
#include "GSVector.h" #include "GSVector.h"
#include "pcsx2/Config.h"
#ifdef _WIN32 #ifdef _WIN32
#include "common/RedtapeWindows.h" #include "common/RedtapeWindows.h"

View File

@ -15,6 +15,7 @@
#include "PrecompiledHeader.h" #include "PrecompiledHeader.h"
#include "common/AlignedMalloc.h"
#include "common/FileSystem.h" #include "common/FileSystem.h"
#include "common/StringUtil.h" #include "common/StringUtil.h"

View File

@ -114,7 +114,7 @@ class GSVector8i;
#include "GSVector8i.h" #include "GSVector8i.h"
#include "GSVector8.h" #include "GSVector8.h"
#include "common/Dependencies.h" #include "common/Pcsx2Defs.h"
// conversion // conversion

View File

@ -13,6 +13,8 @@
* If not, see <http://www.gnu.org/licenses/>. * If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "common/Assertions.h"
class alignas(16) GSVector4i class alignas(16) GSVector4i
{ {
static const GSVector4i m_xff[17]; static const GSVector4i m_xff[17];
@ -259,20 +261,6 @@ public:
GSVector4i fit(int preset) const; GSVector4i fit(int preset) const;
#ifdef _WIN32
__forceinline operator LPCRECT() const
{
return (LPCRECT)this;
}
__forceinline operator LPRECT()
{
return (LPRECT)this;
}
#endif
// //
__forceinline u32 rgba32() const __forceinline u32 rgba32() const

View File

@ -13,6 +13,8 @@
* If not, see <http://www.gnu.org/licenses/>. * If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <cassert>
#if _M_SSE >= 0x500 #if _M_SSE >= 0x500
class alignas(32) GSVector8 class alignas(32) GSVector8

View File

@ -13,6 +13,8 @@
* If not, see <http://www.gnu.org/licenses/>. * If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <cassert>
#if _M_SSE >= 0x501 #if _M_SSE >= 0x501
class alignas(32) GSVector8i class alignas(32) GSVector8i

View File

@ -15,6 +15,8 @@
#pragma once #pragma once
#include "common/AlignedMalloc.h"
template <class T> template <class T>
struct Element struct Element
{ {

Some files were not shown because too many files have changed in this diff Show More