This commit is contained in:
jeanlemotan
2024-07-02 18:10:39 +02:00
commit 48ab06b1d9
733 changed files with 321088 additions and 0 deletions
@@ -0,0 +1,57 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include "EAMain/EAMain.h"
#include "EABase/eabase.h"
#include "EAAssert/eaassert.h"
#include <EAMain/internal/EAMainPrintManager.h>
#include <EAMain/internal/EAMainChannels.h>
#include <EABase/eabase.h>
EA_DISABLE_ALL_VC_WARNINGS()
#include <stdio.h>
#include <string.h>
EA_RESTORE_ALL_VC_WARNINGS()
namespace EA {
namespace EAMain {
//------------------------------------------------------------
// Printf Channel
//------------------------------------------------------------
void PrintfChannel::Send(const char8_t* pData)
{
// Route to default print function
EA::EAMain::GetDefaultReportFunction()(pData);
}
//------------------------------------------------------------
// File Channel
//------------------------------------------------------------
void FileChannel::Init()
{
mFileHandle = fopen("eamain_output.txt", "w");
EA_ASSERT_MSG(mFileHandle, "invalid file handle");
}
//------------------------------------------------------------
void FileChannel::Send(const char8_t* pData)
{
EA_ASSERT_MSG(mFileHandle, "invalid file handle");
fputs(pData, mFileHandle);
}
//------------------------------------------------------------
void FileChannel::Shutdown()
{
EA_ASSERT_MSG(mFileHandle, "invalid file handle");
fclose(mFileHandle);
}
//------------------------------------------------------------
}}
@@ -0,0 +1,154 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <EAMain/EAMain.h>
#include <EAMain/internal/EAMainPrintManager.h>
#include <EAMain/internal/EAMainChannels.h>
#include <internal/NetworkChannel.h>
#include <EAAssert/eaassert.h>
#include <EAStdC/EAString.h>
#include <EAMainPrintf.h>
#include <EABase/eabase.h>
EA_DISABLE_ALL_VC_WARNINGS()
#include <string.h>
EA_RESTORE_ALL_VC_WARNINGS()
namespace EA {
namespace EAMain {
//------------------------------------------------------------
// STATICS
//------------------------------------------------------------
static PrintManager gPrintManager;
static PrintfChannel gPrintfChannel;
static FileChannel gFileChannel;
//------------------------------------------------------------
//------------------------------------------------------------
PrintManager& PrintManager::Instance()
{
return gPrintManager;
}
//------------------------------------------------------------
PrintManager::PrintManager()
{
memset(m_Channels, 0, sizeof(m_Channels));
}
//------------------------------------------------------------
void PrintManager::Send(const char8_t* pData)
{
// Broadcast the message to all the registered channels.
for(int i = 0; i < CHANNEL_MAX; i++)
{
if(m_Channels[i])
m_Channels[i]->Send(pData);
}
}
//------------------------------------------------------------
void PrintManager::Add(EAMainChannel channel, IChannel* instance)
{
EA_ASSERT_MSG(instance, "invalid channel instance");
EA_ASSERT_MSG(m_Channels[channel] == NULL, "channel already added to the list");
if(instance != NULL && m_Channels[channel] == NULL)
{
// Initialize the channel, then add it to the channel vector.
instance->Init();
// Add the channel to the array
m_Channels[channel] = instance;
}
}
//------------------------------------------------------------
void PrintManager::ClearChannel(EAMainChannel channel)
{
if (m_Channels[channel] != NULL)
{
IChannel* instance = m_Channels[channel];
// Shut down the channel.
instance->Shutdown();
// Remove the channel from the array.
m_Channels[channel] = NULL;
}
}
//------------------------------------------------------------
void PrintManager::Remove(EAMainChannel channel, IChannel* instance)
{
EA_ASSERT_MSG(instance, "invalid channel instance");
EA_ASSERT_MSG(m_Channels[channel] != NULL, "channel not added to list yet");
if(instance != NULL && m_Channels[channel] != NULL)
{
// Shut down the channel.
instance->Shutdown();
// Remove the channel from the array.
m_Channels[channel] = NULL;
}
}
//------------------------------------------------------------
void PrintManager::Startup(const char8_t* printServerAddress)
{
// Register PrintManager print function with the reporting module.
//
#if EAMAIN_DISABLE_DEFAULT_NETWORK_CHANNEL
if (!printServerAddress)
{
Add(CHANNEL_PRINTF, &gPrintfChannel);
return;
}
#endif
EA::EAMain::SetReportFunction(EA::EAMain::Messages::Print);
if (!printServerAddress)
{
printServerAddress = MACRO_TO_STRING(EAMAIN_NETWORK_CHANNEL_IP);
}
const char8_t* server = printServerAddress;
const char8_t* portStr = strchr(printServerAddress, ':');
int port = EAMAIN_NETWORK_CHANNEL_PORT;
char8_t serverBuff[64] = { 0 };
if (portStr != NULL)
{
port = EA::StdC::AtoI32(portStr + 1);
server = EA::StdC::Strncpy(serverBuff, server, portStr - server);
}
IChannel *networkChannel = Internal::CreateNetworkChannel(server, port);
if (networkChannel)
{
Add(CHANNEL_NETWORK, networkChannel);
}
else
{
Add(CHANNEL_PRINTF, &gPrintfChannel);
}
}
//------------------------------------------------------------
void PrintManager::Shutdown()
{
for(int i = 0; i < CHANNEL_MAX; i++)
{
if(m_Channels[i])
{
m_Channels[i]->Shutdown();
m_Channels[i] = NULL;
}
}
}
}}
@@ -0,0 +1,166 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <EAMain/internal/EAMainStartupShutdown.h>
#include <EAMain/EAMain.h>
#include <EAMain/EAMainExit.h>
#ifdef _MSC_VER
#pragma warning(push, 0) // Microsoft headers generate warnings at our higher warning levels.
#pragma warning(disable: 4702) // Unreachable code detected.
#endif
#if defined(EA_PLATFORM_MICROSOFT)
#if defined(EA_PLATFORM_WINDOWS_PHONE) || defined(EA_PLATFORM_WINRT)
#define EAMAIN_HAVE_UNHANDLED_EXCEPTION_FILTER 0
#else
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#if defined(EA_PLATFORM_CAPILANO)
#include <xdk.h>
#endif
EA_DISABLE_ALL_VC_WARNINGS();
#include <Windows.h>
#include <DbgHelp.h>
EA_RESTORE_ALL_VC_WARNINGS();
#include <EAStdC/EASprintf.h>
#define EAMAIN_HAVE_UNHANDLED_EXCEPTION_FILTER 1
#endif
#endif
#if !defined(EAMAIN_HAVE_UNHANDLED_EXCEPTION_FILTER)
#define EAMAIN_HAVE_UNHANDLED_EXCEPTION_FILTER 0
#endif
namespace EA
{
namespace EAMain
{
namespace Internal
{
#if EAMAIN_HAVE_UNHANDLED_EXCEPTION_FILTER
static LONG WINAPI EAMainUnhandledExceptionFilter(LPEXCEPTION_POINTERS exception)
{
EA::EAMain::Report("\n");
EA::EAMain::Report("===============================================================================\n");
EA::EAMain::Report("ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION\n");
EA::EAMain::Report("An unhandled exception has been detected. This likely means the application is \n");
EA::EAMain::Report("crashing.\n\n");
EA::EAMain::Report("(This message is courtesy of EAMain but does not mean that EAMain is\n");
EA::EAMain::Report("the cause of the crash.)\n");
EA::EAMain::Report("===============================================================================\n");
#if EAMAIN_MINIDUMP_SUPPORTED
char8_t szPath[MAX_PATH];
char8_t szFileName[MAX_PATH];
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
BOOL bMiniDumpSuccessful;
#if defined(EA_PLATFORM_CAPILANO)
const char8_t* pszDrive = "G:\\";
#else
const char8_t* pszDrive = "C:\\";
#endif
GetLocalTime( &stLocalTime );
EA::StdC::Snprintf(szPath, EAArrayCount(szPath), "%sMiniDumps\\", pszDrive);
CreateDirectoryA(szPath, NULL );
EA::StdC::Snprintf(szFileName, EAArrayCount(szFileName), "%sMiniDump-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
EA::EAMain::Report("Creating Dump File: %s - ", szFileName);
hDumpFile = CreateFileA(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
EA::EAMain::Report("%s (Error: %d) \n", hDumpFile != INVALID_HANDLE_VALUE ? "Success" : "Failure", hDumpFile != INVALID_HANDLE_VALUE ? 0 : HRESULT_FROM_WIN32(GetLastError()));
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = exception;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, NULL, NULL);
EA::EAMain::Report("Dump %s (Error: %d)\n", bMiniDumpSuccessful == TRUE ? "Successful" : "Failed - so deleted minidump file", bMiniDumpSuccessful == TRUE ? 0 : HRESULT_FROM_WIN32(GetLastError()));
if (bMiniDumpSuccessful == FALSE)
{
DeleteFileA(szFileName);
}
#endif
EAMainShutdown(1);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
void EAMainStartup(const char8_t* printServerAddress)
{
static bool sEAMainShutdown_StartupHandled = false;
if(!sEAMainShutdown_StartupHandled)
{
sEAMainShutdown_StartupHandled = true;
#if EAMAIN_HAVE_UNHANDLED_EXCEPTION_FILTER
SetUnhandledExceptionFilter(EAMainUnhandledExceptionFilter);
#endif
// Running under NAnt output only appears when the buffer is filled if we allow the default buffering scheme for printf.
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
setvbuf(stderr, NULL, _IONBF, BUFSIZ);
// Startup the print manager
//
EA::EAMain::PrintManager::Instance().Startup(printServerAddress);
}
}
int EAMainShutdown(int errorCount)
{
static bool sEAMainShutdown_ShutdownHandled = false;
if(!sEAMainShutdown_ShutdownHandled)
{
sEAMainShutdown_ShutdownHandled = true;
// Handle the application specific exit code.
//
#if defined(EA_PLATFORM_IPHONE)
// Get test result. (iOS 5 bug prevents iPhone Runner from getting this from the exit code)
if (errorCount == 0)
Report("\nAll tests completed successfully.\n");
else
Report("\nTests failed. Total error count: %d\n", errorCount);
fflush(stdout);
#endif
#if !defined(EA_PLATFORM_DESKTOP) && !defined(EA_PLATFORM_SERVER) // TODO: change define to something related to the StdC library used on the system.
fflush(stdout);
#endif
// Required so the EAMainPrintServer can terminate with the correct error code.
//
EA::EAMain::Report("\nRETURNCODE=%d\n", errorCount);
// Shutdown the EAMain print manager.
//
EA::EAMain::PrintManager::Instance().Shutdown();
}
return errorCount;
}
}
}
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
@@ -0,0 +1,603 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <EABase/eabase.h>
#include <EAAssert/eaassert.h>
#include <EAMain/internal/EAMainChannels.h>
#if defined(EA_PLATFORM_IPHONE)
#define EAMAIN_HAS_NETWORK_CHANNEL 1
#define EAMAIN_FREOPEN_SUPPORTED 1
#endif
#if defined(EA_PLATFORM_WINRT)
#define EAMAIN_HAS_NETWORK_CHANNEL 1
#define EAMAIN_FREOPEN_SUPPORTED 0
#endif
#if defined(EA_PLATFORM_WINDOWS_PHONE) && !defined(EAMAIN_HAS_NETWORK_CHANNEL)
#define EAMAIN_HAS_NETWORK_CHANNEL 1
#define EAMAIN_FREOPEN_SUPPORTED 0
#endif
// winrt-arm configurations do not have winsock, so for these configurations
// we disable the use of the network channel.
#if defined(_MSC_VER) && !defined(EA_PLATFORM_WINDOWS_PHONE) && defined(EA_PROCESSOR_ARM) && defined(EAMAIN_HAS_NETWORK_CHANNEL)
#undef EAMAIN_HAS_NETWORK_CHANNEL
#endif
#if defined(EA_PLATFORM_CAPILANO) && !defined(EAMAIN_HAS_NETWORK_CHANNEL)
#define EAMAIN_HAS_NETWORK_CHANNEL 1
#define EAMAIN_FREOPEN_SUPPORTED 1
#endif
#if !defined(EAMAIN_HAS_NETWORK_CHANNEL)
#define EAMAIN_HAS_NETWORK_CHANNEL 0
#endif
#if !defined(EAMAIN_FREOPEN_SUPPORTED)
#define EAMAIN_FREOPEN_SUPPORTED 0
#endif
#if EAMAIN_HAS_NETWORK_CHANNEL
#if defined(_MSC_VER)
EA_DISABLE_ALL_VC_WARNINGS()
#if defined(WINAPI_FAMILY)
#undef WINAPI_FAMILY
#endif
#define WINAPI_FAMILY WINAPI_FAMILY_DESKTOP_APP
#include <WinSock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#if defined(EA_PLATFORM_WINDOWS_PHONE)
#pragma warning(disable:4265)
#include <thread>
#else
// Restoring VC warnings on Windows Phone causes some warnings to pop
// up down below, emanating from std::thread. In order to have some
// coverage of this code, warnings are re-enabled on other platforms.
EA_RESTORE_ALL_VC_WARNINGS()
#endif
#define SocketGetLastError() WSAGetLastError()
#define snprintf _snprintf
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#if !defined(EA_PLATFORM_SONY)
#include <netdb.h>
#else
#include <net.h>
#endif
#include <string.h>
#include <unistd.h>
typedef int SOCKET;
const int INVALID_SOCKET = -1;
const int SOCKET_ERROR = -1;
#define SD_SEND SHUT_WR
#define closesocket close
#define WSAECONNREFUSED ECONNREFUSED
#define WSAENETUNREACH ENETUNREACH
#define SocketGetLastError() errno
#endif
#include <stdio.h>
#include "eathread/eathread_thread.h"
#include "EAStdC/EAMemory.h"
#include "EAStdC/EAString.h"
#include "EAStdC/EASprintf.h"
namespace EA
{
namespace EAMain
{
namespace Internal
{
class NetworkChannel : public IChannel
{
SOCKET m_socket;
char m_serverAddressStorage[128];
char m_port[6];
const char *m_serverAddress;
static void SleepThread(int milliseconds);
public:
NetworkChannel();
virtual ~NetworkChannel();
virtual void Init();
virtual void Send(const char8_t *data);
virtual void Shutdown();
void SetServerPort(const char *server, const char *port);
bool Connect();
};
static NetworkChannel g_NetworkChannelInstance;
void NetworkChannel::SleepThread(int milliseconds)
{
#if defined(_MSC_VER)
#if defined(EA_PLATFORM_WINDOWS_PHONE)
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
#else
Sleep(milliseconds);
#endif
#else
usleep(milliseconds * 1000);
#endif
}
NetworkChannel::NetworkChannel()
: m_socket(INVALID_SOCKET)
, m_serverAddress(&m_serverAddressStorage[0])
{
EA::StdC::Memset8(m_serverAddressStorage, 0, sizeof m_serverAddressStorage);
EA::StdC::Memset8(m_port, 0, sizeof m_port);
#if defined(_MSC_VER)
WSAData wsaData = {};
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
}
static void LogNetworkError(const char *format, ...)
{
(void)format;
}
NetworkChannel::~NetworkChannel()
{
#if defined(_MSC_VER)
WSACleanup();
#endif
}
void NetworkChannel::Init()
{
}
void NetworkChannel::Send(const char8_t *data)
{
char *buffer = const_cast<char *>(data);
ssize_t bufferLength = static_cast<ssize_t>(strlen(buffer));
ssize_t bytesSent = 0;
while (bytesSent < bufferLength)
{
ssize_t result = send(m_socket, buffer + bytesSent, static_cast<int>(bufferLength - bytesSent), 0);
if (result == SOCKET_ERROR)
{
bool reconnected = false;
LogNetworkError("[NetworkChannel::Send] Reconnecting...");
for (int i = 0; i < 20; ++i)
{
Shutdown();
if (!Connect())
{
LogNetworkError("[NetworkChannel::Send] Send failed: %d", SocketGetLastError());
}
else
{
reconnected = true;
break;
}
SleepThread(500);
}
if (!reconnected)
{
LogNetworkError("[NetworkChannel::Send] Unable to connect, aborting.");
return;
}
}
else
{
bytesSent += result;
}
}
}
void NetworkChannel::Shutdown()
{
// Closing the socket does not wait for pending data to be sent.
// To ensure that all data has been sent, the write end of the
// socket must first be shut down. This sends a FIN packet to
// the receiver after all data has been sent and acknowledged
// by the receiver. This must also be paired with a call to
// recv to ensure that all pending readable data has been
// read.
shutdown(m_socket, SD_SEND);
char buffer[128];
for (;;)
{
ssize_t rv = recv(m_socket, buffer, (int)sizeof buffer, 0);
if (rv <= 0)
{
// We can assume that a graceful shutdown has occurred
// when rv == 0. If rv < 0 an error has occurred, but
// we are not at a point where we can easily recover, so
// this code will just shutdown the socket and exit the
// program if an error happens here.
break;
}
}
closesocket(m_socket);
m_socket = INVALID_SOCKET;
}
void NetworkChannel::SetServerPort(const char *server, const char *port)
{
using namespace EA::StdC;
// If, somehow, the server name string is longer than the storge
// allocated, allocate some space for it on the C-heap. Not ideal,
// may actually fail some tests, but the alternative would be
// no output from EAMain at all.
if (Strlcpy(m_serverAddressStorage, server, sizeof m_serverAddressStorage) > (sizeof m_serverAddressStorage))
{
size_t serverNameLength = Strlen(server);
char *ptr = static_cast<char *>(calloc(serverNameLength + 1, 1));
Strlcpy(ptr, server, serverNameLength + 1);
m_serverAddress = ptr;
}
// Valid port numbers are in the range [1, 65535] so will have
// always 5 digits max.
EA_ASSERT(sizeof m_port == 6);
Strlcpy(m_port, port, sizeof m_port);
}
bool NetworkChannel::Connect()
{
EA_ASSERT(m_serverAddress != NULL);
EA_ASSERT(m_port != NULL);
bool result = false;
SOCKET remoteSocket = INVALID_SOCKET;
const int MAX_RETRIES = 250;
#if !defined(EA_PLATFORM_SONY)
struct addrinfo hints = {};
hints.ai_socktype = SOCK_STREAM;
addrinfo *p = NULL;
if (getaddrinfo(m_serverAddress, m_port, &hints, &p) != 0)
{
LogNetworkError("[NetworkChannel::Connect] Cannot connect to %s:%s", m_serverAddress, m_port);
goto ErrorReturn;
}
for (struct addrinfo *endpoint = p; endpoint != NULL; endpoint = endpoint->ai_next)
#endif
{
#if !defined(EA_PLATFORM_SONY)
remoteSocket = socket(endpoint->ai_family, endpoint->ai_socktype, endpoint->ai_protocol);
#else
remoteSocket = sceNetSocket("EAMain Socket", SCE_NET_AF_INET, SCE_NET_SOCK_STREAM, 0);
#endif
if (remoteSocket == INVALID_SOCKET)
{
LogNetworkError("[NetworkChannel::Connect] Cannot create socket");
goto ErrorReturn;
}
#if defined(_MSC_VER)
if (endpoint->ai_family == AF_INET6)
{
DWORD v6only = 0;
setsockopt(remoteSocket, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof v6only);
}
#endif
for (int i = 0; i < MAX_RETRIES; ++i)
{
#if !defined(EA_PLATFORM_SONY)
int connectResult = connect(remoteSocket, endpoint->ai_addr, (int)endpoint->ai_addrlen);
#else
char *p;
SceNetInPort_t port = strtol(m_port, &p, 10);
SceNetSockaddrIn sin;
EA::StdC::Memset8(&sin, 0, sizeof sin);
sin.sin_len = sizeof(sin);
sin.sin_family = SCE_NET_AF_INET;
if (sceNetInetPton(SCE_NET_AF_INET, m_serverAddress, &sin.sin_addr) <= 0)
{
LogNetworkError("[NetworkChannel::Connect] Cannot connect to %s:%s", m_serverAddress, m_port);
goto ErrorReturn;
}
sin.sin_port = sceNetHtons(port);
sin.sin_vport = sceNetHtons(SCE_NET_ADHOC_PORT);
int connectResult = sceNetConnect(remoteSocket, (SceNetSockaddr *)&sin, sizeof(sin));
#endif
if (connectResult == 0)
{
result = true;
m_socket = remoteSocket;
goto SuccessReturn;
}
switch (SocketGetLastError())
{
case WSAENETUNREACH:
SleepThread(20);
continue;
default:
LogNetworkError("[NetworkChannel::Connect] Cannot connect to socket");
goto ErrorReturn;
}
}
}
ErrorReturn:
if (remoteSocket != INVALID_SOCKET)
{
LogNetworkError("[NetworkChannel::Connect] FAILED");
closesocket(remoteSocket);
}
SuccessReturn:
#if !defined(EA_PLATFORM_SONY)
if (p)
{
freeaddrinfo(p);
}
#endif
return result;
}
static IChannel *CreateNetworkChannelImpl(const char *server, int port)
{
char portString[6];
if (port > 65536 || port < 0)
{
return NULL;
}
snprintf(portString, sizeof portString, "%d", port);
portString[5] = 0;
g_NetworkChannelInstance.SetServerPort(server, portString);
if (g_NetworkChannelInstance.Connect())
{
return &g_NetworkChannelInstance;
}
return NULL;
}
#if !EAMAIN_FREOPEN_SUPPORTED
IChannel *CreateNetworkChannel(const char *server, int port)
{
// On platforms where we do not support freopen on standard
// IO streams, we create a raw network channel.
return CreateNetworkChannelImpl(server, port);
}
#else
static EA::Thread::Thread g_PrintThread;
static volatile bool g_PrintThreadDone;
static FILE *g_RedirectedStdoutHandle;
static FILE *g_RedirectedStderrHandle;
class StdoutWrapperChannel : public IChannel
{
NetworkChannel &m_channel;
bool m_shutdown;
StdoutWrapperChannel& operator=(const StdoutWrapperChannel&);
StdoutWrapperChannel(const StdoutWrapperChannel&);
public:
StdoutWrapperChannel(NetworkChannel &channel)
: m_channel(channel)
, m_shutdown(false)
{
}
virtual ~StdoutWrapperChannel();
virtual void Init()
{
}
virtual void Send(const char8_t *data)
{
fputs(data, stdout);
fflush(stdout);
}
virtual void Shutdown()
{
if (g_RedirectedStdoutHandle)
{
fclose(g_RedirectedStdoutHandle);
}
if (g_RedirectedStderrHandle)
{
fclose(g_RedirectedStderrHandle);
}
g_PrintThreadDone = true;
if (g_PrintThread.GetStatus() == EA::Thread::Thread::kStatusRunning)
{
g_PrintThread.WaitForEnd();
}
m_channel.Shutdown();
m_shutdown = true;
}
};
StdoutWrapperChannel::~StdoutWrapperChannel()
{
if (!m_shutdown)
{
Shutdown();
}
}
static bool ReadFromFile(FILE *file)
{
static const int BUFFER_SIZE = 1024;
static char buffer[BUFFER_SIZE + 1];
bool haveRead = false;
// This is a tortuous way of checking to see if there is data
// available but the goal here is to prevent this thread from
// blocking if nothing is ready. Blocking could be desirable
// if we were only reading from one stream but because this
// code attempts to read from both stdout and stderr we do not
// want it to block on reading one while the other is receiving
// important information.
// Another possibility would be to use non-blocking IO but this
// would require different implementations for different
// platforms.
long currentPosition = ftell(file);
fseek(file, 0, SEEK_END);
long endPosition = ftell(file);
if (endPosition > currentPosition)
{
size_t bytesAvailable = static_cast<size_t>(endPosition - currentPosition);
fseek(file, currentPosition, SEEK_SET);
while (bytesAvailable > 0)
{
size_t bytesToRead = (bytesAvailable > BUFFER_SIZE) ? BUFFER_SIZE : bytesAvailable;
size_t bytesRead = fread(buffer, 1, bytesToRead, file);
buffer[bytesRead] = 0;
g_NetworkChannelInstance.Send(buffer);
bytesAvailable -= bytesRead;
}
haveRead = true;
}
return haveRead;
}
static char g_StdoutLogPath[256];
static char g_StderrLogPath[256];
static intptr_t PrintFunction(void *)
{
FILE *stdoutLog = fopen(g_StdoutLogPath, "rb");
FILE *stderrLog = fopen(g_StderrLogPath, "rb");
while (!g_PrintThreadDone)
{
// It might look neater to combine these file reads into
// the if statement but this was not done because the
// shortcircuting of the left hand condition prevented
// the right hand condition from being evaluated, but
// every iteration should read from both sources.
bool haveReadStdout = ReadFromFile(stdoutLog);
bool haveReadStderr = ReadFromFile(stderrLog);
if (!haveReadStdout && !haveReadStderr)
{
EA::Thread::ThreadSleep(50);
}
}
fflush(stdout); ReadFromFile(stdoutLog); fclose(stdoutLog);
fflush(stderr); ReadFromFile(stderrLog); fclose(stderrLog);
return 0;
}
IChannel *CreateNetworkChannel(const char *server, int port)
{
#if defined(EA_PLATFORM_CAPILANO)
if (IsDebuggerPresent())
{
return NULL;
}
#endif
EA::Thread::ThreadParameters threadParameters;
char *STDOUT_LOG_NAME = "stdout.log";
const char *STDERR_LOG_NAME = "stderr.log";
threadParameters.mnPriority = EA::Thread::kThreadPriorityMax;
#if defined EA_PLATFORM_IPHONE
char temporaryDirectory[256];
confstr(_CS_DARWIN_USER_TEMP_DIR, temporaryDirectory, sizeof temporaryDirectory);
EA::StdC::Snprintf(g_StdoutLogPath, sizeof g_StdoutLogPath, "%s/%s", temporaryDirectory, STDOUT_LOG_NAME);
EA::StdC::Snprintf(g_StderrLogPath, sizeof g_StderrLogPath, "%s/%s", temporaryDirectory, STDERR_LOG_NAME);
#elif defined EA_PLATFORM_CAPILANO
EA::StdC::Snprintf(g_StdoutLogPath, sizeof g_StdoutLogPath, "T:\\%s", STDOUT_LOG_NAME);
EA::StdC::Snprintf(g_StderrLogPath, sizeof g_StderrLogPath, "T:\\%s", STDERR_LOG_NAME);
#else
EA::StdC::Strlcpy(g_StdoutLogPath, STDOUT_LOG_NAME, sizeof g_StdoutLogPath);
EA::StdC::Strlcpy(g_StderrLogPath, STDERR_LOG_NAME, sizeof g_StderrLogPath);
#endif
fprintf(stdout, ""); fflush(stdout);
fprintf(stderr, ""); fflush(stderr);
g_RedirectedStdoutHandle = freopen(g_StdoutLogPath, "wb", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
g_RedirectedStderrHandle = freopen(g_StderrLogPath, "wb", stderr);
setvbuf(stderr, NULL, _IONBF, 0);
if (CreateNetworkChannelImpl(server, port) != NULL)
{
g_PrintThread.Begin(PrintFunction, NULL, &threadParameters);
}
return new StdoutWrapperChannel(g_NetworkChannelInstance);
}
#endif
}
}
}
#else
namespace EA
{
namespace EAMain
{
namespace Internal
{
IChannel *CreateNetworkChannel(const char *server, int port)
{
return NULL;
}
}
}
}
#endif
@@ -0,0 +1,21 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef EAMAIN_INTERNAL_NETWORKCHANNEL_H
#define EAMAIN_INTERNAL_NETWORKCHANNEL_H
#include <EAMain/internal/EAMainChannels.h>
namespace EA
{
namespace EAMain
{
namespace Internal
{
IChannel *CreateNetworkChannel(const char *connection, int port);
}
}
}
#endif
@@ -0,0 +1,108 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <kernel.h>
#include <sceerror.h>
#include <gnm.h>
#include "EAAssert/eaassert.h"
#define SUBMIT_DEBUG_PRINT(arg)
namespace EA
{
namespace EAMain
{
namespace Internal
{
static ScePthread gSubmitDoneThread;
static SceKernelSema gSubmitDoneSema;
volatile static bool gShutdownSubmitDoneThread = false;
void* SubmitDoneThreadFunction(void *)
{
int result;
EA_UNUSED(result);
SUBMIT_DEBUG_PRINT("Started submit done thread\n");
for(;;)
{
const int microsecondsPerSecond = 1000000;
SceKernelUseconds timeout = 2 * microsecondsPerSecond;
result = sceKernelWaitSema(gSubmitDoneSema, 1, &timeout);
EA_ASSERT(result == SCE_OK || result == SCE_KERNEL_ERROR_ETIMEDOUT);
if(gShutdownSubmitDoneThread)
{
// Break out to avoid calling submitDone
break;
}
else
{
SUBMIT_DEBUG_PRINT("submitDone\n");
#if SCE_ORBIS_SDK_VERSION >= 0x01000051u && SCE_ORBIS_SDK_VERSION != 0x01000071u
// Only perform the submitDone call if we are above SDK version 1.00.051
// but not 1.00.071 since the requirement was temporarily removed in that release.
// This is not required in previous or later SDK versions.
sce::Gnm::submitDone();
#endif
}
}
SUBMIT_DEBUG_PRINT("Ending submit done thread\n");
return nullptr;
}
void StartSubmitDoneThread()
{
int result;
EA_UNUSED(result);
SUBMIT_DEBUG_PRINT("Starting submit done thread\n");
result = sceKernelCreateSema(&gSubmitDoneSema, "submit done semaphore", 0, 0, 1, nullptr);
EA_ASSERT(result == SCE_OK);
result = scePthreadCreate(&gSubmitDoneThread, NULL, SubmitDoneThreadFunction, NULL, "submit done thread");
EA_ASSERT(result == SCE_OK);
}
void ShutdownSubmitDoneThread()
{
if(!gShutdownSubmitDoneThread)
{
SUBMIT_DEBUG_PRINT("Disabling submit done thread\n");
int result;
EA_UNUSED(result);
// Indicate that the submit done thread should exit
gShutdownSubmitDoneThread = true;
// Signal semaphore to unblock the submit done thread
result = sceKernelSignalSema(gSubmitDoneSema, 1);
EA_ASSERT(result == SCE_OK);
// Wait for the thread to exit
result = scePthreadJoin(gSubmitDoneThread, nullptr);
EA_ASSERT(result == SCE_OK);
// Free up kernel resources
result = sceKernelDeleteSema(gSubmitDoneSema);
EA_ASSERT(result == SCE_OK);
}
}
}
void DisableSubmitDoneThread()
{
using namespace EA::EAMain::Internal;
ShutdownSubmitDoneThread();
}
}
}
#undef SUBMIT_DEBUG_PRINT