jexcept.cpp 42 KB

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