jexcept.cpp 42 KB

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