123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604 |
- #include "stdafx.h"
- #include "SpBase.h"
- #include "SpTimer.h"
- #include "SpEntity.h"
- #include "SpModule.h"
- #ifdef WIN32
- #include "SpBaseRoutine.h"
- #endif
- #include "SpMisc.h"
- #include "SpClientSessionFunction.h"
- #include "sockutil.h"
- #include "fileutil.h"
- #include "sp_shm.h"
- #include "sp_dbg_export.h"
- #include "sp_def.h"
- #include "sp_env.h"
- #include "DumpException.h"
- #ifdef _WIN32
- #include "sp_checkEntity.h"
- #include <DbgHelp.h>
- #else
- #include <exception>
- #endif // _WIN32
- #include<winpr//library.h>
- #include <winpr/locale.h>
- #include <winpr/exception.h>
- #ifndef _WIN32
- static SpModule* g_module = NULL;
- #endif //NOT _WIN32
- SpModule *GetSpModule()
- {
- #ifdef _WIN32
- SpModule *curModule = NULL;
- if (findThreadModule(GetCurrentThreadId(), (void **)&curModule))
- return curModule;
- else
- {
- CSimpleStringA mod_name = TraceStack();
- if (CSimpleStringA("") == mod_name) {
- return NULL;
- }
- SetthreadGroup(GetCurrentThreadId(), mod_name);
- if (findThreadModule(GetCurrentThreadId(), (void**)&curModule))
- return curModule;
- }
- return NULL;
- #else
- return g_module;
- #endif //_WIN32
- }
- #ifdef _WIN32
- static LONG WINAPI SuppressError(struct _EXCEPTION_POINTERS* ExceptionInfo)
- {
- char tmp[MAX_PATH] = { '\0' };
- char drivePath[_MAX_DRIVE] = {'\0'};
- sp_dir_get_cur_drive(drivePath);
- wsprintfA(tmp, "%s\\rvc\\dmp\\expt.%s.%d.%d.log", drivePath, GetSpModule() ? GetSpModule()->get_mod()->cfg->name : "", GetCurrentThreadId(), GetCurrentProcessId());
- HANDLE hLogFile = ::CreateFileA(tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
- if (hLogFile != INVALID_HANDLE_VALUE) {
- DumpExceptionInfo(ExceptionInfo, hLogFile);
- FlushFileBuffers(hLogFile);
- SetEndOfFile(hLogFile);
- CloseHandle(hLogFile);
- }
- wsprintfA(tmp, "%s\\rvc\\dmp\\expt.%s.%d.%d.dmp", drivePath, GetSpModule() ? GetSpModule()->get_mod()->cfg->name : "", GetCurrentThreadId(), GetCurrentProcessId());
- HANDLE hDumpFile = CreateFileA( tmp, GENERIC_READ | GENERIC_WRITE,
- 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
- if( ( hDumpFile != NULL ) && ( hDumpFile != INVALID_HANDLE_VALUE ) )
- {
- MINIDUMP_EXCEPTION_INFORMATION mdei;
- mdei.ThreadId = GetCurrentThreadId();
- mdei.ExceptionPointers = ExceptionInfo;
- mdei.ClientPointers = FALSE;
- MINIDUMP_TYPE mdt = MiniDumpWithIndirectlyReferencedMemory;
- BOOL rv = MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
- hDumpFile, mdt, (ExceptionInfo != 0) ? &mdei : 0, 0, 0 );
- CloseHandle( hDumpFile );
- }
- Dbg("exit entity exception!");
- ExitProcess(Error_Exception); // exit process to suppress reporting exception
- return EXCEPTION_EXECUTE_HANDLER;
- }
- static void DisableSetUnhandledExceptionFilter()
- {
- void* addr = (void*)GetProcAddress(LoadLibrary("kernel32.dll"), "SetUnhandledExceptionFilter");
- if (addr) {
- DWORD dwOldFlag, dwTempFlag;
- unsigned char code[] = {0x33, 0xC0, 0xC2, 0x04, 0x00}; // xor eax,eax; ret 4;
- VirtualProtect(addr, sizeof(code), PAGE_READWRITE, &dwOldFlag);
- WriteProcessMemory(GetCurrentProcess(), addr, code, sizeof(code), NULL);
- VirtualProtect(addr, sizeof(code), dwOldFlag, &dwTempFlag);
- }
- }
- #endif //_WIN32
- SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage)
- {//MAX string len < 1024
- SpModule *pModule = GetSpModule();
- if (pModule) {
- pModule->LogMessage(Log_Event, eLevel, 0, dwUserEventCode, pszMessage);
- }
- // write a copy in dbg log
- sp_dbg_info("Event: {%s}(uc=0x%X)", pszMessage, dwUserEventCode);
- }
- SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage)
- {
- SpModule *pModule = GetSpModule();
- if (pModule) {
- pModule->LogMessage(Log_Error, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
- }
- else
- sp_dbg_info("LogError failed!can not find the module");
- // write a copy in dbg log
- sp_dbg_error("Error: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
- }
- SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage)
- {
- SpModule *pModule = GetSpModule();
- if (pModule) {
- pModule->LogMessage(Log_Warning, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
- }
- // write a copy in dbg log
- sp_dbg_warn("Warn: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
- }
- SPBASE_API void LogAssert(const char *pszMessage,const char *pszFile,const int nLine)
- {
- SpModule *pModule = GetSpModule();
- if (pModule) {
- pModule->LogMessage(Log_Debug, Severity_Middle, 0, 0,
- CSimpleStringA::Format("assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
- pszMessage, _GetFileName(pszFile), nLine,
- #ifdef _WIN32
- (const char*)DumpStack(2)
- #else
- "not implement, TODO:"
- #endif //_WIN32
- ));
- }
- // write a copy in dbg log
- sp_dbg_debug("Assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
- pszMessage, _GetFileName(pszFile), nLine,
- #ifdef _WIN32
- (const char*)DumpStack(2)
- #else
- "not implement, TODO:"
- #endif //_WIN32
- );
- }
- SPBASE_API void LogTrace(const char *pszMessage,const char *pszFile,const int nLine)
- {
- sp_dbg_debug("========Trace: {%s}, file: {%s}, line: {%d}", pszMessage, _GetFileName(pszFile), nLine);
- SpModule *pModule = GetSpModule();
- if (pModule) {
- pModule->LogMessage(Log_Debug, Severity_None, 0, 0, pszMessage);
- }
- // write a copy in dbg log
- sp_dbg_debug("Trace: {%s}, file: {%s}, line: {%d}", pszMessage, _GetFileName(pszFile), nLine);
- }
- #include "log.h"
- #include <malloc.h>
- extern "C" SPBASE_API void Dbg(const char *str, ...)
- {
- va_list arg;
- va_start(arg, str);
- vDbg(str, arg);
- va_end(arg);
- }
- extern "C" SPBASE_API void vDbg(const char *str, va_list list)
- {
- int n = _vscprintf(str, list);
- if (n > 1024)
- n = 1024;
- char *buf = (char*)_alloca(n+1);
- memset(buf, 0, n+1);
- /*write at most n bytes(including the terminating null byte '\0') to buf*/
- vsnprintf(buf, n+1, str, list); // plus 1 to n, never changed code but the log lost one char [4/1/2020 16:25 Gifur]
-
- sp_dbg_debug("Debug: {%s}", buf); //打印到文件
-
- //修改,不发出Log_Debug类消息
- //SpModule* pModule = GetSpModule();
- // if (pModule)
- // {
- // __try
- // {
- // SpEntity *pEntity = (SpEntity*)(getEntityResource()->m_Entity);
- //
- // if (pEntity != NULL)
- // {
- // auto pEntCfg = pEntity->get_cfg_ent();
- // if (pEntCfg != NULL && pEntCfg->debug_level > 0)
- // {
- // pEntity->LogMessage(Log_Debug, Severity_None, -1, -1, buf);
- // }
- // }
- // }
- // __finally
- // {
- //
- // }
- // }
- }
- static bool RegistMain(HMODULE hModule,EntryRoutine Main, EntryRoutine Exit)
- {
- SpModule::SetEntryRoutine(Main, Exit);
- return true;
- }
- static HMODULE LoadModuleLibrary(sp_mod_t *mod)
- {
- sp_env_t *env = sp_get_env();
- char tmp[MAX_PATH];
- sp_dir_get_path(env->dir, SP_DIR_MODULE_BIN, mod->cfg->name, tmp, sizeof(tmp));
- return LoadLibraryA(tmp);
- }
- SPBASE_API HINSTANCE SpLoadLibrary(const char *file)
- {
- sp_env_t *env = sp_get_env();
- if (env) {
- char tmp[MAX_PATH];
- #ifdef _WIN32
- sprintf(tmp, "%s\\%s", env->dir->dep_path, file);
- #else
- sprintf(tmp, "%s/%s", env->dir->dep_path, file);
- #endif //_WIN32
- return LoadLibraryA(tmp);
- } else {
- return NULL;
- }
- }
- #ifdef _WIN32
- extern "C" SPBASE_API int __stdcall SpExit(const char* mod_name)
- {
- Dbg("Do SpExit!");
- SetthreadGroup(GetCurrentThreadId(), mod_name);
- CleanModuleThread(mod_name);
- sp_iom_stop(GetSpModule()->get_iom());
- GetSpModule()->Term();
- sp_shm_term();
- sp_dbg_term();
- sp_iom_destroy(GetSpModule()->get_iom());
- delete GetSpModule();
- //winsock_term();
- FreeLibrary(getEntityResource()->m_Module);
- DestoryModuleInfo(mod_name);
- return 0;
- }
- #endif //_WIN32
- extern "C" SPBASE_API int __stdcall SpRun(const char *mod_name, int epid, int range, int group)
- {
- ErrorCodeEnum Error = Error_Unexpect;
- if (!mod_name)
- return Error_Bug;
- if (epid == SP_INVALID_MOD_ID)
- return Error_Bug;
- #ifdef _WIN32
- if (findModuleByName(mod_name)) //检测实体是否已创建
- SpExit(mod_name);
- bool result = group == 0 ? CreateModuleInfo(ENTITY_SINGLE_GROUPNAME) : CreateModuleInfo(mod_name);
- //the SetthreadGroup routine would never return false, so the group variable must be not-zero
- if (!result || !SetthreadGroup(GetCurrentThreadId(), mod_name))
- return Error_Duplication;
- #else
- if (g_module) {
- return Error_Duplication;
- }
- #endif //_WIN32
- if (winsock_init() != 0) {
- return Error_NetBroken;
- }
- sp_dbg_init(mod_name);
- sp_dbg_info("==============SpRun(%s) start==============", mod_name);
- sp_dbg_info("process id: %d", GetCurrentProcessId());
-
- void *hint_addr = sp_shm_init(range, FALSE);
- if (!hint_addr) {
- sp_dbg_warn("shm init failed! hint_addr: 0x%08x", hint_addr);
- return Error_Unexpect;
- }
- sp_dbg_info("shm init ok! hint_addr: 0x%08x", hint_addr);
- sp_env_t *env = sp_get_env();
- if (!env) {
- sp_dbg_warn("module env object init failed!");
- return Error_Unexpect;
- }
- sp_dbg_info("retrieve env object ok!");
- sp_mod_t *mod = sp_mod_mgr_find_module_by_idx(env->mod_mgr, epid);
- if (!mod) {
- sp_dbg_warn("find shm module object failed!");
- return Error_NotExist;
- }
- sp_dbg_info("find module %s id %d ok!", mod->cfg->name, mod->cfg->idx);
- sp_dbg_info("module %s file version: %d.%d.%d.%d", mod->cfg->name,
- mod->cfg->version.major,
- mod->cfg->version.minor,
- mod->cfg->version.revision,
- mod->cfg->version.build);
- SpInitUUID((WORD)mod->cfg->idx);
- sp_cfg_shell_module_t *cfg_mod = sp_cfg_get_module_by_idx(env->cfg, epid);
- if (!cfg_mod) {
- sp_dbg_warn("get module %s cfg object failed!", mod->cfg->name);
- return Error_Bug;
- }
- sp_dbg_info("find cfg module object %s id %d ok!", cfg_mod->name, cfg_mod->idx);
- #ifdef _WIN32
- SetUnhandledExceptionFilter(&SuppressError);
- //DisableSetUnhandledExceptionFilter();
- #endif //_WIN32
- #ifdef _WIN32
- SpModule* curModule = new SpModule(mod, cfg_mod);
- getEntityResource()->m_Module = LoadModuleLibrary(mod);
- if (!getEntityResource()->m_Module) {
- sp_dbg_warn("load module library %s failed! GetLastError = %d", mod->cfg->name, GetLastError());
- goto on_error;
- }
- curModule->getEntryRoutine(&(getEntityResource()->m_pfMain), &(getEntityResource()->m_pfExit));
- Error = curModule->Init(env->url);
- if (Error) {
- delete curModule;
- curModule = NULL;
- goto on_error;
- }
- #else
- g_module = new SpModule(mod, cfg_mod);
- HMODULE hModule = LoadModuleLibrary(mod);
- if (!hModule) {
- sp_dbg_warn("load module library %s failed! GetLastError = %d", mod->cfg->name, GetLastError());
- goto on_error;
- }
- Error = g_module->Init(env->url);
- if (Error) {
- delete g_module;
- g_module = NULL;
- goto on_error;
- }
- #endif //_WIN32
- sp_dbg_debug("before set thread priority");
- SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
- sp_dbg_debug("after set thread priority");
- #ifdef _WIN32
- if (!SetSpModule(mod_name, curModule))
- goto on_error;
- Error = curModule->Run();
- curModule->Term();
- FreeLibrary(getEntityResource()->m_Module);
- delete curModule;
- curModule = NULL;
- #else
- Error = g_module->Run();
- g_module->Term();
- FreeLibrary(hModule);
- #endif //_WIN32
- sp_shm_term();
- on_error:
- return Error;
- }
- SPBASE_API CSimpleStringA GetSysErrMsg(int nErrCode)
- {
- char szBuf[2048] = {};
- DWORD dwRet = FormatMessageA(
- FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- nErrCode,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- szBuf,
- sizeof(szBuf)-1,
- NULL);
- char *p = strrchr(szBuf, '\r');
- if (p != NULL)
- *p = ' ';
-
- p = strrchr(szBuf, '\n');
- if (p != NULL)
- *p = ' ';
- return dwRet > 0 ? szBuf : CSimpleStringA::Format("get error message fail: %d", GetLastError());
- }
- SPBASE_API const char *_GetFileName(const char *pszFilePath)
- {
- int i=strlen(pszFilePath);
- for( ; i>0 && pszFilePath[i-1]!=SPLIT_SLASH; i--)NULL;
- return pszFilePath+i;
- }
- #ifdef _WIN32
- extern "C" BOOL APIENTRY DllMain(HMODULE hModule,
- DWORD ul_reason_for_call,
- LPVOID lpReserved)
- {
- switch (ul_reason_for_call) {
- case DLL_PROCESS_ATTACH:
- {
- DisableThreadLibraryCalls(hModule);
- break;
- }
- case DLL_THREAD_ATTACH:
- break;
- case DLL_THREAD_DETACH:
- break;
- case DLL_PROCESS_DETACH:
- break;
- }
- return TRUE;
- }
- #endif //_WIN32
- ModuleBase::~ModuleBase()
- {
- #ifdef _WIN32
- getEntityResource()->m_moduleBase = NULL;
- #else
- ModuleBase::s_pModuleInst = NULL;
- #endif //_WIN32
- for (int i = 0; i < m_nEntityCount; ++i)
- {
- if (m_pEntityArray[i])
- {
- #ifdef _WIN32
- __try {
- delete m_pEntityArray[i];
- }
- __finally {
- m_pEntityArray[i] = NULL;
- }
- #else
- delete m_pEntityArray[i];
- m_pEntityArray[i] = NULL;
- #endif //_WIN32
- }
- }
- m_nEntityCount = 0;
- }
- static ErrorCodeEnum __Init()
- {
- #ifdef _WIN32
- ModuleBase* pThis = (ModuleBase*)(getEntityResource()->m_moduleBase);
- #else
- ModuleBase* pThis = ModuleBase::s_pModuleInst;
- #endif //_WIN32
- _ASSERT(pThis);
- return pThis->Init();
- }
- static ErrorCodeEnum __Exit()
- {
- #ifdef _WIN32
- ModuleBase* pThis = (ModuleBase*)(getEntityResource()->m_moduleBase);
- #else
- ModuleBase* pThis = ModuleBase::s_pModuleInst;
- #endif //_WIN32
- _ASSERT(pThis);
- return pThis->Exit();
- }
- ErrorCodeEnum ModuleBase::Init()
- {
- ErrorCodeEnum Error = Error_Succeed;
- for (int i = 0; i < m_nEntityCount; ++i)
- {
- Error = RegistEntity(m_pEntityArray[i]);
- if (Error)
- break;
- }
- return Error;
- }
- ErrorCodeEnum ModuleBase::Exit()
- {
- ErrorCodeEnum Error = Error_Succeed;
- for (int i = 0; i < m_nEntityCount; ++i)
- {
- Error = UnregistEntity(m_pEntityArray[i]);
- if (Error)
- break;
- }
- return Error;
- }
- BOOL ModuleBase::DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
- {
- if (dwReason == DLL_PROCESS_ATTACH) {
- bool ret = RegistMain(hInstance, &__Init, &__Exit);
- if (!ret)
- return FALSE;
- DisableThreadLibraryCalls(hInstance);
- m_hInstance = hInstance;
- }
- return TRUE;
- }
- ErrorCodeEnum ModuleBase::RegistEntity(CEntityBase *pEntity)
- {
- SpModule *pModule = GetSpModule();
- if (!pModule)
- return Error_Null;
- return pModule->AddEntityBase(pEntity);
- }
- ErrorCodeEnum ModuleBase::UnregistEntity(CEntityBase *pEntity)
- {
- SpModule *pModule = GetSpModule();
- return pModule->RemoveEntityBase(pEntity);
- }
- ErrorCodeEnum ModuleBase::GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity)
- {
- SpModule *pModule = GetSpModule();
- return pModule->GetEntityBase(pszEntityName, pEntity);
- }
- #ifndef _WIN32
- ModuleBase* ModuleBase::s_pModuleInst = NULL;
- #endif //NOT _WIN32
- ModuleBase* ModuleBase::GetModuleBase()
- {
- #ifdef _WIN32
- return (ModuleBase*)(getEntityResource()->m_moduleBase);
- #else
- return ModuleBase::s_pModuleInst;
- #endif //_WIN32
- }
- ModuleBase::ModuleBase()
- :m_hInstance(NULL), m_nEntityCount(0)
- {
- #ifdef _WIN32
- getEntityResource()->m_moduleBase = this;
- #else
- ModuleBase::s_pModuleInst = this;
- #endif //_WIN32
- }
- CClientSessionBase::~CClientSessionBase()
- {
- if (m_pSessionFunction) {
- SpClientSessionFunction *pFunction = dynamic_cast<SpClientSessionFunction *>(m_pSessionFunction);
- m_pSessionFunction = NULL;
- pFunction->DecrementRef();
- }
- }
|