SpBase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. #include "stdafx.h"
  2. #include "SpBase.h"
  3. #include "SpTimer.h"
  4. #include "SpEntity.h"
  5. #include "SpModule.h"
  6. #ifdef WIN32
  7. #include "SpBaseRoutine.h"
  8. #endif
  9. #include "SpMisc.h"
  10. #include "SpClientSessionFunction.h"
  11. #include "sockutil.h"
  12. #include "fileutil.h"
  13. #include "sp_shm.h"
  14. #include "sp_dbg_export.h"
  15. #include "sp_def.h"
  16. #include "sp_env.h"
  17. #include "DumpException.h"
  18. #ifdef _WIN32
  19. #include "sp_checkEntity.h"
  20. #include <DbgHelp.h>
  21. #else
  22. #include <exception>
  23. #endif // _WIN32
  24. #include<winpr//library.h>
  25. #include <winpr/locale.h>
  26. #include <winpr/exception.h>
  27. #ifndef _WIN32
  28. static SpModule* g_module = NULL;
  29. #endif //NOT _WIN32
  30. SpModule *GetSpModule()
  31. {
  32. #ifdef _WIN32
  33. SpModule *curModule = NULL;
  34. if (findThreadModule(GetCurrentThreadId(), (void **)&curModule))
  35. return curModule;
  36. else
  37. {
  38. CSimpleStringA mod_name = TraceStack();
  39. if (CSimpleStringA("") == mod_name) {
  40. return NULL;
  41. }
  42. SetthreadGroup(GetCurrentThreadId(), mod_name);
  43. if (findThreadModule(GetCurrentThreadId(), (void**)&curModule))
  44. return curModule;
  45. }
  46. return NULL;
  47. #else
  48. return g_module;
  49. #endif //_WIN32
  50. }
  51. #ifdef _WIN32
  52. static LONG WINAPI SuppressError(struct _EXCEPTION_POINTERS* ExceptionInfo)
  53. {
  54. char tmp[MAX_PATH] = { '\0' };
  55. char drivePath[_MAX_DRIVE] = {'\0'};
  56. sp_dir_get_cur_drive(drivePath);
  57. wsprintfA(tmp, "%s\\rvc\\dmp\\expt.%s.%d.%d.log", drivePath, GetSpModule() ? GetSpModule()->get_mod()->cfg->name : "", GetCurrentThreadId(), GetCurrentProcessId());
  58. HANDLE hLogFile = ::CreateFileA(tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  59. if (hLogFile != INVALID_HANDLE_VALUE) {
  60. DumpExceptionInfo(ExceptionInfo, hLogFile);
  61. FlushFileBuffers(hLogFile);
  62. SetEndOfFile(hLogFile);
  63. CloseHandle(hLogFile);
  64. }
  65. wsprintfA(tmp, "%s\\rvc\\dmp\\expt.%s.%d.%d.dmp", drivePath, GetSpModule() ? GetSpModule()->get_mod()->cfg->name : "", GetCurrentThreadId(), GetCurrentProcessId());
  66. HANDLE hDumpFile = CreateFileA( tmp, GENERIC_READ | GENERIC_WRITE,
  67. 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
  68. if( ( hDumpFile != NULL ) && ( hDumpFile != INVALID_HANDLE_VALUE ) )
  69. {
  70. MINIDUMP_EXCEPTION_INFORMATION mdei;
  71. mdei.ThreadId = GetCurrentThreadId();
  72. mdei.ExceptionPointers = ExceptionInfo;
  73. mdei.ClientPointers = FALSE;
  74. MINIDUMP_TYPE mdt = MiniDumpWithIndirectlyReferencedMemory;
  75. BOOL rv = MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
  76. hDumpFile, mdt, (ExceptionInfo != 0) ? &mdei : 0, 0, 0 );
  77. CloseHandle( hDumpFile );
  78. }
  79. Dbg("exit entity exception!");
  80. ExitProcess(Error_Exception); // exit process to suppress reporting exception
  81. return EXCEPTION_EXECUTE_HANDLER;
  82. }
  83. static void DisableSetUnhandledExceptionFilter()
  84. {
  85. void* addr = (void*)GetProcAddress(LoadLibrary("kernel32.dll"), "SetUnhandledExceptionFilter");
  86. if (addr) {
  87. DWORD dwOldFlag, dwTempFlag;
  88. unsigned char code[] = {0x33, 0xC0, 0xC2, 0x04, 0x00}; // xor eax,eax; ret 4;
  89. VirtualProtect(addr, sizeof(code), PAGE_READWRITE, &dwOldFlag);
  90. WriteProcessMemory(GetCurrentProcess(), addr, code, sizeof(code), NULL);
  91. VirtualProtect(addr, sizeof(code), dwOldFlag, &dwTempFlag);
  92. }
  93. }
  94. #endif //_WIN32
  95. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage)
  96. {//MAX string len < 1024
  97. SpModule *pModule = GetSpModule();
  98. if (pModule) {
  99. pModule->LogMessage(Log_Event, eLevel, 0, dwUserEventCode, pszMessage);
  100. }
  101. // write a copy in dbg log
  102. sp_dbg_info("Event: {%s}(uc=0x%X)", pszMessage, dwUserEventCode);
  103. }
  104. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage)
  105. {
  106. SpModule *pModule = GetSpModule();
  107. if (pModule) {
  108. pModule->LogMessage(Log_Error, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
  109. }
  110. else
  111. sp_dbg_info("LogError failed!can not find the module");
  112. // write a copy in dbg log
  113. sp_dbg_error("Error: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  114. }
  115. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage)
  116. {
  117. SpModule *pModule = GetSpModule();
  118. if (pModule) {
  119. pModule->LogMessage(Log_Warning, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
  120. }
  121. // write a copy in dbg log
  122. sp_dbg_warn("Warn: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  123. }
  124. SPBASE_API void LogAssert(const char *pszMessage,const char *pszFile,const int nLine)
  125. {
  126. SpModule *pModule = GetSpModule();
  127. if (pModule) {
  128. pModule->LogMessage(Log_Debug, Severity_Middle, 0, 0,
  129. CSimpleStringA::Format("assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
  130. pszMessage, _GetFileName(pszFile), nLine,
  131. #ifdef _WIN32
  132. (const char*)DumpStack(2)
  133. #else
  134. "not implement, TODO:"
  135. #endif //_WIN32
  136. ));
  137. }
  138. // write a copy in dbg log
  139. sp_dbg_debug("Assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
  140. pszMessage, _GetFileName(pszFile), nLine,
  141. #ifdef _WIN32
  142. (const char*)DumpStack(2)
  143. #else
  144. "not implement, TODO:"
  145. #endif //_WIN32
  146. );
  147. }
  148. SPBASE_API void LogTrace(const char *pszMessage,const char *pszFile,const int nLine)
  149. {
  150. sp_dbg_debug("========Trace: {%s}, file: {%s}, line: {%d}", pszMessage, _GetFileName(pszFile), nLine);
  151. SpModule *pModule = GetSpModule();
  152. if (pModule) {
  153. pModule->LogMessage(Log_Debug, Severity_None, 0, 0, pszMessage);
  154. }
  155. // write a copy in dbg log
  156. sp_dbg_debug("Trace: {%s}, file: {%s}, line: {%d}", pszMessage, _GetFileName(pszFile), nLine);
  157. }
  158. #include "log.h"
  159. #include <malloc.h>
  160. extern "C" SPBASE_API void Dbg(const char *str, ...)
  161. {
  162. va_list arg;
  163. va_start(arg, str);
  164. vDbg(str, arg);
  165. va_end(arg);
  166. }
  167. extern "C" SPBASE_API void vDbg(const char *str, va_list list)
  168. {
  169. int n = _vscprintf(str, list);
  170. if (n > 1024)
  171. n = 1024;
  172. char *buf = (char*)_alloca(n+1);
  173. memset(buf, 0, n+1);
  174. /*write at most n bytes(including the terminating null byte '\0') to buf*/
  175. 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]
  176. sp_dbg_debug("Debug: {%s}", buf); //打印到文件
  177. //修改,不发出Log_Debug类消息
  178. //SpModule* pModule = GetSpModule();
  179. // if (pModule)
  180. // {
  181. // __try
  182. // {
  183. // SpEntity *pEntity = (SpEntity*)(getEntityResource()->m_Entity);
  184. //
  185. // if (pEntity != NULL)
  186. // {
  187. // auto pEntCfg = pEntity->get_cfg_ent();
  188. // if (pEntCfg != NULL && pEntCfg->debug_level > 0)
  189. // {
  190. // pEntity->LogMessage(Log_Debug, Severity_None, -1, -1, buf);
  191. // }
  192. // }
  193. // }
  194. // __finally
  195. // {
  196. //
  197. // }
  198. // }
  199. }
  200. static bool RegistMain(HMODULE hModule,EntryRoutine Main, EntryRoutine Exit)
  201. {
  202. SpModule::SetEntryRoutine(Main, Exit);
  203. return true;
  204. }
  205. static HMODULE LoadModuleLibrary(sp_mod_t *mod)
  206. {
  207. sp_env_t *env = sp_get_env();
  208. char tmp[MAX_PATH];
  209. sp_dir_get_path(env->dir, SP_DIR_MODULE_BIN, mod->cfg->name, tmp, sizeof(tmp));
  210. return LoadLibraryA(tmp);
  211. }
  212. SPBASE_API HINSTANCE SpLoadLibrary(const char *file)
  213. {
  214. sp_env_t *env = sp_get_env();
  215. if (env) {
  216. char tmp[MAX_PATH];
  217. #ifdef _WIN32
  218. sprintf(tmp, "%s\\%s", env->dir->dep_path, file);
  219. #else
  220. sprintf(tmp, "%s/%s", env->dir->dep_path, file);
  221. #endif //_WIN32
  222. return LoadLibraryA(tmp);
  223. } else {
  224. return NULL;
  225. }
  226. }
  227. #ifdef _WIN32
  228. extern "C" SPBASE_API int __stdcall SpExit(const char* mod_name)
  229. {
  230. Dbg("Do SpExit!");
  231. SetthreadGroup(GetCurrentThreadId(), mod_name);
  232. CleanModuleThread(mod_name);
  233. sp_iom_stop(GetSpModule()->get_iom());
  234. GetSpModule()->Term();
  235. sp_shm_term();
  236. sp_dbg_term();
  237. sp_iom_destroy(GetSpModule()->get_iom());
  238. delete GetSpModule();
  239. //winsock_term();
  240. FreeLibrary(getEntityResource()->m_Module);
  241. DestoryModuleInfo(mod_name);
  242. return 0;
  243. }
  244. #endif //_WIN32
  245. extern "C" SPBASE_API int __stdcall SpRun(const char *mod_name, int epid, int range, int group)
  246. {
  247. ErrorCodeEnum Error = Error_Unexpect;
  248. if (!mod_name)
  249. return Error_Bug;
  250. if (epid == SP_INVALID_MOD_ID)
  251. return Error_Bug;
  252. #ifdef _WIN32
  253. if (findModuleByName(mod_name)) //检测实体是否已创建
  254. SpExit(mod_name);
  255. bool result = group == 0 ? CreateModuleInfo(ENTITY_SINGLE_GROUPNAME) : CreateModuleInfo(mod_name);
  256. //the SetthreadGroup routine would never return false, so the group variable must be not-zero
  257. if (!result || !SetthreadGroup(GetCurrentThreadId(), mod_name))
  258. return Error_Duplication;
  259. #else
  260. if (g_module) {
  261. return Error_Duplication;
  262. }
  263. #endif //_WIN32
  264. if (winsock_init() != 0) {
  265. return Error_NetBroken;
  266. }
  267. sp_dbg_init(mod_name);
  268. sp_dbg_info("==============SpRun(%s) start==============", mod_name);
  269. sp_dbg_info("process id: %d", GetCurrentProcessId());
  270. void *hint_addr = sp_shm_init(range, FALSE);
  271. if (!hint_addr) {
  272. sp_dbg_warn("shm init failed! hint_addr: 0x%08x", hint_addr);
  273. return Error_Unexpect;
  274. }
  275. sp_dbg_info("shm init ok! hint_addr: 0x%08x", hint_addr);
  276. sp_env_t *env = sp_get_env();
  277. if (!env) {
  278. sp_dbg_warn("module env object init failed!");
  279. return Error_Unexpect;
  280. }
  281. sp_dbg_info("retrieve env object ok!");
  282. sp_mod_t *mod = sp_mod_mgr_find_module_by_idx(env->mod_mgr, epid);
  283. if (!mod) {
  284. sp_dbg_warn("find shm module object failed!");
  285. return Error_NotExist;
  286. }
  287. sp_dbg_info("find module %s id %d ok!", mod->cfg->name, mod->cfg->idx);
  288. sp_dbg_info("module %s file version: %d.%d.%d.%d", mod->cfg->name,
  289. mod->cfg->version.major,
  290. mod->cfg->version.minor,
  291. mod->cfg->version.revision,
  292. mod->cfg->version.build);
  293. SpInitUUID((WORD)mod->cfg->idx);
  294. sp_cfg_shell_module_t *cfg_mod = sp_cfg_get_module_by_idx(env->cfg, epid);
  295. if (!cfg_mod) {
  296. sp_dbg_warn("get module %s cfg object failed!", mod->cfg->name);
  297. return Error_Bug;
  298. }
  299. sp_dbg_info("find cfg module object %s id %d ok!", cfg_mod->name, cfg_mod->idx);
  300. #ifdef _WIN32
  301. SetUnhandledExceptionFilter(&SuppressError);
  302. //DisableSetUnhandledExceptionFilter();
  303. #endif //_WIN32
  304. #ifdef _WIN32
  305. SpModule* curModule = new SpModule(mod, cfg_mod);
  306. getEntityResource()->m_Module = LoadModuleLibrary(mod);
  307. if (!getEntityResource()->m_Module) {
  308. sp_dbg_warn("load module library %s failed! GetLastError = %d", mod->cfg->name, GetLastError());
  309. goto on_error;
  310. }
  311. curModule->getEntryRoutine(&(getEntityResource()->m_pfMain), &(getEntityResource()->m_pfExit));
  312. Error = curModule->Init(env->url);
  313. if (Error) {
  314. delete curModule;
  315. curModule = NULL;
  316. goto on_error;
  317. }
  318. #else
  319. g_module = new SpModule(mod, cfg_mod);
  320. HMODULE hModule = LoadModuleLibrary(mod);
  321. if (!hModule) {
  322. sp_dbg_warn("load module library %s failed! GetLastError = %d", mod->cfg->name, GetLastError());
  323. goto on_error;
  324. }
  325. Error = g_module->Init(env->url);
  326. if (Error) {
  327. delete g_module;
  328. g_module = NULL;
  329. goto on_error;
  330. }
  331. #endif //_WIN32
  332. sp_dbg_debug("before set thread priority");
  333. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  334. sp_dbg_debug("after set thread priority");
  335. #ifdef _WIN32
  336. if (!SetSpModule(mod_name, curModule))
  337. goto on_error;
  338. Error = curModule->Run();
  339. curModule->Term();
  340. FreeLibrary(getEntityResource()->m_Module);
  341. delete curModule;
  342. curModule = NULL;
  343. #else
  344. Error = g_module->Run();
  345. g_module->Term();
  346. FreeLibrary(hModule);
  347. #endif //_WIN32
  348. sp_shm_term();
  349. on_error:
  350. return Error;
  351. }
  352. SPBASE_API CSimpleStringA GetSysErrMsg(int nErrCode)
  353. {
  354. char szBuf[2048] = {};
  355. DWORD dwRet = FormatMessageA(
  356. FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  357. NULL,
  358. nErrCode,
  359. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  360. szBuf,
  361. sizeof(szBuf)-1,
  362. NULL);
  363. char *p = strrchr(szBuf, '\r');
  364. if (p != NULL)
  365. *p = ' ';
  366. p = strrchr(szBuf, '\n');
  367. if (p != NULL)
  368. *p = ' ';
  369. return dwRet > 0 ? szBuf : CSimpleStringA::Format("get error message fail: %d", GetLastError());
  370. }
  371. SPBASE_API const char *_GetFileName(const char *pszFilePath)
  372. {
  373. int i=strlen(pszFilePath);
  374. for( ; i>0 && pszFilePath[i-1]!=SPLIT_SLASH; i--)NULL;
  375. return pszFilePath+i;
  376. }
  377. #ifdef _WIN32
  378. extern "C" BOOL APIENTRY DllMain(HMODULE hModule,
  379. DWORD ul_reason_for_call,
  380. LPVOID lpReserved)
  381. {
  382. switch (ul_reason_for_call) {
  383. case DLL_PROCESS_ATTACH:
  384. {
  385. DisableThreadLibraryCalls(hModule);
  386. break;
  387. }
  388. case DLL_THREAD_ATTACH:
  389. break;
  390. case DLL_THREAD_DETACH:
  391. break;
  392. case DLL_PROCESS_DETACH:
  393. break;
  394. }
  395. return TRUE;
  396. }
  397. #endif //_WIN32
  398. ModuleBase::~ModuleBase()
  399. {
  400. #ifdef _WIN32
  401. getEntityResource()->m_moduleBase = NULL;
  402. #else
  403. ModuleBase::s_pModuleInst = NULL;
  404. #endif //_WIN32
  405. for (int i = 0; i < m_nEntityCount; ++i)
  406. {
  407. if (m_pEntityArray[i])
  408. {
  409. #ifdef _WIN32
  410. __try {
  411. delete m_pEntityArray[i];
  412. }
  413. __finally {
  414. m_pEntityArray[i] = NULL;
  415. }
  416. #else
  417. delete m_pEntityArray[i];
  418. m_pEntityArray[i] = NULL;
  419. #endif //_WIN32
  420. }
  421. }
  422. m_nEntityCount = 0;
  423. }
  424. static ErrorCodeEnum __Init()
  425. {
  426. #ifdef _WIN32
  427. ModuleBase* pThis = (ModuleBase*)(getEntityResource()->m_moduleBase);
  428. #else
  429. ModuleBase* pThis = ModuleBase::s_pModuleInst;
  430. #endif //_WIN32
  431. _ASSERT(pThis);
  432. return pThis->Init();
  433. }
  434. static ErrorCodeEnum __Exit()
  435. {
  436. #ifdef _WIN32
  437. ModuleBase* pThis = (ModuleBase*)(getEntityResource()->m_moduleBase);
  438. #else
  439. ModuleBase* pThis = ModuleBase::s_pModuleInst;
  440. #endif //_WIN32
  441. _ASSERT(pThis);
  442. return pThis->Exit();
  443. }
  444. ErrorCodeEnum ModuleBase::Init()
  445. {
  446. ErrorCodeEnum Error = Error_Succeed;
  447. for (int i = 0; i < m_nEntityCount; ++i)
  448. {
  449. Error = RegistEntity(m_pEntityArray[i]);
  450. if (Error)
  451. break;
  452. }
  453. return Error;
  454. }
  455. ErrorCodeEnum ModuleBase::Exit()
  456. {
  457. ErrorCodeEnum Error = Error_Succeed;
  458. for (int i = 0; i < m_nEntityCount; ++i)
  459. {
  460. Error = UnregistEntity(m_pEntityArray[i]);
  461. if (Error)
  462. break;
  463. }
  464. return Error;
  465. }
  466. BOOL ModuleBase::DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
  467. {
  468. if (dwReason == DLL_PROCESS_ATTACH) {
  469. bool ret = RegistMain(hInstance, &__Init, &__Exit);
  470. if (!ret)
  471. return FALSE;
  472. DisableThreadLibraryCalls(hInstance);
  473. m_hInstance = hInstance;
  474. }
  475. return TRUE;
  476. }
  477. ErrorCodeEnum ModuleBase::RegistEntity(CEntityBase *pEntity)
  478. {
  479. SpModule *pModule = GetSpModule();
  480. if (!pModule)
  481. return Error_Null;
  482. return pModule->AddEntityBase(pEntity);
  483. }
  484. ErrorCodeEnum ModuleBase::UnregistEntity(CEntityBase *pEntity)
  485. {
  486. SpModule *pModule = GetSpModule();
  487. return pModule->RemoveEntityBase(pEntity);
  488. }
  489. ErrorCodeEnum ModuleBase::GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity)
  490. {
  491. SpModule *pModule = GetSpModule();
  492. return pModule->GetEntityBase(pszEntityName, pEntity);
  493. }
  494. #ifndef _WIN32
  495. ModuleBase* ModuleBase::s_pModuleInst = NULL;
  496. #endif //NOT _WIN32
  497. ModuleBase* ModuleBase::GetModuleBase()
  498. {
  499. #ifdef _WIN32
  500. return (ModuleBase*)(getEntityResource()->m_moduleBase);
  501. #else
  502. return ModuleBase::s_pModuleInst;
  503. #endif //_WIN32
  504. }
  505. ModuleBase::ModuleBase()
  506. :m_hInstance(NULL), m_nEntityCount(0)
  507. {
  508. #ifdef _WIN32
  509. getEntityResource()->m_moduleBase = this;
  510. #else
  511. ModuleBase::s_pModuleInst = this;
  512. #endif //_WIN32
  513. }
  514. CClientSessionBase::~CClientSessionBase()
  515. {
  516. if (m_pSessionFunction) {
  517. SpClientSessionFunction *pFunction = dynamic_cast<SpClientSessionFunction *>(m_pSessionFunction);
  518. m_pSessionFunction = NULL;
  519. pFunction->DecrementRef();
  520. }
  521. }