jexcept.cpp 39 KB

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