jexcept.cpp 52 KB

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