jexcept.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include <algorithm>
  15. #include "jexcept.hpp"
  16. #include <assert.h>
  17. #include <stdio.h>
  18. #include <stdarg.h>
  19. #include <errno.h>
  20. #include "jptree.hpp"
  21. #ifdef _WIN32
  22. #include "psapi.h"
  23. #include <eh.h>
  24. #elif defined (__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
  25. #include <sys/wait.h>
  26. #include <sys/types.h>
  27. #include <stddef.h>
  28. #include <errno.h>
  29. #ifdef __linux__
  30. #include <execinfo.h> // comment out if not present
  31. #endif
  32. #ifdef __APPLE__
  33. #ifndef _XOPEN_SOURCE
  34. #define _XOPEN_SOURCE
  35. #endif
  36. #include <ucontext.h>
  37. #endif
  38. #endif
  39. //#define NOSEH
  40. #define NO_LINUX_SEH
  41. #define EXTENDED_EXCEPTION_TRACE
  42. #ifdef EXTENDED_EXCEPTION_TRACE
  43. #include "jmisc.hpp"
  44. #define LINUX_SIGNAL_EXCEPTION
  45. #endif
  46. class jlib_thrown_decl StringException: public IException, public CInterface
  47. {
  48. public:
  49. IMPLEMENT_IINTERFACE;
  50. StringException(int code, const char *str, MessageAudience aud = MSGAUD_user) : errcode(code), msg(str), audience(aud) {};
  51. int errorCode() const { return errcode; }
  52. StringBuffer & errorMessage(StringBuffer &str) const { str.append(msg); return str;}
  53. MessageAudience errorAudience() const { return audience; }
  54. protected:
  55. int errcode;
  56. StringAttr msg;
  57. MessageAudience audience;
  58. };
  59. IException *makeStringExceptionVA(int code, const char *format, va_list args)
  60. {
  61. StringBuffer eStr;
  62. eStr.limited_valist_appendf(1024, format, args);
  63. return new StringException(code, eStr.str());
  64. }
  65. IException *makeStringExceptionV(int code,const char *format, ...)
  66. {
  67. va_list args;
  68. va_start(args, format);
  69. IException *ret = makeStringExceptionVA(code, format, args);
  70. va_end(args);
  71. return ret;
  72. }
  73. IException jlib_decl *makeStringException(int code,const char *why)
  74. {
  75. return new StringException(code,why);
  76. }
  77. IException *makeStringExceptionVA(MessageAudience aud, int code, const char *format, va_list args)
  78. {
  79. StringBuffer eStr;
  80. eStr.limited_valist_appendf(1024, format, args);
  81. return new StringException(code, eStr.str(), aud);
  82. }
  83. IException *makeStringExceptionV(MessageAudience aud, int code, const char *format, ...)
  84. {
  85. va_list args;
  86. va_start(args, format);
  87. IException *ret = makeStringExceptionVA(aud, code, format, args);
  88. va_end(args);
  89. return ret;
  90. }
  91. IException jlib_decl *makeStringException(MessageAudience aud,int code,const char *why)
  92. {
  93. return new StringException(code,why,aud);
  94. }
  95. void jlib_decl throwStringExceptionV(int code,const char *format, ...)
  96. {
  97. va_list args;
  98. va_start(args, format);
  99. IException *ret = makeStringExceptionVA(code, format, args);
  100. va_end(args);
  101. throw ret;
  102. }
  103. class jlib_thrown_decl OsException: public IOSException, public CInterface
  104. {
  105. public:
  106. IMPLEMENT_IINTERFACE;
  107. OsException(int code) : errcode(code) {};
  108. OsException(int code, const char *_msg) : msg(_msg), errcode(code) {};
  109. ~OsException() {}
  110. int errorCode() const { return errcode; }
  111. StringBuffer & errorMessage(StringBuffer &str) const
  112. {
  113. if (msg)
  114. str.append(msg).append(", ");
  115. formatSystemError(str, errcode);
  116. return str;
  117. }
  118. MessageAudience errorAudience() const { return MSGAUD_user; }
  119. protected:
  120. StringAttr msg;
  121. int errcode;
  122. };
  123. IOSException *makeOsException(int code)
  124. {
  125. return new OsException(code);
  126. }
  127. IOSException *makeOsException(int code, const char *msg)
  128. {
  129. return new OsException(code, msg);
  130. }
  131. IOSException *makeOsExceptionV(int code, const char *msg, ...)
  132. {
  133. StringBuffer eStr;
  134. va_list args;
  135. va_start(args, msg);
  136. eStr.limited_valist_appendf(1024, msg, args);
  137. va_end(args);
  138. return new OsException(code, eStr.str());
  139. }
  140. class jlib_thrown_decl ErrnoException: public IErrnoException, public CInterface
  141. {
  142. public:
  143. IMPLEMENT_IINTERFACE;
  144. ErrnoException(int errn) : audience(MSGAUD_user) { errcode = errn==-1?errno:errn; }
  145. ErrnoException(int errn, const char *_msg, MessageAudience aud = MSGAUD_user) : msg(_msg), audience(aud) { errcode = errn==-1?errno:errn; }
  146. ~ErrnoException() { }
  147. int errorCode() const { return errcode; }
  148. StringBuffer & errorMessage(StringBuffer &str) const
  149. {
  150. if (msg)
  151. str.append(msg).append(", ");
  152. if (errcode==DISK_FULL_EXCEPTION_CODE)
  153. str.append("Disk full");
  154. else
  155. str.append(strerror(errcode));
  156. return str;
  157. }
  158. MessageAudience errorAudience() const { return audience; }
  159. protected:
  160. StringAttr msg;
  161. int errcode;
  162. MessageAudience audience;
  163. };
  164. IErrnoException *makeErrnoException(int errn, const char *msg)
  165. {
  166. return new ErrnoException(errn, msg);
  167. }
  168. IErrnoException *makeErrnoException(const char *msg)
  169. {
  170. return new ErrnoException(-1, msg);
  171. }
  172. IErrnoException *makeErrnoExceptionV(int errn, const char *msg, ...)
  173. {
  174. StringBuffer eStr;
  175. va_list args;
  176. va_start(args, msg);
  177. eStr.limited_valist_appendf(1024, msg, args);
  178. va_end(args);
  179. return new ErrnoException(errn, eStr.str());
  180. }
  181. IErrnoException *makeErrnoExceptionV(const char *msg, ...)
  182. {
  183. StringBuffer eStr;
  184. va_list args;
  185. va_start(args, msg);
  186. eStr.limited_valist_appendf(1024, msg, args);
  187. va_end(args);
  188. return new ErrnoException(-1, eStr.str());
  189. }
  190. IErrnoException *makeErrnoException(MessageAudience aud, int errn, const char *msg)
  191. {
  192. return new ErrnoException(errn, msg, aud);
  193. }
  194. IErrnoException *makeErrnoExceptionV(MessageAudience aud, int errn, const char *msg, ...)
  195. {
  196. StringBuffer eStr;
  197. va_list args;
  198. va_start(args, msg);
  199. eStr.limited_valist_appendf(1024, msg, args);
  200. va_end(args);
  201. return new ErrnoException(errn, eStr.str(), aud);
  202. }
  203. IErrnoException *makeErrnoExceptionV(MessageAudience aud, const char *msg, ...)
  204. {
  205. StringBuffer eStr;
  206. va_list args;
  207. va_start(args, msg);
  208. eStr.limited_valist_appendf(1024, msg, args);
  209. va_end(args);
  210. return new ErrnoException(-1, eStr.str(), aud);
  211. }
  212. const char* serializeMessageAudience(MessageAudience ma)
  213. {
  214. const char* ret;
  215. switch(ma)
  216. {
  217. case MSGAUD_unknown: ret = "unknown"; break;
  218. case MSGAUD_operator: ret = "operator"; break;
  219. case MSGAUD_user: ret = "user"; break;
  220. case MSGAUD_monitor: ret = "monitor"; break;
  221. case MSGAUD_performance: ret = "performance"; break;
  222. case MSGAUD_internal: ret = "internal"; break;
  223. case MSGAUD_programmer: ret = "programmer"; break;
  224. case MSGAUD_legacy: ret = "legacy"; break;
  225. case MSGAUD_all: ret = "all"; break;
  226. default: ret = "unknown"; break;
  227. }
  228. return ret;
  229. }
  230. MessageAudience deserializeMessageAudience(const char* text)
  231. {
  232. MessageAudience ma = MSGAUD_unknown;
  233. if (text && *text)
  234. {
  235. if (!strcmp(text, "operator"))
  236. ma = MSGAUD_operator;
  237. else if (!strcmp(text, "user"))
  238. ma = MSGAUD_user;
  239. else if (!strcmp(text, "monitor"))
  240. ma = MSGAUD_monitor;
  241. else if (!strcmp(text, "performance"))
  242. ma = MSGAUD_performance;
  243. else if (!strcmp(text, "internal"))
  244. ma = MSGAUD_internal;
  245. else if (!strcmp(text, "programmer"))
  246. ma = MSGAUD_programmer;
  247. else if (!strcmp(text, "legacy"))
  248. ma = MSGAUD_legacy;
  249. else if (!strcmp(text, "all"))
  250. ma = MSGAUD_all;
  251. }
  252. return ma;
  253. }
  254. class jlib_thrown_decl CMultiException : implements IMultiException, public CInterface
  255. {
  256. public:
  257. IMPLEMENT_IINTERFACE
  258. CMultiException(const char* source=NULL)
  259. {
  260. if (source)
  261. source_.append(source);
  262. }
  263. //convenience methods for handling this as an array
  264. virtual aindex_t ordinality() const
  265. {
  266. synchronized block(m_mutex);
  267. return array_.ordinality();
  268. }
  269. virtual IException& item(aindex_t pos) const
  270. {
  271. synchronized block(m_mutex);
  272. return array_.item(pos);
  273. }
  274. virtual const char* source() const
  275. {
  276. synchronized block(m_mutex);
  277. return source_.str();
  278. }
  279. //for complete control...caller is responsible for thread safety!
  280. virtual IArrayOf<IException>& getArray() { return array_; }
  281. //add another exception
  282. virtual void append(IException& e)
  283. {
  284. synchronized block(m_mutex);
  285. array_.append(e);
  286. }
  287. virtual void append(IMultiException& me)
  288. {
  289. synchronized block(m_mutex);
  290. IArrayOf<IException>& exceptions = me.getArray();
  291. const char* source = me.source();
  292. ForEachItemIn(i, exceptions)
  293. {
  294. IException& e = exceptions.item(i);
  295. if (source && *source)
  296. {
  297. StringBuffer msg;
  298. msg.appendf("[%s] ",source);
  299. e.errorMessage(msg);
  300. array_.append(*makeStringExceptionV(e.errorAudience(), e.errorCode(), "%s", msg.str()));
  301. }
  302. else
  303. array_.append(*LINK(&e));
  304. }
  305. }
  306. StringBuffer& serialize(StringBuffer& buffer, unsigned indent = 0, bool simplified=false, bool root=true) const
  307. {
  308. synchronized block(m_mutex);
  309. if (root)
  310. buffer.append("<Exceptions>");
  311. if (!simplified)
  312. {
  313. if (indent) buffer.append("\n\t");
  314. buffer.appendf("<Source>%s</Source>", source_.str());
  315. }
  316. ForEachItemIn(i, array_)
  317. {
  318. IException& exception = array_.item(i);
  319. if (indent) buffer.append("\n\t");
  320. buffer.append("<Exception>");
  321. //tag order is important for some soap clients (i.e. Java Axis)
  322. if (indent) buffer.append("\n\t\t");
  323. buffer.appendf("<Code>%d</Code>", exception.errorCode());
  324. if (indent) buffer.append("\n\t\t");
  325. buffer.appendf("<Audience>%s</Audience>", serializeMessageAudience( exception.errorAudience() ));
  326. if (simplified)
  327. {
  328. if (indent) buffer.append("\n\t\t");
  329. StringBuffer msg;
  330. buffer.appendf("<Source>%s</Source>", source_.str());
  331. }
  332. if (indent) buffer.append("\n\t\t");
  333. StringBuffer msg;
  334. StringBuffer encoded;
  335. encodeXML(exception.errorMessage(msg).str(), encoded);
  336. buffer.appendf("<Message>%s</Message>", encoded.str());
  337. if (indent) buffer.append("\n\t");
  338. buffer.append("</Exception>");
  339. }
  340. if (root)
  341. buffer.append("</Exceptions>");
  342. return buffer;
  343. }
  344. virtual void deserialize(const char* xml)
  345. {
  346. synchronized block(m_mutex);
  347. StringBuffer wrapper;
  348. if (strncmp(xml, "<Exceptions>", 12))
  349. xml = wrapper.appendf("<Exceptions>%s</Exceptions>", xml).str();
  350. Owned<IPropertyTree> pTree = createPTreeFromXMLString(xml);
  351. if (!pTree)
  352. throw makeStringException(-1, "Failed to deserialize IMultiException!");
  353. Owned<IPropertyTreeIterator> i = pTree->getElements("Exception");
  354. if (pTree->hasProp("Source"))
  355. source_.clear().append( pTree->queryProp("Source"));
  356. else
  357. {
  358. if (i->first())
  359. {
  360. IPropertyTree* pNode = &i->query();
  361. source_.clear().append( pNode->queryProp("Source"));
  362. }
  363. }
  364. array_.kill();
  365. ForEach(*i)
  366. {
  367. IPropertyTree* pNode = &i->query();
  368. IException* pException =
  369. makeStringException(
  370. deserializeMessageAudience(pNode->queryProp("Audience")),
  371. pNode->getPropInt("Code", -1),
  372. pNode->queryProp("Message"));
  373. array_.append(*pException);
  374. }
  375. }
  376. //the following methods override those in IIException
  377. //
  378. virtual int errorCode() const
  379. {
  380. synchronized block(m_mutex);
  381. return ordinality() == 1 ? item(0).errorCode() : -1;
  382. }
  383. virtual StringBuffer& errorMessage(StringBuffer &msg) const
  384. {
  385. synchronized block(m_mutex);
  386. ForEachItemIn(i, array_)
  387. {
  388. IException& e = item(i);
  389. StringBuffer buf;
  390. msg.appendf("[%3d: %s] ", e.errorCode(), e.errorMessage(buf).str());
  391. }
  392. return msg;
  393. }
  394. virtual MessageAudience errorAudience() const
  395. {
  396. synchronized block(m_mutex);
  397. return ordinality() == 1 ? item(0).errorAudience() : MSGAUD_unknown;
  398. }
  399. private:
  400. CMultiException( const CMultiException& );
  401. IArrayOf<IException> array_;
  402. StringBuffer source_;
  403. mutable Mutex m_mutex;
  404. };
  405. IMultiException *makeMultiException(const char* source/*=NULL*/)
  406. {
  407. return new CMultiException(source);
  408. }
  409. void pexception(const char *msg,IException *e)
  410. { // like perror except for exceptions
  411. StringBuffer s;
  412. fprintf(stderr,"%s : %s\n",msg,e?e->errorMessage(s).str():"NULL Exception!");
  413. }
  414. void userBreakpoint()
  415. {
  416. #ifdef _WIN32
  417. try
  418. {
  419. DebugBreak();
  420. }
  421. catch (...)
  422. {
  423. //if not debugging don't give an unhandled exception.
  424. }
  425. #endif
  426. }
  427. void throwUnexpectedException(const char * file, unsigned line)
  428. {
  429. printStackReport();
  430. throw makeStringExceptionV(9999, "Internal Error at %s(%d)", file, line);
  431. }
  432. void throwUnexpectedException(const char * where, const char * file, unsigned line)
  433. {
  434. printStackReport();
  435. throw makeStringExceptionV(9999, "Internal Error '%s' at %s(%d)", where, file, line);
  436. }
  437. void raiseAssertException(const char *assertion, const char *file, unsigned line)
  438. {
  439. StringBuffer s;
  440. s.append("assert(");
  441. s.append(assertion);
  442. s.append(") failed - file: ");
  443. s.append(file);
  444. s.append(", line ");
  445. s.append(line);
  446. if (queryLogMsgManager())
  447. {
  448. printStackReport();
  449. ERRLOG("%s",s.str()); // make sure doesn't get lost!
  450. queryLogMsgManager()->flushQueue(10*1000);
  451. #ifdef _DEBUG
  452. // cause a breakpoint in the debugger if we are debugging.
  453. //userBreakpoint();
  454. #endif
  455. }
  456. #if 0
  457. #ifndef USING_MPATROL
  458. #ifdef _WIN32
  459. // disable memory leak dump since it is meaningless in this case
  460. int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  461. tmpFlag &= ~_CRTDBG_LEAK_CHECK_DF;
  462. _CrtSetDbgFlag( tmpFlag );
  463. #endif
  464. #endif
  465. #endif
  466. throw makeStringException(3000, s.str()); // 3000: internal error
  467. }
  468. void raiseAssertCore(const char *assertion, const char *file, unsigned line)
  469. {
  470. printStackReport();
  471. StringBuffer s;
  472. s.append("assert(");
  473. s.append(assertion);
  474. s.append(") failed - file: ");
  475. s.append(file);
  476. s.append(", line ");
  477. s.append(line);
  478. ERRLOG("%s",s.str()); // make sure doesn't get lost!
  479. queryLogMsgManager()->flushQueue(10*1000);
  480. #ifdef _WIN32
  481. userBreakpoint();
  482. ExitProcess(255);
  483. #else
  484. raise(SIGABRT);
  485. _exit(255);
  486. #endif
  487. }
  488. static int SEHnested = 0;
  489. static IExceptionHandler *SEHHandler = NULL;
  490. static bool SEHtermOnSystemDLLs = false;
  491. static bool SEHtermAlways = false;
  492. #ifdef _WIN32
  493. static void *SEHrestore;
  494. #ifdef EXTENDED_EXCEPTION_TRACE
  495. static LPTSTR GetExceptionString( DWORD dwCode )
  496. {
  497. #define EXCEPTION( x ) case EXCEPTION_##x: return #x;
  498. switch ( dwCode )
  499. {
  500. EXCEPTION( ACCESS_VIOLATION )
  501. EXCEPTION( DATATYPE_MISALIGNMENT )
  502. EXCEPTION( BREAKPOINT )
  503. EXCEPTION( SINGLE_STEP )
  504. EXCEPTION( ARRAY_BOUNDS_EXCEEDED )
  505. EXCEPTION( FLT_DENORMAL_OPERAND )
  506. EXCEPTION( FLT_DIVIDE_BY_ZERO )
  507. EXCEPTION( FLT_INEXACT_RESULT )
  508. EXCEPTION( FLT_INVALID_OPERATION )
  509. EXCEPTION( FLT_OVERFLOW )
  510. EXCEPTION( FLT_STACK_CHECK )
  511. EXCEPTION( FLT_UNDERFLOW )
  512. EXCEPTION( INT_DIVIDE_BY_ZERO )
  513. EXCEPTION( INT_OVERFLOW )
  514. EXCEPTION( PRIV_INSTRUCTION )
  515. EXCEPTION( IN_PAGE_ERROR )
  516. EXCEPTION( ILLEGAL_INSTRUCTION )
  517. EXCEPTION( NONCONTINUABLE_EXCEPTION )
  518. EXCEPTION( STACK_OVERFLOW )
  519. EXCEPTION( INVALID_DISPOSITION )
  520. EXCEPTION( GUARD_PAGE )
  521. EXCEPTION( INVALID_HANDLE )
  522. }
  523. static CHAR szBuffer[512] = { 0 };
  524. FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE,
  525. GetModuleHandle( "NTDLL.DLL" ),
  526. dwCode, 0, szBuffer, sizeof( szBuffer ), 0 );
  527. return szBuffer;
  528. }
  529. static BOOL GetLogicalAddress( PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD& offset )
  530. {
  531. szModule[0] = 0;
  532. section = 0;
  533. offset = 0;
  534. if ((unsigned)addr<0x10000)
  535. return FALSE;
  536. MEMORY_BASIC_INFORMATION mbi;
  537. if ( !VirtualQuery( addr, &mbi, sizeof(mbi) ) )
  538. return FALSE;
  539. DWORD hMod = (DWORD)mbi.AllocationBase;
  540. if ( !GetModuleFileName( (HMODULE)hMod, szModule, len ) )
  541. return FALSE;
  542. PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)hMod;
  543. PIMAGE_NT_HEADERS pNtHdr = (PIMAGE_NT_HEADERS)(hMod + pDosHdr->e_lfanew);
  544. PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION( pNtHdr );
  545. DWORD rva = (DWORD)addr - hMod;
  546. for (unsigned i = 0; i < pNtHdr->FileHeader.NumberOfSections; i++, pSection++ )
  547. {
  548. DWORD sectionStart = pSection->VirtualAddress;
  549. DWORD sectionEnd = sectionStart
  550. + std::max(pSection->SizeOfRawData, pSection->Misc.VirtualSize);
  551. if ( (rva >= sectionStart) && (rva <= sectionEnd) )
  552. {
  553. section = i+1;
  554. offset = rva - sectionStart;
  555. return TRUE;
  556. }
  557. }
  558. return FALSE;
  559. }
  560. #if defined(_WIN32)
  561. #ifdef __cplusplus
  562. extern "C" {
  563. typedef BOOL (CALLBACK* LPENUMPROCESSMODULES)(HANDLE,HMODULE *,DWORD,LPDWORD);
  564. typedef BOOL (CALLBACK* LPGETMODULEINFORMATION)(HANDLE,HMODULE,LPMODULEINFO,DWORD);
  565. }
  566. #endif
  567. #endif
  568. static void ModuleWalk()
  569. {
  570. HMODULE hmSystem = LoadLibrary("psapi.dll");
  571. if (!hmSystem)
  572. return;
  573. LPENUMPROCESSMODULES enumProcessModules = (LPENUMPROCESSMODULES)GetProcAddress(hmSystem,"EnumProcessModules");
  574. if (!enumProcessModules)
  575. return;
  576. LPGETMODULEINFORMATION getModuleInformation = (LPGETMODULEINFORMATION)GetProcAddress(hmSystem,"GetModuleInformation");
  577. if (!getModuleInformation)
  578. return;
  579. DWORD processID = GetCurrentProcessId();
  580. PrintLog( "Process ID: %u", processID );
  581. // Get a list of all the modules in this process.
  582. HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
  583. PROCESS_VM_READ,
  584. FALSE, processID );
  585. if (NULL == hProcess)
  586. return;
  587. HMODULE hMods[1024];
  588. DWORD cbNeeded;
  589. if (enumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
  590. for (unsigned i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ ) {
  591. char szModName[MAX_PATH];
  592. szModName[0] = 0;
  593. // Get the full path to the module's file.
  594. MODULEINFO modinfo;
  595. memset(&modinfo,0,sizeof(modinfo));
  596. getModuleInformation(hProcess, hMods[i], &modinfo, sizeof(modinfo));
  597. GetModuleFileName( hMods[i], szModName, sizeof(szModName));
  598. PrintLog("%8X %8X %8X %s",(unsigned)modinfo.lpBaseOfDll,(unsigned)modinfo.SizeOfImage,(unsigned)modinfo.EntryPoint,szModName);
  599. }
  600. }
  601. CloseHandle( hProcess );
  602. FreeLibrary(hmSystem);
  603. }
  604. static void StackWalk( size_t pc, size_t bp )
  605. {
  606. PrintLog( "Call stack:" );
  607. PrintLog( "Address Frame Logical addr Module" );
  608. size_t * pFrame;
  609. size_t * pPrevFrame=NULL;
  610. pFrame = (size_t*)bp;
  611. do
  612. {
  613. TCHAR szModule[MAX_PATH] = "";
  614. DWORD section = 0, offset = 0;
  615. if (pc>0x10000)
  616. GetLogicalAddress((PVOID)pc, szModule,sizeof(szModule),section,offset );
  617. else
  618. strcpy(szModule,"NULL");
  619. PrintLog( "%08X %08X %04X:%08X %s",
  620. pc, pFrame, section, offset, szModule );
  621. if ( (size_t)pFrame & 0x80000003 )
  622. break;
  623. if ( (size_t)pFrame <= (size_t)pPrevFrame )
  624. break;
  625. if ( IsBadWritePtr(pFrame, sizeof(PVOID)*2) )
  626. break;
  627. pc = pFrame[1];
  628. if ( IsBadCodePtr((FARPROC) pc) )
  629. break;
  630. pPrevFrame = pFrame;
  631. pFrame = (size_t *)pFrame[0];
  632. } while ( 1 );
  633. }
  634. static void doPrintStackReport( size_t ip, size_t _bp, size_t sp )
  635. {
  636. if (_bp==0) {
  637. #ifdef _ARCH_X86_
  638. __asm {
  639. mov eax,ebp
  640. mov _bp,eax
  641. }
  642. #else
  643. PrintLog("inline assembler is only supported for x86_32; StackReport incomplete bp tend to not be used");
  644. #endif
  645. }
  646. for (unsigned i=0;i<8;i++) {
  647. StringBuffer s;
  648. #ifdef __64BIT__
  649. s.appendf("Stack[%016X]:",sp);
  650. #else
  651. s.appendf("Stack[%08X]:",sp);
  652. #endif
  653. for (unsigned j=0;j<8;j++) {
  654. if ( IsBadReadPtr((const void *)sp, sizeof(unsigned)) )
  655. break;
  656. size_t v = *(size_t *)sp;
  657. sp += sizeof(unsigned);
  658. #ifdef __64BIT__
  659. s.appendf(" %016X",v);
  660. #else
  661. s.appendf(" %08X",v);
  662. #endif
  663. }
  664. PrintLog( "%s",s.str());
  665. }
  666. StackWalk( ip , _bp);
  667. ModuleWalk();
  668. StringBuffer threadlist;
  669. PrintLog( "ThreadList:\n%s",getThreadList(threadlist).str());
  670. }
  671. static void PrintExceptionReport( PEXCEPTION_POINTERS pExceptionInfo)
  672. {
  673. PrintLog("=====================================================");
  674. PrintMemoryStatusLog();
  675. PEXCEPTION_RECORD pExceptionRecord = pExceptionInfo->ExceptionRecord;
  676. PrintLog( "Exception code: %08X %s",
  677. pExceptionRecord->ExceptionCode,
  678. GetExceptionString(pExceptionRecord->ExceptionCode) );
  679. PrintLog( "Fault address: %08X", pExceptionRecord->ExceptionAddress);
  680. TCHAR szFaultingModule[MAX_PATH];
  681. DWORD section, offset;
  682. GetLogicalAddress( pExceptionRecord->ExceptionAddress,
  683. szFaultingModule,
  684. sizeof( szFaultingModule ),
  685. section, offset );
  686. PrintLog("Fault module: %02X:%08X %s", section, offset, szFaultingModule);
  687. PCONTEXT pCtx = pExceptionInfo->ContextRecord;
  688. PrintLog( "\nRegisters:" );
  689. #ifdef _ARCH_X86_64_
  690. PrintLog("RAX:%016" I64F "X RBX:%016" I64F "X RCX:%016" I64F "X RDX:%016" I64F "X RSI:%016" I64F "X RDI:%016" I64F "X",
  691. pCtx->Rax, pCtx->Rbx, pCtx->Rcx, pCtx->Rdx, pCtx->Rsi, pCtx->Rdi );
  692. PrintLog( "CS:RIP:%04X:%016" I64F "X", pCtx->SegCs, pCtx->Rip );
  693. PrintLog( "SS:PSP:%04X:%016" I64F "X PBP:%016" I64F "X",
  694. pCtx->SegSs, pCtx->Rsp, pCtx->Rbp );
  695. #elif defined(_ARCH_X86_)
  696. PrintLog("EAX:%08X EBX:%08X ECX:%08X EDX:%08X ESI:%08X EDI:%08X",
  697. pCtx->Eax, pCtx->Ebx, pCtx->Ecx, pCtx->Edx, pCtx->Esi, pCtx->Edi );
  698. PrintLog( "CS:EIP:%04X:%08X", pCtx->SegCs, pCtx->Eip );
  699. PrintLog( "SS:ESP:%04X:%08X EBP:%08X",
  700. pCtx->SegSs, pCtx->Esp, pCtx->Ebp );
  701. #else
  702. // ARMFIX: Implement register bank dump for ARM on _WIN32.
  703. PrintLog("Register bank not implemented for your platform");
  704. #endif
  705. PrintLog( "DS:%04X ES:%04X FS:%04X GS:%04X",
  706. pCtx->SegDs, pCtx->SegEs, pCtx->SegFs, pCtx->SegGs );
  707. PrintLog( "Flags:%08X", pCtx->EFlags );
  708. #ifdef _ARCH_X86_64_
  709. doPrintStackReport(pCtx->Rip, pCtx->Rbp,pCtx->Rsp);
  710. #elif defined(_ARCH_X86_)
  711. doPrintStackReport(pCtx->Eip, pCtx->Ebp,pCtx->Esp);
  712. #else
  713. // ARMFIX: Implement stack dump for ARM on _WIN32.
  714. PrintLog("Stack report not implemented for your platform");
  715. #endif
  716. if (SEHtermOnSystemDLLs || SEHtermAlways) {
  717. char *s = szFaultingModule;
  718. while (*s) {
  719. char *sep = strchr(s,'\\');
  720. if (!sep) {
  721. sep = strchr(s,'.');
  722. if (sep)
  723. *sep = 0;
  724. break;
  725. }
  726. s = sep+1;
  727. }
  728. if (SEHtermAlways || (stricmp(s,"ntdll")==0)||(stricmp(s,"kernel32")==0)||(stricmp(s,"msvcrt")==0)||(stricmp(s,"msvcrtd")==0)) {
  729. TerminateProcess(GetCurrentProcess(), 1);
  730. }
  731. }
  732. }
  733. class jlib_thrown_decl CSEHException: public ISEH_Exception, public CInterface
  734. {
  735. public:
  736. IMPLEMENT_IINTERFACE;
  737. CSEHException(unsigned int u, _EXCEPTION_POINTERS* pExp) : errcode((int)u)
  738. {
  739. #ifdef EXTENDED_EXCEPTION_TRACE
  740. PrintExceptionReport(pExp);
  741. #endif
  742. #ifdef ALLREGS
  743. char s[256]; // not too good on stack faults!
  744. sprintf(s,"SEH Exception(%x)\n"
  745. "EAX=%08X EBX=%08X ECX=%08X EDX=%08X ESI=%08X\n"
  746. "EDI=%08X EBP=%08X ESP=%08X EIP=%08X FLG=%08X\n"
  747. "CS=%04X DS=%04X SS=%04X ES=%04X FS=%04X GS=%04X",
  748. u,
  749. pExp->ContextRecord->Eax, pExp->ContextRecord->Ebx,
  750. pExp->ContextRecord->Ecx, pExp->ContextRecord->Edx,
  751. pExp->ContextRecord->Esi, pExp->ContextRecord->Edi,
  752. pExp->ContextRecord->Ebp, pExp->ContextRecord->Esp,
  753. pExp->ContextRecord->Eip, pExp->ContextRecord->EFlags,
  754. pExp->ContextRecord->SegCs, pExp->ContextRecord->SegDs,
  755. pExp->ContextRecord->SegSs, pExp->ContextRecord->SegEs,
  756. pExp->ContextRecord->SegFs, pExp->ContextRecord->SegGs);
  757. #else
  758. char s[80];
  759. #ifdef _ARCH_X86_64_
  760. sprintf(s,"SEH Exception(%08X) at %04X:%016" I64F "X\n",u,pExp->ContextRecord->SegCs,pExp->ContextRecord->Rip);
  761. #elif defined(_ARCH_X86_)
  762. sprintf(s,"SEH Exception(%08X) at %04X:%08X\n",u,pExp->ContextRecord->SegCs,pExp->ContextRecord->Eip);
  763. #else
  764. // ARMFIX: Implement exception dump for ARM on _WIN32.
  765. sprintf(s,"SEH Exception");
  766. #endif
  767. #endif
  768. msg.set(s);
  769. };
  770. int errorCode() const { return errcode; }
  771. StringBuffer & errorMessage(StringBuffer &str) const { str.append(msg); return str;}
  772. MessageAudience errorAudience() const { return MSGAUD_user; }
  773. static void Translate(unsigned int u, _EXCEPTION_POINTERS* pExp)
  774. {
  775. #ifdef _DEBUG
  776. if (u == 0x80000003) return; // int 3 breakpoints
  777. static CriticalSection crit;
  778. {
  779. CriticalBlock b(crit);
  780. PrintExceptionReport(pExp);
  781. }
  782. #endif
  783. ISEH_Exception *e = new CSEHException(u,pExp);
  784. if (SEHHandler && SEHHandler->fireException(e)) return;
  785. throw(e);
  786. }
  787. protected:
  788. int errcode;
  789. StringAttr msg;
  790. };
  791. #endif
  792. #else
  793. #ifdef LINUX_SIGNAL_EXCEPTION
  794. #ifndef NO_LINUX_SEH
  795. static IException *sigsegv_exc;
  796. #endif
  797. static int excsignal;
  798. class jlib_thrown_decl CSEHException: public ISEH_Exception, public CInterface
  799. {
  800. public:
  801. IMPLEMENT_IINTERFACE;
  802. CSEHException(int signum, const char *s)
  803. {
  804. errcode = signum;
  805. msg.set(s);
  806. };
  807. int errorCode() const { return errcode; }
  808. StringBuffer & errorMessage(StringBuffer &str) const { str.append(msg); return str;}
  809. MessageAudience errorAudience() const { return MSGAUD_user; }
  810. protected:
  811. int errcode;
  812. StringAttr msg;
  813. };
  814. #ifndef NO_LINUX_SEH
  815. static void throwSigSegV()
  816. {
  817. int childpid = fork();
  818. if (childpid <= 0) { // the child
  819. // generate a coredump on different process
  820. signal(excsignal, SIG_DFL);
  821. raise(excsignal);
  822. return;
  823. }
  824. PROGLOG("Dumping core using child process %d",childpid);
  825. waitpid(childpid, NULL, 0);
  826. if (SEHHandler && SEHHandler->fireException(sigsegv_exc))
  827. return;
  828. throw sigsegv_exc;
  829. }
  830. #endif
  831. void excsighandler(int signum, siginfo_t *info, void *extra)
  832. {
  833. static byte nested=0;
  834. if (nested++)
  835. return;
  836. excsignal = 0;
  837. #if defined(NO_LINUX_SEH)
  838. // ensure other signals from now on cause exit
  839. sigset_t blockset;
  840. sigemptyset(&blockset);
  841. struct sigaction act;
  842. act.sa_mask = blockset;
  843. act.sa_flags = 0;
  844. act.sa_handler = SIG_DFL;
  845. sigaction(SIGSEGV, &act, NULL);
  846. sigaction(SIGILL, &act, NULL);
  847. sigaction(SIGBUS, &act, NULL);
  848. sigaction(SIGFPE, &act, NULL);
  849. sigaction(SIGABRT, &act, NULL);
  850. #endif
  851. StringBuffer s;
  852. #ifdef _ARCH_X86_64_
  853. #define I64X "%016" I64F "X"
  854. ucontext_t *uc = (ucontext_t *)extra;
  855. #ifdef __APPLE__
  856. __int64 ip = uc->uc_mcontext->__ss.__rip;
  857. __int64 sp = uc->uc_mcontext->__ss.__rsp;
  858. #else
  859. __int64 ip = uc->uc_mcontext.gregs[REG_RIP];
  860. __int64 sp = uc->uc_mcontext.gregs[REG_RSP];
  861. #endif
  862. excsignal = signum;
  863. s.appendf("SIG: %s(%d), accessing " I64X ", IP=" I64X, strsignal(signum),signum, (__int64)info->si_addr, ip);
  864. PROGLOG("================================================");
  865. PROGLOG("Signal: %d %s",signum,strsignal(signum));
  866. PROGLOG("Fault IP: " I64X "", ip);
  867. PROGLOG("Accessing: " I64X "", (unsigned __int64) info->si_addr);
  868. #ifdef _EXECINFO_H
  869. printStackReport(ip);
  870. #endif
  871. PROGLOG("Registers:" );
  872. PROGLOG("EAX:" I64X " EBX:" I64X " ECX:" I64X " EDX:" I64X " ESI:" I64X " EDI:" I64X "",
  873. #ifdef __APPLE__
  874. (unsigned __int64) uc->uc_mcontext->__ss.__rax, (unsigned __int64)uc->uc_mcontext->__ss.__rbx,
  875. (unsigned __int64) uc->uc_mcontext->__ss.__rcx, (unsigned __int64)uc->uc_mcontext->__ss.__rdx,
  876. (unsigned __int64) uc->uc_mcontext->__ss.__rsi, (unsigned __int64)uc->uc_mcontext->__ss.__rdi);
  877. PROGLOG( "CS:EIP:%04X:" I64X "", ((unsigned) uc->uc_mcontext->__ss.__cs)&0xffff, ip );
  878. PROGLOG( " ESP:" I64X " EBP:" I64X "", sp, (unsigned __int64) uc->uc_mcontext->__ss.__rbp );
  879. #else
  880. (unsigned __int64) uc->uc_mcontext.gregs[REG_RAX], (unsigned __int64)uc->uc_mcontext.gregs[REG_RBX],
  881. (unsigned __int64) uc->uc_mcontext.gregs[REG_RCX], (unsigned __int64) uc->uc_mcontext.gregs[REG_RDX],
  882. (unsigned __int64) uc->uc_mcontext.gregs[REG_RSI], (unsigned __int64) uc->uc_mcontext.gregs[REG_RDI] );
  883. PROGLOG( "CS:EIP:%04X:" I64X "", ((unsigned) uc->uc_mcontext.gregs[REG_CSGSFS])&0xffff, ip );
  884. PROGLOG( " ESP:" I64X " EBP:" I64X "", sp, (unsigned __int64) uc->uc_mcontext.gregs[REG_RBP] );
  885. #endif
  886. for (unsigned i=0;i<8;i++) {
  887. StringBuffer s;
  888. s.appendf("Stack[" I64X "]:",sp);
  889. for (unsigned j=0;j<8;j++) {
  890. __int64 v = *(size_t *)sp;
  891. sp += sizeof(unsigned);
  892. s.appendf(" " I64X "",v);
  893. }
  894. PROGLOG( "%s",s.str());
  895. }
  896. #elif defined (__linux__) && defined (_ARCH_X86_)
  897. ucontext_t *uc = (ucontext_t *)extra;
  898. unsigned ip = uc->uc_mcontext.gregs[REG_EIP];
  899. unsigned sp = uc->uc_mcontext.gregs[REG_ESP];
  900. excsignal = signum;
  901. s.appendf("SIG: %s(%d), accessing %p, IP=%x", strsignal(signum),signum, info->si_addr, ip);
  902. PROGLOG("================================================");
  903. PROGLOG("Signal: %d %s",signum,strsignal(signum));
  904. PROGLOG("Fault IP: %08X", ip);
  905. PROGLOG("Accessing: %08X", (unsigned) info->si_addr);
  906. #ifdef _EXECINFO_H
  907. printStackReport(ip);
  908. #endif
  909. PROGLOG("Registers:" );
  910. PROGLOG("EAX:%08X EBX:%08X ECX:%08X EDX:%08X ESI:%08X EDI:%08X",
  911. uc->uc_mcontext.gregs[REG_EAX], uc->uc_mcontext.gregs[REG_EBX],
  912. uc->uc_mcontext.gregs[REG_ECX], uc->uc_mcontext.gregs[REG_EDX],
  913. uc->uc_mcontext.gregs[REG_ESI], uc->uc_mcontext.gregs[REG_EDI] );
  914. PROGLOG( "CS:EIP:%04X:%08X", uc->uc_mcontext.gregs[REG_CS], ip );
  915. PROGLOG( "SS:ESP:%04X:%08X EBP:%08X",
  916. uc->uc_mcontext.gregs[REG_SS], sp, uc->uc_mcontext.gregs[REG_EBP] );
  917. for (unsigned i=0;i<8;i++) {
  918. StringBuffer s;
  919. s.appendf("Stack[%08X]:",sp);
  920. for (unsigned j=0;j<8;j++) {
  921. size_t v = *(size_t *)sp;
  922. sp += sizeof(unsigned);
  923. s.appendf(" %08X",v);
  924. }
  925. PROGLOG( "%s",s.str());
  926. }
  927. PROGLOG("Frame:");
  928. unsigned* bp = (unsigned*) (uc->uc_mcontext.gregs[REG_EBP]);
  929. for (unsigned n=0; n<64; n++) {
  930. unsigned * nextbp = (unsigned *) *bp++;
  931. unsigned fip = *bp;
  932. if ((fip < 0x08000000) || (fip > 0x7fffffff) || (nextbp < bp))
  933. break;
  934. PROGLOG("%2d %08X %08X",n+1,fip,(unsigned) bp);
  935. bp = nextbp;
  936. }
  937. #elif defined (__linux__) && defined (__ARM_ARCH_7A__)
  938. #pragma message "Implement signal dump for ARMv7-A."
  939. ucontext_t *uc = (ucontext_t *) extra;
  940. PROGLOG("================================================");
  941. PROGLOG("Signal: %d %s",signum,strsignal(signum));
  942. PROGLOG("Registers:" );
  943. PROGLOG("r0 :%08lX r1 :%08lX r2 :%08lX r3 :%08lX r4 :%08lX r5 :%08lX",
  944. uc->uc_mcontext.arm_r0, uc->uc_mcontext.arm_r1, uc->uc_mcontext.arm_r2,
  945. uc->uc_mcontext.arm_r3, uc->uc_mcontext.arm_r4, uc->uc_mcontext.arm_r5);
  946. PROGLOG("r6 :%08lX r7 :%08lX r8 :%08lX r9 :%08lX r10:%08lX fp :%08lX",
  947. uc->uc_mcontext.arm_r6, uc->uc_mcontext.arm_r7, uc->uc_mcontext.arm_r8,
  948. uc->uc_mcontext.arm_r9, uc->uc_mcontext.arm_r10, uc->uc_mcontext.arm_fp);
  949. PROGLOG("ip :%08lX sp :%08lX lr :%08lX pc :%08lX",
  950. uc->uc_mcontext.arm_ip, uc->uc_mcontext.arm_sp, uc->uc_mcontext.arm_lr,
  951. uc->uc_mcontext.arm_pc);
  952. PROGLOG("CPSR:%08lX\n", uc->uc_mcontext.arm_cpsr);
  953. struct flags
  954. {
  955. unsigned int Mode:4; // bit 0 - 3
  956. unsigned int M:1; // bit 4
  957. unsigned int T:1; // bit 5
  958. unsigned int F:1; // bit 6
  959. unsigned int I:1; // bit 7
  960. unsigned int A:1; // bit 8
  961. unsigned int E:1; // bit 9
  962. unsigned int IT1:6; // bit 10 - 15
  963. unsigned int GE:4; // bit 16 - 19
  964. unsigned int DNM:4; // bit 20 - 23
  965. unsigned int J:1; // bit 24
  966. unsigned int IT2:2; // bit 25 - 26
  967. unsigned int Q:1; // bit 27
  968. unsigned int V:1; // bit 28
  969. unsigned int C:1; // bit 29
  970. unsigned int Z:1; // bit 30
  971. unsigned int N:1; // bit 31
  972. } *flags_p;
  973. const char *ArmCpuModes[] = {
  974. // M M[3:0]
  975. "User", // 1 0000
  976. "FIQ", // 1 0001
  977. "IRQ", // 1 0010
  978. "Supervisor", // 1 0011
  979. "N/A", // 1 0100
  980. "N/A", // 1 0101
  981. "Monitor", // 1 0110
  982. "Abort", // 1 0111
  983. "N/A", // 1 1000
  984. "N/A", // 1 1001
  985. "Hyp" // 1 1010
  986. "Undefined", // 1 1011
  987. "N/A", // 1 1100
  988. "N/A", // 1 1101
  989. "N/A", // 1 1110
  990. "System" // 1 1111
  991. };
  992. flags_p = (struct flags *)&uc->uc_mcontext.arm_cpsr;
  993. PROGLOG("Flags N:%d Z:%d C:%d V:%d Q:%d IT:0x%X J:%d GE:0x%X E:%d A:%d I:%d F:%d T:%d M:0x%X [%s]"
  994. , flags_p->N, flags_p->Z, flags_p->C, flags_p->V, flags_p->Q
  995. , (flags_p->IT2 << 6 | flags_p->IT1)
  996. , flags_p->J, flags_p->GE
  997. , flags_p->E, flags_p->A, flags_p->I, flags_p->F, flags_p->T, (flags_p->M << 4 | flags_p->Mode)
  998. , ArmCpuModes[flags_p->Mode]
  999. );
  1000. PROGLOG("Fault address: %08lX", uc->uc_mcontext.fault_address);
  1001. PROGLOG("Trap no : %08lX", uc->uc_mcontext.trap_no);
  1002. PROGLOG("Error code : %08lX", uc->uc_mcontext.error_code);
  1003. PROGLOG("Old mask : %08lX", uc->uc_mcontext.oldmask);
  1004. unsigned sp = uc->uc_mcontext.arm_sp;
  1005. for (unsigned i=0;i<8;i++)
  1006. {
  1007. StringBuffer s;
  1008. s.appendf("Stack[%08X]:",sp);
  1009. for (unsigned j=0;j<8;j++)
  1010. {
  1011. size_t v = *(size_t *)sp;
  1012. sp += sizeof(unsigned);
  1013. s.appendf(" %08X",v);
  1014. }
  1015. }
  1016. PROGLOG( "%s",s.str());
  1017. #elif defined (__linux__) && defined (__arm__)
  1018. #pragma message "Unknown ARM architecture!"
  1019. PROGLOG("================================================");
  1020. PROGLOG("Signal: %d %s",signum,strsignal(signum));
  1021. PROGLOG("More information unavailable on your platform");
  1022. #else
  1023. // Placeholder for any new HW-SW platform
  1024. #endif
  1025. StringBuffer threadlist;
  1026. PROGLOG( "ThreadList:\n%s",getThreadList(threadlist).str());
  1027. queryLogMsgManager()->flushQueue(10*1000);
  1028. // MCK - really should not return after recv'ing any of these signals
  1029. #ifndef NO_LINUX_SEH
  1030. void (* _P)() = throwSigSegV;
  1031. uc->uc_mcontext.gregs[REG_ESP]-=4;
  1032. uc->uc_mcontext.gregs[REG_EIP] = (unsigned)_P;
  1033. unsigned *spp = (unsigned *)sp;
  1034. *spp = ip;
  1035. sigsegv_exc = new CSEHException(signum,s.str());
  1036. #else
  1037. if (SEHHandler)
  1038. {
  1039. if ( SEHHandler->fireException(new CSEHException(signum,s.str())) )
  1040. return;
  1041. }
  1042. raise(signum);
  1043. #endif
  1044. nested--;
  1045. }
  1046. #endif
  1047. #endif
  1048. void jlib_decl setTerminateOnSEHInSystemDLLs(bool set)
  1049. {
  1050. SEHtermOnSystemDLLs = set;
  1051. }
  1052. void jlib_decl setTerminateOnSEH(bool set)
  1053. {
  1054. SEHtermAlways = set;
  1055. }
  1056. void *EnableSEHtranslation()
  1057. {
  1058. #ifdef NOSEH
  1059. return NULL;
  1060. #else
  1061. #ifdef _WIN32
  1062. return _set_se_translator( CSEHException::Translate );
  1063. #else
  1064. UNIMPLEMENTED;
  1065. #endif
  1066. #endif
  1067. }
  1068. void jlib_decl *setSEHtoExceptionHandler(IExceptionHandler *handler)
  1069. {
  1070. #ifdef NOSEH
  1071. return NULL;
  1072. #endif
  1073. void *ret = SEHHandler;
  1074. SEHHandler = handler;
  1075. return ret;
  1076. }
  1077. void jlib_decl enableSEHtoExceptionMapping()
  1078. {
  1079. #ifdef NOSEH
  1080. return;
  1081. #endif
  1082. if (SEHnested++)
  1083. return; // already done
  1084. #ifdef _WIN32
  1085. enableThreadSEH();
  1086. SEHrestore = EnableSEHtranslation();
  1087. #else
  1088. struct sigaction act;
  1089. sigset_t blockset;
  1090. sigemptyset(&blockset);
  1091. // defer these for thread in handler
  1092. sigaddset(&blockset, SIGINT);
  1093. sigaddset(&blockset, SIGQUIT);
  1094. sigaddset(&blockset, SIGTERM);
  1095. act.sa_mask = blockset;
  1096. act.sa_flags = SA_SIGINFO;
  1097. #if defined(SA_RESETHAND)
  1098. act.sa_flags |= SA_RESETHAND;
  1099. #endif
  1100. act.sa_sigaction = &excsighandler;
  1101. sigaction(SIGSEGV, &act, NULL);
  1102. sigaction(SIGILL, &act, NULL);
  1103. sigaction(SIGBUS, &act, NULL);
  1104. sigaction(SIGFPE, &act, NULL);
  1105. sigaction(SIGABRT, &act, NULL);
  1106. #endif
  1107. }
  1108. void jlib_decl disableSEHtoExceptionMapping()
  1109. {
  1110. #ifdef NOSEH
  1111. return;
  1112. #endif
  1113. if (--SEHnested)
  1114. return;
  1115. #ifdef _WIN32
  1116. if (SEHrestore) {
  1117. void *restore = SEHrestore;
  1118. SEHrestore = NULL;
  1119. _set_se_translator( (_se_translator_function)restore );
  1120. }
  1121. #else
  1122. sigset_t blockset;
  1123. sigemptyset(&blockset);
  1124. struct sigaction act;
  1125. act.sa_mask = blockset;
  1126. act.sa_flags = 0;
  1127. act.sa_handler = SIG_DFL;
  1128. sigaction(SIGSEGV, &act, NULL);
  1129. sigaction(SIGILL, &act, NULL);
  1130. sigaction(SIGBUS, &act, NULL);
  1131. sigaction(SIGFPE, &act, NULL);
  1132. sigaction(SIGABRT, &act, NULL);
  1133. #endif
  1134. }
  1135. StringBuffer & formatSystemError(StringBuffer & out, unsigned errcode)
  1136. {
  1137. #ifdef _WIN32
  1138. const char * lpMessageBuffer=NULL;
  1139. FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  1140. NULL,
  1141. errcode,
  1142. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default
  1143. (LPTSTR) &lpMessageBuffer,
  1144. 0,
  1145. NULL );
  1146. if (lpMessageBuffer) {
  1147. out.append(lpMessageBuffer);
  1148. LocalFree( (void *)lpMessageBuffer );
  1149. }
  1150. else {
  1151. out.append(errcode);
  1152. }
  1153. #else
  1154. int saverr = errno;
  1155. errno = 0;
  1156. const char *errstr = strerror(errcode);
  1157. if (errno==0) {
  1158. out.append(errstr);
  1159. }
  1160. else {
  1161. out.append(errcode);
  1162. }
  1163. errno = saverr;
  1164. #endif
  1165. return out;
  1166. }
  1167. IException * deserializeException(MemoryBuffer & in)
  1168. {
  1169. byte nulle;
  1170. in.read(nulle);
  1171. if (nulle) return NULL;
  1172. int code;
  1173. StringAttr text;
  1174. in.read(code);
  1175. in.read(text);
  1176. return makeStringExceptionV(code, "%s", text.get());
  1177. }
  1178. void jlib_decl serializeException(IException * e, MemoryBuffer & out)
  1179. {
  1180. if (!e)
  1181. out.append((byte)1);
  1182. else
  1183. {
  1184. out.append((byte)0);
  1185. StringBuffer text;
  1186. out.append(e->errorCode());
  1187. out.append(e->errorMessage(text).str());
  1188. }
  1189. }
  1190. void printStackReport(__int64 startIP)
  1191. {
  1192. if (!queryLogMsgManager())
  1193. return;
  1194. #ifdef _WIN32
  1195. unsigned onstack=1234;
  1196. doPrintStackReport(0, 0,(unsigned)&onstack);
  1197. #elif defined(__linux__)
  1198. DBGLOG("Backtrace:");
  1199. void *btarray[100];
  1200. unsigned btn = backtrace (btarray, 100);
  1201. char **strings = backtrace_symbols (btarray, btn);
  1202. unsigned i;
  1203. unsigned firstReal = 0;
  1204. if (startIP)
  1205. {
  1206. VStringBuffer iptext("[%p]", (void *) startIP);
  1207. for (i=0; i<btn; i++)
  1208. {
  1209. if (strstr(strings[i], iptext) != nullptr)
  1210. {
  1211. firstReal = i;
  1212. break;
  1213. }
  1214. }
  1215. }
  1216. for (i=firstReal; i<btn; i++)
  1217. DBGLOG(" %s", strings[i]);
  1218. free (strings);
  1219. #endif
  1220. queryLogMsgManager()->flushQueue(10*1000);
  1221. }
  1222. //---------------------------------------------------------------------------------------------------------------------
  1223. class jlib_decl CError : public CInterfaceOf<IError>
  1224. {
  1225. public:
  1226. CError(WarnErrorCategory _category,ErrorSeverity _severity, int _no, const char* _msg, const char* _filename, int _lineno, int _column, int _position, unsigned _activity);
  1227. virtual int errorCode() const { return no; }
  1228. virtual StringBuffer & errorMessage(StringBuffer & ret) const { return ret.append(msg); }
  1229. virtual MessageAudience errorAudience() const { return MSGAUD_user; }
  1230. virtual const char* getFilename() const { return filename; }
  1231. virtual WarnErrorCategory getCategory() const { return category; }
  1232. virtual int getLine() const { return lineno; }
  1233. virtual int getColumn() const { return column; }
  1234. virtual int getPosition() const { return position; }
  1235. virtual StringBuffer& toString(StringBuffer&) const;
  1236. virtual ErrorSeverity getSeverity() const { return severity; }
  1237. virtual IError * cloneSetSeverity(ErrorSeverity _severity) const;
  1238. virtual unsigned getActivity() const { return activity; }
  1239. protected:
  1240. ErrorSeverity severity;
  1241. WarnErrorCategory category;
  1242. int no;
  1243. StringAttr msg;
  1244. StringAttr filename;
  1245. int lineno;
  1246. int column;
  1247. int position;
  1248. unsigned activity;
  1249. };
  1250. CError::CError(WarnErrorCategory _category, ErrorSeverity _severity, int _no, const char* _msg, const char* _filename, int _lineno, int _column, int _position, unsigned _activity)
  1251. : severity(_severity), category(_category), msg(_msg), filename(_filename), activity(_activity)
  1252. {
  1253. no = _no;
  1254. lineno = _lineno;
  1255. column = _column;
  1256. position = _position;
  1257. }
  1258. StringBuffer& CError::toString(StringBuffer& buf) const
  1259. {
  1260. buf.append(filename);
  1261. if(lineno && column)
  1262. buf.append('(').append(lineno).append(',').append(column).append(')');
  1263. buf.append(" : ");
  1264. buf.append(no).append(": ").append(msg);
  1265. return buf;
  1266. }
  1267. IError * CError::cloneSetSeverity(ErrorSeverity newSeverity) const
  1268. {
  1269. return new CError(category, newSeverity,
  1270. errorCode(), msg, filename,
  1271. getLine(), getColumn(), getPosition(), getActivity());
  1272. }
  1273. IError *createError(WarnErrorCategory category, ErrorSeverity severity, int errNo, const char *msg, const char * filename, int lineno, int column, int pos, unsigned activity)
  1274. {
  1275. return new CError(category,severity,errNo,msg,filename,lineno,column,pos, activity);
  1276. }
  1277. IError *createError(WarnErrorCategory category, ErrorSeverity severity, int errNo, const char *msg, unsigned activity)
  1278. {
  1279. return new CError(category,severity,errNo,msg,nullptr, 0, 0, 0, activity);
  1280. }