jexcept.cpp 44 KB

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