SpBase.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. #include "stdafx.h"
  2. #include "version.h"
  3. #include "SpBase.h"
  4. #include <base64File.hpp>
  5. #include "SpTimer.h"
  6. #include "SpEntity.h"
  7. #include "SpModule.h"
  8. #include "RVCEventCode.h"
  9. #ifdef WIN32
  10. #include "SpBaseRoutine.h"
  11. #endif
  12. #include "SpMisc.h"
  13. #include "SpClientSessionFunction.h"
  14. #include "sockutil.h"
  15. #include "fileutil.h"
  16. #include "memutil.h"
  17. #include "dbgutil.h"
  18. #include "sp_shm.h"
  19. #include "sp_dbg_export.h"
  20. #include "sp_def.h"
  21. #include "sp_env.h"
  22. #include "DumpException.h"
  23. #ifdef RVC_OS_WIN
  24. #include "sp_checkEntity.h"
  25. #include <DbgHelp.h>
  26. #else
  27. #include <exception>
  28. #endif // RVC_OS_WIN
  29. #include "SpSecureClient.h"
  30. #include "IHttpFunc.h"
  31. #include <RestfulFunc.h>
  32. #include <winpr/library.h>
  33. #include <winpr/locale.h>
  34. #include <winpr/exception.h>
  35. #include "uuid4.h"
  36. #include <chrono>
  37. #ifndef RVC_OS_WIN
  38. static SpModule* g_module = NULL;
  39. #endif //NOT RVC_OS_WIN
  40. SpModule *GetSpModule()
  41. {
  42. #ifdef RVC_OS_WIN
  43. SpModule *curModule = NULL;
  44. if (findThreadModule(GetCurrentThreadId(), (void **)&curModule))
  45. return curModule;
  46. else
  47. {
  48. CSimpleStringA mod_name = TraceStack();
  49. if (CSimpleStringA("") == mod_name) {
  50. return NULL;
  51. }
  52. SetthreadGroup(GetCurrentThreadId(), mod_name);
  53. if (findThreadModule(GetCurrentThreadId(), (void**)&curModule))
  54. return curModule;
  55. }
  56. return NULL;
  57. #else
  58. return g_module;
  59. #endif //RVC_OS_WIN
  60. }
  61. #ifdef RVC_OS_WIN
  62. static LONG WINAPI SuppressError(struct _EXCEPTION_POINTERS* ExceptionInfo)
  63. {
  64. //get active ver
  65. sp_version_t active_version = { 0 };
  66. sscanf(strrchr(sp_get_env()->dir->base_path, '\\') + 1, "%d.%d.%d.%d",
  67. &active_version.major, &active_version.minor, &active_version.revision, &active_version.build);
  68. std::string dmpFileStr;
  69. char tmp[MAX_PATH], tmpPath[MAX_PATH];
  70. GetModuleFileNameA(NULL, tmpPath, MAX_PATH);
  71. *strrchr(tmpPath, SPLIT_SLASH) = 0;
  72. *strrchr(tmpPath, SPLIT_SLASH) = 0;
  73. *strrchr(tmpPath, SPLIT_SLASH) = 0;
  74. *strrchr(tmpPath, SPLIT_SLASH) = 0;
  75. *strrchr(tmpPath, SPLIT_SLASH) = 0;
  76. wsprintfA(tmp, "%s\\rvc\\dmp\\expt.%d_%d_%d_%d.%s.%d.%d.log", tmpPath, active_version.major, active_version.minor
  77. , active_version.revision, active_version.build, GetSpModule() ? GetSpModule()->get_mod()->cfg->name : "", GetCurrentThreadId(), GetCurrentProcessId());
  78. HANDLE hLogFile = ::CreateFileA(tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  79. if (hLogFile != INVALID_HANDLE_VALUE) {
  80. DumpExceptionInfo(ExceptionInfo, hLogFile);
  81. FlushFileBuffers(hLogFile);
  82. SetEndOfFile(hLogFile);
  83. CloseHandle(hLogFile);
  84. }
  85. wsprintfA(tmp, "%s\\rvc\\dmp\\expt.%d_%d_%d_%d.%s.%d.%d.dmp", tmpPath, active_version.major, active_version.minor
  86. , active_version.revision, active_version.build, GetSpModule() ? GetSpModule()->get_mod()->cfg->name : "", GetCurrentThreadId(), GetCurrentProcessId());
  87. HANDLE hDumpFile = CreateFileA( tmp, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
  88. if( ( hDumpFile != NULL ) && ( hDumpFile != INVALID_HANDLE_VALUE ) )
  89. {
  90. MINIDUMP_EXCEPTION_INFORMATION mdei;
  91. mdei.ThreadId = GetCurrentThreadId();
  92. mdei.ExceptionPointers = ExceptionInfo;
  93. mdei.ClientPointers = FALSE;
  94. MINIDUMP_TYPE mdt = MiniDumpWithIndirectlyReferencedMemory;
  95. MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(),
  96. hDumpFile, mdt, (ExceptionInfo != 0) ? &mdei : 0, 0, 0 );
  97. CloseHandle( hDumpFile );
  98. }
  99. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setLogCode(ERR_ENTITY_EXCEPTION).setVtmCode(RTAERR_ENTITY_EXCEPTION)("exit entity exception, saveDmp, %s, detail:%d:%s"
  100. , tmp, dmpFileStr.length(), dmpFileStr.c_str());
  101. Sleep(1500);//wait until all log send
  102. ExitProcess(Error_Exception); // exit process to suppress reporting exception
  103. return EXCEPTION_EXECUTE_HANDLER;
  104. }
  105. #else
  106. #include <execinfo.h>
  107. static void HandleSignalCallback(int signalNo)
  108. {
  109. switch (signalNo) {
  110. case SIGSEGV:
  111. {
  112. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("=========>>> capture signal SIGSEGV <<<=========");
  113. void* l_buffer[512];
  114. char** l_ptrace;
  115. //char l_s8aBuff[128] = { 0x00 };
  116. //snprintf(l_s8aBuff, sizeof(l_s8aBuff), "cat /proc/%d/maps", getpid());
  117. //system(l_s8aBuff);
  118. //objdump -d libbacktrace.so > log.txt
  119. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Dump stack start...");
  120. int size = backtrace(l_buffer, 512);
  121. l_ptrace = backtrace_symbols(l_buffer, size);
  122. if (NULL == l_ptrace) {
  123. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("backtrace_symbols");
  124. exit(1);
  125. }
  126. for (int i = 0; i < size; i++) {
  127. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)(" [%02d] %s", i, l_ptrace[i]);
  128. }
  129. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Dump stack end...");
  130. free(l_ptrace);
  131. exit(-1);
  132. break;
  133. }
  134. case SIGKILL:
  135. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("=========>>> capture signal SIGKILL <<<=========");
  136. break;
  137. case SIGTERM:
  138. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("=========>>> capture signal SIGTERM <<<=========");
  139. break;
  140. default:
  141. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("=========>>> capture signal %d <<<=========", signalNo);
  142. break;
  143. }
  144. return;
  145. }
  146. static LONG WINAPI SuppressError(struct _EXCEPTION_POINTERS* ExceptionInfo)
  147. {
  148. LONG result(0);
  149. #if 1
  150. struct sigaction siga;
  151. siga.sa_handler = HandleSignalCallback;
  152. siga.sa_flags = 0;
  153. sigemptyset(&siga.sa_mask);
  154. if (0 > sigaction(SIGSEGV, &siga, NULL)) {
  155. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("register signal 'SIGSEGV' failed! %s %d", strerror(errno), errno);
  156. result = -1;
  157. }
  158. //if (0 > sigaction(SIGTERM, &siga, NULL)) {
  159. // sp_dbg_error("register signal 'SIGTERM' failed! %s %d", strerror(errno), errno); result = -1;
  160. //}
  161. //if (0 > sigaction(SIGKILL, &siga, NULL)) {
  162. // sp_dbg_error("register signal 'SIGKILL' failed! %d", errno); result = -1;
  163. //}
  164. #endif
  165. return result;
  166. }
  167. #endif //RVC_OS_WIN
  168. SPBASE_API void GetLibVersion(CVersion& version)
  169. {
  170. CVersion ver(VER_Major, VER_Minor, VER_Revision, VER_Build);
  171. version = ver;
  172. }
  173. SPBASE_API LPCSTR GetLibBuildDate()
  174. {
  175. #if defined(WITH_DEBUG)
  176. static char buildDate[] = __DATE__ " " __TIME__ " Debug";
  177. #elif defined(WITH_NO_DEBUG)
  178. static char buildDate[] = __DATE__ " " __TIME__ " Release";
  179. #else
  180. static char buildDate[] = __DATE__ " " __TIME__;
  181. #endif // WITH_DEBUG
  182. return buildDate;
  183. }
  184. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage)
  185. {//MAX string len < 1024
  186. SpModule *pModule = GetSpModule();
  187. if (pModule) {
  188. pModule->LogMessage(Log_Event, eLevel, 0, dwUserEventCode, pszMessage);
  189. }
  190. // write a copy in dbg log
  191. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(dwUserEventCode).GetData())
  192. ("Event: {%s}(uc=0x%X)", pszMessage, dwUserEventCode);
  193. }
  194. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage)
  195. {
  196. SpModule *pModule = GetSpModule();
  197. if (pModule) {
  198. pModule->LogMessage(Log_Error, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
  199. }
  200. else {
  201. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("LogError failed!can not find the module");
  202. }
  203. // write a copy in dbg log
  204. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(dwUserErrorCode).GetData())
  205. ("Error: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  206. }
  207. SPBASE_API void LogFatal(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage)
  208. {
  209. SpModule* pModule = GetSpModule();
  210. if (pModule) {
  211. pModule->LogMessage(Log_Fatal, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
  212. } else
  213. sp_dbg_info("LogFatal failed!can not find the module");
  214. DbgWithLink(LOG_LEVEL_FATAL, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(dwUserErrorCode).GetData())
  215. ("Fatal: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  216. }
  217. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage)
  218. {
  219. SpModule *pModule = GetSpModule();
  220. if (pModule) {
  221. pModule->LogMessage(Log_Warning, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage);
  222. }
  223. // write a copy in dbg log
  224. DbgWithLink(eLevel == Severity_Low ? LOG_LEVEL_INFO : LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(dwUserErrorCode).GetData())
  225. ("Warn: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  226. }
  227. SPBASE_API void LogAssert(const char *pszMessage,const char *pszFile,const int nLine)
  228. {
  229. SpModule *pModule = GetSpModule();
  230. if (pModule) {
  231. pModule->LogMessage(Log_Debug, Severity_Middle, 0, 0,
  232. CSimpleStringA::Format("assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
  233. pszMessage, _GetFileName(pszFile), nLine,
  234. #ifdef RVC_OS_WIN
  235. (const char*)DumpStack(2)
  236. #else
  237. "not implement, TODO:"
  238. #endif //RVC_OS_WIN
  239. ));
  240. }
  241. // write a copy in dbg log
  242. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(ERR_ENTITY_ASSERT).GetData())("Assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
  243. pszMessage, _GetFileName(pszFile), nLine,
  244. #ifdef RVC_OS_WIN
  245. (const char*)DumpStack(2)
  246. #else
  247. "not implement, TODO:"
  248. #endif //RVC_OS_WIN
  249. );
  250. }
  251. SPBASE_API void LogTrace(const char *pszMessage,const char *pszFile,const int nLine)
  252. {
  253. SpModule *pModule = GetSpModule();
  254. if (pModule) {
  255. pModule->LogMessage(Log_Debug, Severity_None, 0, 0, pszMessage);
  256. }
  257. // write a copy in dbg log
  258. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Trace: {%s}, file: {%s}, line: {%d}", pszMessage, _GetFileName(pszFile), nLine);
  259. }
  260. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel, DWORD dwUserEventCode, const char* pszMessage, const linkContext& t_context)
  261. {
  262. SpModule* pModule = GetSpModule();
  263. if (pModule) {
  264. pModule->LogMessage(Log_Event, eLevel, 0, dwUserEventCode, pszMessage, t_context);
  265. }
  266. // write a copy in dbg log
  267. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(dwUserEventCode).GetData())
  268. ("Event: {%s}(uc=0x%X)", pszMessage, dwUserEventCode);
  269. }
  270. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context)
  271. {
  272. SpModule* pModule = GetSpModule();
  273. if (pModule) {
  274. pModule->LogMessage(Log_Error, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage, t_context);
  275. }
  276. else {
  277. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("LogError failed!can not find the module");
  278. }
  279. // write a copy in dbg log
  280. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(dwSysErrorCode).GetData())
  281. ("Error: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  282. }
  283. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context)
  284. {
  285. SpModule* pModule = GetSpModule();
  286. if (pModule) {
  287. pModule->LogMessage(Log_Warning, eLevel, dwSysErrorCode, dwUserErrorCode, pszMessage, t_context);
  288. }
  289. // write a copy in dbg log
  290. DbgWithLink(eLevel == Severity_Low ? LOG_LEVEL_INFO : LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setVtmCode(DWORD2Hex(dwUserErrorCode).GetData())
  291. ("Warn: {%s}(sc=0x%X, uc=0x%X)", pszMessage, dwSysErrorCode, dwUserErrorCode);
  292. }
  293. SPBASE_API void LogAssert(const char* pszMessage, const char* pszFile, const int nLine, const linkContext& t_context)
  294. {
  295. SpModule* pModule = GetSpModule();
  296. if (pModule) {
  297. pModule->LogMessage(Log_Debug, Severity_Middle, 0, 0,
  298. CSimpleStringA::Format("assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
  299. pszMessage, _GetFileName(pszFile), nLine,
  300. #ifdef RVC_OS_WIN
  301. (const char*)DumpStack(2)
  302. #else
  303. "not implement, TODO:"
  304. #endif //_WIN32
  305. ), t_context);
  306. }
  307. // write a copy in dbg log
  308. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setVtmCode(DWORD2Hex(ERR_ENTITY_ASSERT).GetData())("Assert fail: {%s}, file: {%s}, line: {%d}, stack: {%s}",
  309. pszMessage, _GetFileName(pszFile), nLine,
  310. #ifdef RVC_OS_WIN
  311. (const char*)DumpStack(2)
  312. #else
  313. "not implement, TODO:"
  314. #endif //_WIN32
  315. );
  316. }
  317. SPBASE_API void LogTrace(const char* pszMessage, const char* pszFile, const int nLine, const linkContext& t_context)
  318. {
  319. SpModule* pModule = GetSpModule();
  320. if (pModule) {
  321. pModule->LogMessage(Log_Debug, Severity_None, 0, 0, pszMessage, t_context);
  322. }
  323. // write a copy in dbg log
  324. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Trace: {%s}, file: {%s}, line: {%d}", pszMessage, _GetFileName(pszFile), nLine);
  325. }
  326. #include "log.h"
  327. SPBASE_API void SpGetToken(char* channelId, char* token, char* terminalno, char* reserve1)
  328. {
  329. sp_env_t* env = sp_get_env();
  330. if (NULL != env && NULL != env->cfg && NULL != env->cfg->shell_ini &&
  331. env->cfg->shell_ini->channelId != NULL && env->cfg->shell_ini->token != NULL
  332. && env->cfg->root_ini != NULL && env->cfg->root_ini->terminal_no != NULL)
  333. {
  334. snprintf(channelId, MAX_TOKEN_LEN, "%s", env->cfg->shell_ini->channelId);
  335. snprintf(token, MAX_TOKEN_LEN, "%s", env->cfg->shell_ini->token);
  336. snprintf(terminalno, MAX_TOKEN_LEN, "%s", env->cfg->root_ini->terminal_no);
  337. }
  338. else if (NULL == env)
  339. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SpGetToken can not get token!env == NULL");
  340. else if (NULL == env->cfg)
  341. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SpGetToken can not get token!env->cfg == NULL");
  342. else if (NULL == env->cfg->shell_ini)
  343. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SpGetToken can not get token!env->cfg->shell_ini == NULL");
  344. else if (NULL == env->cfg->shell_ini->channelId)
  345. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SpGetToken can not get token!env->cfg->shell_ini->channelId == NULL");
  346. else if (NULL == env->cfg->shell_ini->token)
  347. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SpGetToken can not get token!env->cfg->shell_ini->token == NULL");
  348. }
  349. extern "C" SPBASE_API void Dbg(const char *str, ...)
  350. {
  351. if (str == nullptr)
  352. return;
  353. va_list arg;
  354. va_start(arg, str);
  355. vDbg(str, arg);
  356. va_end(arg);
  357. }
  358. extern "C" SPBASE_API void vDbg(const char *str, va_list list)
  359. {
  360. int n = _vscprintf(str, list);
  361. if (n > 1024)
  362. n = 1024;
  363. char *buf = (char*)_alloca(n + 1);
  364. memset(buf, '\0', n + 1);
  365. /*write at most n bytes(including the terminating null byte '\0') to buf*/
  366. 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]
  367. buf[n] = '\0';
  368. #if defined(_MSC_VER)
  369. sp_dbg_debugNoOut("Debug: {%s}", buf); //打印到文件
  370. #else
  371. sp_dbg_debug("Debug: {%s}", buf);
  372. #endif //_MSC_VER
  373. #ifdef RVC_OS_WIN
  374. SpModule* pModule = GetSpModule();
  375. if (pModule) {
  376. SpEntity* pEntity = (SpEntity*)(getEntityResource()->m_Entity);
  377. if (pEntity != NULL) {
  378. auto pEntCfg = pEntity->get_cfg_ent();
  379. if (pEntCfg != NULL)
  380. pEntity->LogMessage(Log_Debug, Severity_None, 0, 0, buf);
  381. }
  382. }
  383. #endif // RVC_OS_WIN
  384. }
  385. static bool RegistMain(HMODULE hModule,EntryRoutine Main, EntryRoutine Exit)
  386. {
  387. SpModule::SetEntryRoutine(Main, Exit);
  388. return true;
  389. }
  390. static HMODULE LoadModuleLibrary(sp_mod_t *mod)
  391. {
  392. sp_env_t *env = sp_get_env();
  393. char tmp[MAX_PATH];
  394. sp_dir_get_path(env->dir, SP_DIR_MODULE_BIN, mod->cfg->name, tmp, sizeof(tmp));
  395. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("load module library: %s", tmp);
  396. return LoadLibraryA(tmp);
  397. }
  398. /*only sphost would invoke it.*/
  399. extern "C" SPBASE_API int __stdcall SpExit(const char* mod_name)
  400. {
  401. #ifdef RVC_OS_WIN
  402. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Do SpExit!");
  403. SetthreadGroup(GetCurrentThreadId(), mod_name);
  404. CleanModuleThread(mod_name);
  405. sp_iom_stop(GetSpModule()->get_iom());
  406. GetSpModule()->Term();
  407. sp_shm_term();
  408. sp_dbg_term();
  409. sp_iom_destroy(GetSpModule()->get_iom());
  410. delete GetSpModule();
  411. //winsock_term();
  412. FreeLibrary(getEntityResource()->m_Module);
  413. DestoryModuleInfo(mod_name);
  414. #else
  415. if (sp_shm_is_newalloc())
  416. return 0; /*spshell*/
  417. if (g_module) {
  418. delete g_module;
  419. g_module = nullptr;
  420. }
  421. #endif //RVC_OS_WIN
  422. return 0;
  423. }
  424. extern "C" SPBASE_API int __stdcall SpRun(const char *mod_name, int epid, int range, int group, int saveFile)
  425. {
  426. ErrorCodeEnum Error = Error_Unexpect;
  427. if (!mod_name) { return Error_Param; }
  428. if (epid == SP_INVALID_MOD_ID) { return Error_Param; }
  429. #ifdef RVC_OS_WIN
  430. if (findModuleByName(mod_name)) //检测实体是否已创建
  431. SpExit(mod_name);
  432. bool result = group == 0 ? CreateModuleInfo(ENTITY_SINGLE_GROUPNAME) : CreateModuleInfo(mod_name);
  433. //the SetthreadGroup routine would never return false, so the group variable must be not-zero
  434. if (!result || !SetthreadGroup(GetCurrentThreadId(), mod_name))
  435. return Error_Duplication;
  436. #else
  437. if (g_module) {
  438. return Error_Duplication;
  439. }
  440. #endif //RVC_OS_WIN
  441. void* hint_addr = NULL;
  442. HMODULE hModule = NULL;
  443. sp_env_t* env = NULL;
  444. sp_mod_t* mod = NULL;
  445. sp_cfg_shell_module_t* cfg_mod = NULL;
  446. SpModule* curModule = NULL;
  447. if (winsock_init() != 0) {
  448. sp_dbg_error("winsock init failed!");
  449. Error = Error_NetBroken;
  450. goto on_error;
  451. }
  452. SetTokenCallBack(getHttpToken);
  453. SetRestfulTokenCallBack(getHttpToken);
  454. //need init shm first, because log_record save in shm
  455. hint_addr = sp_shm_init(range, FALSE);
  456. create_log_producer_default(mod_name, epid);
  457. if (saveFile)
  458. sp_dbg_init(mod_name, 1);
  459. else
  460. sp_dbg_init(mod_name, 0);
  461. EntityResource::setSaveFile(saveFile);
  462. sp_dbg_set_level(XLOG_LEVEL_DEBUG);
  463. if (!hint_addr) {
  464. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shm init failed!");
  465. Error = Error_Null;
  466. goto on_error;
  467. }
  468. sp_trace_init();
  469. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("==============SpRun(%s) start==============", mod_name);
  470. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("process id: %d, curLogLevel:%d", GetCurrentProcessId(), getCurLogLevel());
  471. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shm init ok! hint_addr: %p", hint_addr);
  472. env = sp_get_env();
  473. if (!env) {
  474. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("module env object init failed(env is null)!");
  475. Error = Error_Unexpect;
  476. goto on_error;
  477. }
  478. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("retrieve env object ok!");
  479. mod = sp_mod_mgr_find_module_by_idx(env->mod_mgr, epid);
  480. if (!mod) {
  481. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find shm module object failed!");
  482. Error = Error_NotExist;
  483. goto on_error;
  484. }
  485. //sp_dbg_info("find module %s id %d ok!", mod->cfg->name, mod->cfg->idx);
  486. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("module %s id %d static file version: %d.%d.%d.%d", mod->cfg->name, mod->cfg->idx,
  487. mod->cfg->version.major,
  488. mod->cfg->version.minor,
  489. mod->cfg->version.revision,
  490. mod->cfg->version.build);
  491. SpInitUUID((WORD)mod->cfg->idx);
  492. cfg_mod = sp_cfg_get_module_by_idx(env->cfg, epid);
  493. if (!cfg_mod) {
  494. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get module %s cfg object failed!", mod->cfg->name);
  495. Error = Error_NotExist;
  496. goto on_error;
  497. }
  498. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find cfg module object %s id %d ok!", cfg_mod->name, cfg_mod->idx);
  499. #ifdef RVC_OS_WIN
  500. SetUnhandledExceptionFilter(&SuppressError);
  501. #else
  502. SuppressError(NULL);
  503. #endif //RVC_OS_WIN
  504. #ifdef RVC_OS_WIN
  505. curModule = new SpModule(mod, cfg_mod);
  506. getEntityResource()->m_Module = LoadModuleLibrary(mod);
  507. if (!getEntityResource()->m_Module) {
  508. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("load module library %s failed! GetLastError = %d", mod->cfg->name, GetLastError());
  509. Error = Error_Unregisted;
  510. goto on_error;
  511. }
  512. curModule->getEntryRoutine(&(getEntityResource()->m_pfMain), &(getEntityResource()->m_pfExit));
  513. Error = curModule->Init(env->url);
  514. if (Error) {
  515. delete curModule;
  516. curModule = NULL;
  517. goto on_error;
  518. }
  519. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init moudle succ.");
  520. #else
  521. g_module = new SpModule(mod, cfg_mod);
  522. hModule = LoadModuleLibrary(mod);
  523. if (!hModule) {
  524. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("load module library %s failed! %s", mod->cfg->name, DLoadErrorString());
  525. Error = Error_Unregisted;
  526. goto on_error;
  527. }
  528. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to init module...");
  529. Error = g_module->Init(env->url);
  530. if (Error) {
  531. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("init moudle returned %s", SpStrError(Error));
  532. goto on_error;
  533. }
  534. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init moudle succ.");
  535. #endif //RVC_OS_WIN
  536. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  537. #ifdef RVC_OS_WIN
  538. if (!SetSpModule(mod_name, curModule)) {
  539. Error = Error_Unexpect;
  540. goto on_error;
  541. }
  542. sp_trace_term();
  543. Error = curModule->Run();
  544. curModule->Term();
  545. FreeLibrary(getEntityResource()->m_Module);
  546. delete curModule;
  547. curModule = NULL;
  548. #else
  549. sp_trace_term();
  550. Error = g_module->Run();
  551. g_module->Term();
  552. #endif //RVC_OS_WIN
  553. on_error:
  554. #ifndef RVC_OS_WIN
  555. if (hModule) {
  556. FreeLibrary(hModule);
  557. hModule = NULL;
  558. }
  559. if (g_module) {
  560. delete g_module;
  561. g_module = nullptr;
  562. }
  563. #endif //NOT RVC_OS_WIN
  564. if (!!sp_trace_exist()) {
  565. char* last_err = NULL;
  566. sp_trace_retrieve(&last_err, NULL);
  567. if (last_err) {
  568. sp_mod_supress_last_err_for_all_entity(mod, last_err);
  569. FREE(last_err);
  570. }
  571. }
  572. sp_shm_term();
  573. //destroy_log_producer_default();
  574. return Error;
  575. }
  576. extern "C" SPBASE_API const char* SpStrError(ErrorCodeEnum errorCode)
  577. {
  578. return sp_strerror((int)errorCode);
  579. }
  580. SPBASE_API CSimpleStringA GetSysErrMsg(DWORD nErrCode)
  581. {
  582. #if defined(RVC_OS_WIN)
  583. char szBuf[2048] = {};
  584. DWORD dwRet = FormatMessageA(
  585. FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  586. NULL,
  587. nErrCode,
  588. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  589. szBuf,
  590. sizeof(szBuf) - 1,
  591. NULL);
  592. char* p = strrchr(szBuf, '\r');
  593. if (p != NULL)
  594. *p = ' ';
  595. p = strrchr(szBuf, '\n');
  596. if (p != NULL)
  597. *p = ' ';
  598. return dwRet > 0 ? szBuf : CSimpleStringA::Format("get error message fail: %d", GetLastError());
  599. #else
  600. std::string szBuf(strerror(nErrCode));
  601. return szBuf.c_str();
  602. #endif //RVC_OS_WIN
  603. }
  604. extern "C" SPBASE_API const char *_GetFileName(const char *pszFilePath)
  605. {
  606. int i=strlen(pszFilePath);
  607. for( ; i>0 && pszFilePath[i-1]!=SPLIT_SLASH; i--)NULL;
  608. return pszFilePath+i;
  609. }
  610. #ifdef RVC_OS_WIN
  611. extern "C" BOOL APIENTRY DllMain(HMODULE hModule,
  612. DWORD ul_reason_for_call,
  613. LPVOID lpReserved)
  614. {
  615. switch (ul_reason_for_call) {
  616. case DLL_PROCESS_ATTACH:
  617. {
  618. DisableThreadLibraryCalls(hModule);
  619. break;
  620. }
  621. case DLL_THREAD_ATTACH:
  622. break;
  623. case DLL_THREAD_DETACH:
  624. break;
  625. case DLL_PROCESS_DETACH:
  626. break;
  627. }
  628. return TRUE;
  629. }
  630. #endif //RVC_OS_WIN
  631. ModuleBase::~ModuleBase()
  632. {
  633. #ifdef RVC_OS_WIN
  634. getEntityResource()->m_moduleBase = NULL;
  635. #else
  636. ModuleBase::s_pModuleInst = NULL;
  637. #endif //RVC_OS_WIN
  638. for (int i = 0; i < m_nEntityCount; ++i)
  639. {
  640. if (m_pEntityArray[i])
  641. {
  642. #ifdef RVC_OS_WIN
  643. //属于实体关闭掉,会自动清理,实际上不做对应的delete也行
  644. //基于该部分出了的问题,应该用share_ptr来处理
  645. //不过因为需要导出到spbase.h中,处理比较麻烦
  646. //__try {
  647. // delete m_pEntityArray[i];
  648. //}
  649. //__finally {
  650. // m_pEntityArray[i] = NULL;
  651. //}
  652. #else
  653. delete m_pEntityArray[i];
  654. m_pEntityArray[i] = NULL;
  655. #endif //RVC_OS_WIN
  656. }
  657. }
  658. m_nEntityCount = 0;
  659. }
  660. static ErrorCodeEnum __Init()
  661. {
  662. #ifdef RVC_OS_WIN
  663. ModuleBase* pThis = (ModuleBase*)(getEntityResource()->m_moduleBase);
  664. #else
  665. ModuleBase* pThis = ModuleBase::s_pModuleInst;
  666. #endif //RVC_OS_WIN
  667. _ASSERT(pThis);
  668. return pThis->Init();
  669. }
  670. static ErrorCodeEnum __Exit()
  671. {
  672. #ifdef RVC_OS_WIN
  673. ModuleBase* pThis = (ModuleBase*)(getEntityResource()->m_moduleBase);
  674. #else
  675. ModuleBase* pThis = ModuleBase::s_pModuleInst;
  676. #endif //RVC_OS_WIN
  677. _ASSERT(pThis);
  678. return pThis->Exit();
  679. }
  680. ErrorCodeEnum ModuleBase::Init()
  681. {
  682. ErrorCodeEnum Error = Error_Succeed;
  683. for (int i = 0; i < m_nEntityCount; ++i)
  684. {
  685. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to regist entity %s", m_pEntityArray[i]->GetEntityName());
  686. Error = RegistEntity(m_pEntityArray[i]);
  687. if (Error) {
  688. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("regist entity %s returned %s", m_pEntityArray[i]->GetEntityName(), SpStrError(Error));
  689. break;
  690. }
  691. }
  692. return Error;
  693. }
  694. ErrorCodeEnum ModuleBase::Exit()
  695. {
  696. ErrorCodeEnum Error = Error_Succeed;
  697. for (int i = 0; i < m_nEntityCount; ++i)
  698. {
  699. Error = UnregistEntity(m_pEntityArray[i]);
  700. if (Error)
  701. break;
  702. }
  703. return Error;
  704. }
  705. BOOL ModuleBase::DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
  706. {
  707. if (dwReason == DLL_PROCESS_ATTACH) {
  708. bool ret = RegistMain(hInstance, &__Init, &__Exit);
  709. if (!ret)
  710. return FALSE;
  711. DisableThreadLibraryCalls(hInstance);
  712. m_hInstance = hInstance;
  713. }
  714. return TRUE;
  715. }
  716. ErrorCodeEnum ModuleBase::RegistEntity(CEntityBase *pEntity)
  717. {
  718. SpModule *pModule = GetSpModule();
  719. SpSecureClient::SetSecureEntity(pEntity);
  720. if (!pModule)
  721. return Error_Null;
  722. return pModule->AddEntityBase(pEntity);
  723. }
  724. ErrorCodeEnum ModuleBase::UnregistEntity(CEntityBase *pEntity)
  725. {
  726. SpModule *pModule = GetSpModule();
  727. return pModule->RemoveEntityBase(pEntity);
  728. }
  729. ErrorCodeEnum ModuleBase::GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity)
  730. {
  731. SpModule *pModule = GetSpModule();
  732. return pModule->GetEntityBase(pszEntityName, pEntity);
  733. }
  734. #ifndef RVC_OS_WIN
  735. ModuleBase* ModuleBase::s_pModuleInst = NULL;
  736. #endif //NOT RVC_OS_WIN
  737. ModuleBase* ModuleBase::GetModuleBase()
  738. {
  739. #ifdef RVC_OS_WIN
  740. return (ModuleBase*)(getEntityResource()->m_moduleBase);
  741. #else
  742. return ModuleBase::s_pModuleInst;
  743. #endif //RVC_OS_WIN
  744. }
  745. ModuleBase::ModuleBase()
  746. :m_hInstance(NULL), m_nEntityCount(0)
  747. {
  748. #ifdef RVC_OS_WIN
  749. getEntityResource()->m_moduleBase = this;
  750. #else
  751. ModuleBase::s_pModuleInst = this;
  752. #endif //RVC_OS_WIN
  753. }
  754. CClientSessionBase::~CClientSessionBase()
  755. {
  756. if (m_pSessionFunction) {
  757. SpClientSessionFunction *pFunction = dynamic_cast<SpClientSessionFunction *>(m_pSessionFunction);
  758. m_pSessionFunction = NULL;
  759. pFunction->DecrementRef();
  760. }
  761. }
  762. CSimpleStringA uuid4_generateStr(int len)
  763. {
  764. auto ret = uuid4_generate(len);
  765. return ret.c_str();
  766. }