jexcept.cpp 53 KB

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