backward.hpp 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406
  1. /*
  2. * backward.hpp
  3. * Copyright 2013 Google Inc. All Rights Reserved.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. #ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
  24. #define H_6B9572DA_A64B_49E6_B234_051480991C89
  25. #ifndef __cplusplus
  26. #error "It's not going to compile without a C++ compiler..."
  27. #endif
  28. #if defined(BACKWARD_CXX11)
  29. #elif defined(BACKWARD_CXX98)
  30. #else
  31. #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)
  32. #define BACKWARD_CXX11
  33. #define BACKWARD_ATLEAST_CXX11
  34. #define BACKWARD_ATLEAST_CXX98
  35. #else
  36. #define BACKWARD_CXX98
  37. #define BACKWARD_ATLEAST_CXX98
  38. #endif
  39. #endif
  40. // You can define one of the following (or leave it to the auto-detection):
  41. //
  42. // #define BACKWARD_SYSTEM_LINUX
  43. // - specialization for linux
  44. //
  45. // #define BACKWARD_SYSTEM_DARWIN
  46. // - specialization for Mac OS X 10.5 and later.
  47. //
  48. // #define BACKWARD_SYSTEM_WINDOWS
  49. // - specialization for Windows (Clang 9 and MSVC2017)
  50. //
  51. // #define BACKWARD_SYSTEM_UNKNOWN
  52. // - placebo implementation, does nothing.
  53. //
  54. #if defined(BACKWARD_SYSTEM_LINUX)
  55. #elif defined(BACKWARD_SYSTEM_DARWIN)
  56. #elif defined(BACKWARD_SYSTEM_UNKNOWN)
  57. #elif defined(BACKWARD_SYSTEM_WINDOWS)
  58. #else
  59. #if defined(__linux) || defined(__linux__)
  60. #define BACKWARD_SYSTEM_LINUX
  61. #elif defined(__APPLE__)
  62. #define BACKWARD_SYSTEM_DARWIN
  63. #elif defined(_WIN32)
  64. #define BACKWARD_SYSTEM_WINDOWS
  65. #else
  66. #define BACKWARD_SYSTEM_UNKNOWN
  67. #endif
  68. #endif
  69. #define NOINLINE __attribute__((noinline))
  70. #include <algorithm>
  71. #include <cctype>
  72. #include <cstdio>
  73. #include <cstdlib>
  74. #include <cstring>
  75. #include <fstream>
  76. #include <iomanip>
  77. #include <iostream>
  78. #include <limits>
  79. #include <new>
  80. #include <sstream>
  81. #include <streambuf>
  82. #include <string>
  83. #include <vector>
  84. #include <exception>
  85. #if defined(BACKWARD_SYSTEM_LINUX)
  86. // On linux, backtrace can back-trace or "walk" the stack using the following
  87. // libraries:
  88. //
  89. // #define BACKWARD_HAS_UNWIND 1
  90. // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
  91. // - with unwind, the stacktrace is as accurate as it can possibly be, since
  92. // this is used by the C++ runtine in gcc/clang for stack unwinding on
  93. // exception.
  94. // - normally libgcc is already linked to your program by default.
  95. //
  96. // #define BACKWARD_HAS_LIBUNWIND 1
  97. // - libunwind provides, in some cases, a more accurate stacktrace as it knows
  98. // to decode signal handler frames and lets us edit the context registers when
  99. // unwinding, allowing stack traces over bad function references.
  100. //
  101. // #define BACKWARD_HAS_BACKTRACE == 1
  102. // - backtrace seems to be a little bit more portable than libunwind, but on
  103. // linux, it uses unwind anyway, but abstract away a tiny information that is
  104. // sadly really important in order to get perfectly accurate stack traces.
  105. // - backtrace is part of the (e)glib library.
  106. //
  107. // The default is:
  108. // #define BACKWARD_HAS_UNWIND == 1
  109. //
  110. // Note that only one of the define should be set to 1 at a time.
  111. //
  112. #if BACKWARD_HAS_UNWIND == 1
  113. #elif BACKWARD_HAS_LIBUNWIND == 1
  114. #elif BACKWARD_HAS_BACKTRACE == 1
  115. #else
  116. #undef BACKWARD_HAS_UNWIND
  117. #define BACKWARD_HAS_UNWIND 1
  118. #undef BACKWARD_HAS_LIBUNWIND
  119. #define BACKWARD_HAS_LIBUNWIND 0
  120. #undef BACKWARD_HAS_BACKTRACE
  121. #define BACKWARD_HAS_BACKTRACE 0
  122. #endif
  123. // On linux, backward can extract detailed information about a stack trace
  124. // using one of the following libraries:
  125. //
  126. // #define BACKWARD_HAS_DW 1
  127. // - libdw gives you the most juicy details out of your stack traces:
  128. // - object filename
  129. // - function name
  130. // - source filename
  131. // - line and column numbers
  132. // - source code snippet (assuming the file is accessible)
  133. // - variables name and values (if not optimized out)
  134. // - You need to link with the lib "dw":
  135. // - apt-get install libdw-dev
  136. // - g++/clang++ -ldw ...
  137. //
  138. // #define BACKWARD_HAS_BFD 1
  139. // - With libbfd, you get a fair amount of details:
  140. // - object filename
  141. // - function name
  142. // - source filename
  143. // - line numbers
  144. // - source code snippet (assuming the file is accessible)
  145. // - You need to link with the lib "bfd":
  146. // - apt-get install binutils-dev
  147. // - g++/clang++ -lbfd ...
  148. //
  149. // #define BACKWARD_HAS_DWARF 1
  150. // - libdwarf gives you the most juicy details out of your stack traces:
  151. // - object filename
  152. // - function name
  153. // - source filename
  154. // - line and column numbers
  155. // - source code snippet (assuming the file is accessible)
  156. // - variables name and values (if not optimized out)
  157. // - You need to link with the lib "dwarf":
  158. // - apt-get install libdwarf-dev
  159. // - g++/clang++ -ldwarf ...
  160. //
  161. // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
  162. // - backtrace provides minimal details for a stack trace:
  163. // - object filename
  164. // - function name
  165. // - backtrace is part of the (e)glib library.
  166. //
  167. // The default is:
  168. // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  169. //
  170. // Note that only one of the define should be set to 1 at a time.
  171. //
  172. #if BACKWARD_HAS_DW == 1
  173. #elif BACKWARD_HAS_BFD == 1
  174. #elif BACKWARD_HAS_DWARF == 1
  175. #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  176. #else
  177. #undef BACKWARD_HAS_DW
  178. #define BACKWARD_HAS_DW 0
  179. #undef BACKWARD_HAS_BFD
  180. #define BACKWARD_HAS_BFD 0
  181. #undef BACKWARD_HAS_DWARF
  182. #define BACKWARD_HAS_DWARF 0
  183. #undef BACKWARD_HAS_BACKTRACE_SYMBOL
  184. #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
  185. #endif
  186. #include <cxxabi.h>
  187. #include <fcntl.h>
  188. #ifdef __ANDROID__
  189. // Old Android API levels define _Unwind_Ptr in both link.h and
  190. // unwind.h Rename the one in link.h as we are not going to be using
  191. // it
  192. #define _Unwind_Ptr _Unwind_Ptr_Custom
  193. #include <link.h>
  194. #undef _Unwind_Ptr
  195. #else
  196. #include <link.h>
  197. #endif
  198. #include <signal.h>
  199. #include <sys/stat.h>
  200. #include <syscall.h>
  201. #include <unistd.h>
  202. #if BACKWARD_HAS_BFD == 1
  203. // NOTE: defining PACKAGE{,_VERSION} is required before including
  204. // bfd.h on some platforms, see also:
  205. // https://sourceware.org/bugzilla/show_bug.cgi?id=14243
  206. #ifndef PACKAGE
  207. #define PACKAGE
  208. #endif
  209. #ifndef PACKAGE_VERSION
  210. #define PACKAGE_VERSION
  211. #endif
  212. #include <bfd.h>
  213. #ifndef _GNU_SOURCE
  214. #define _GNU_SOURCE
  215. #include <dlfcn.h>
  216. #undef _GNU_SOURCE
  217. #else
  218. #include <dlfcn.h>
  219. #endif
  220. #endif
  221. #if BACKWARD_HAS_DW == 1
  222. #include <dwarf.h>
  223. #include <elfutils/libdw.h>
  224. #include <elfutils/libdwfl.h>
  225. #endif
  226. #if BACKWARD_HAS_DWARF == 1
  227. #include <algorithm>
  228. #include <dwarf.h>
  229. #include <libdwarf.h>
  230. #include <libelf.h>
  231. #include <map>
  232. #ifndef _GNU_SOURCE
  233. #define _GNU_SOURCE
  234. #include <dlfcn.h>
  235. #undef _GNU_SOURCE
  236. #else
  237. #include <dlfcn.h>
  238. #endif
  239. #endif
  240. #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
  241. // then we shall rely on backtrace
  242. #include <execinfo.h>
  243. #endif
  244. #endif // defined(BACKWARD_SYSTEM_LINUX)
  245. #if defined(BACKWARD_SYSTEM_DARWIN)
  246. // On Darwin, backtrace can back-trace or "walk" the stack using the following
  247. // libraries:
  248. //
  249. // #define BACKWARD_HAS_UNWIND 1
  250. // - unwind comes from libgcc, but I saw an equivalent inside clang itself.
  251. // - with unwind, the stacktrace is as accurate as it can possibly be, since
  252. // this is used by the C++ runtine in gcc/clang for stack unwinding on
  253. // exception.
  254. // - normally libgcc is already linked to your program by default.
  255. //
  256. // #define BACKWARD_HAS_LIBUNWIND 1
  257. // - libunwind comes from clang, which implements an API compatible version.
  258. // - libunwind provides, in some cases, a more accurate stacktrace as it knows
  259. // to decode signal handler frames and lets us edit the context registers when
  260. // unwinding, allowing stack traces over bad function references.
  261. //
  262. // #define BACKWARD_HAS_BACKTRACE == 1
  263. // - backtrace is available by default, though it does not produce as much
  264. // information as another library might.
  265. //
  266. // The default is:
  267. // #define BACKWARD_HAS_UNWIND == 1
  268. //
  269. // Note that only one of the define should be set to 1 at a time.
  270. //
  271. #if BACKWARD_HAS_UNWIND == 1
  272. #elif BACKWARD_HAS_BACKTRACE == 1
  273. #elif BACKWARD_HAS_LIBUNWIND == 1
  274. #else
  275. #undef BACKWARD_HAS_UNWIND
  276. #define BACKWARD_HAS_UNWIND 1
  277. #undef BACKWARD_HAS_BACKTRACE
  278. #define BACKWARD_HAS_BACKTRACE 0
  279. #undef BACKWARD_HAS_LIBUNWIND
  280. #define BACKWARD_HAS_LIBUNWIND 0
  281. #endif
  282. // On Darwin, backward can extract detailed information about a stack trace
  283. // using one of the following libraries:
  284. //
  285. // #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
  286. // - backtrace provides minimal details for a stack trace:
  287. // - object filename
  288. // - function name
  289. //
  290. // The default is:
  291. // #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  292. //
  293. #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  294. #else
  295. #undef BACKWARD_HAS_BACKTRACE_SYMBOL
  296. #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
  297. #endif
  298. #include <cxxabi.h>
  299. #include <fcntl.h>
  300. #include <pthread.h>
  301. #include <signal.h>
  302. #include <sys/stat.h>
  303. #include <unistd.h>
  304. #if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
  305. #include <execinfo.h>
  306. #endif
  307. #endif // defined(BACKWARD_SYSTEM_DARWIN)
  308. #if defined(BACKWARD_SYSTEM_WINDOWS)
  309. #include <condition_variable>
  310. #include <mutex>
  311. #include <thread>
  312. #include <basetsd.h>
  313. typedef SSIZE_T ssize_t;
  314. #define NOMINMAX
  315. #include <windows.h>
  316. #include <winnt.h>
  317. #include <psapi.h>
  318. #include <signal.h>
  319. #ifndef __clang__
  320. #undef NOINLINE
  321. #define NOINLINE __declspec(noinline)
  322. #endif
  323. #pragma comment(lib, "psapi.lib")
  324. #pragma comment(lib, "dbghelp.lib")
  325. // Comment / packing is from stackoverflow:
  326. // https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
  327. // Some versions of imagehlp.dll lack the proper packing directives themselves
  328. // so we need to do it.
  329. #pragma pack(push, before_imagehlp, 8)
  330. #include <imagehlp.h>
  331. #pragma pack(pop, before_imagehlp)
  332. // TODO maybe these should be undefined somewhere else?
  333. #undef BACKWARD_HAS_UNWIND
  334. #undef BACKWARD_HAS_BACKTRACE
  335. #if BACKWARD_HAS_PDB_SYMBOL == 1
  336. #else
  337. #undef BACKWARD_HAS_PDB_SYMBOL
  338. #define BACKWARD_HAS_PDB_SYMBOL 1
  339. #endif
  340. #endif
  341. #if BACKWARD_HAS_UNWIND == 1
  342. #include <unwind.h>
  343. // while gcc's unwind.h defines something like that:
  344. // extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *);
  345. // extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
  346. //
  347. // clang's unwind.h defines something like this:
  348. // uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context);
  349. //
  350. // Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we
  351. // cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr
  352. // anyway.
  353. //
  354. // Luckily we can play on the fact that the guard macros have a different name:
  355. #ifdef __CLANG_UNWIND_H
  356. // In fact, this function still comes from libgcc (on my different linux boxes,
  357. // clang links against libgcc).
  358. #include <inttypes.h>
  359. extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *, int *);
  360. #endif
  361. #endif // BACKWARD_HAS_UNWIND == 1
  362. #if BACKWARD_HAS_LIBUNWIND == 1
  363. #define UNW_LOCAL_ONLY
  364. #include <libunwind.h>
  365. #endif // BACKWARD_HAS_LIBUNWIND == 1
  366. #ifdef BACKWARD_ATLEAST_CXX11
  367. #include <unordered_map>
  368. #include <utility> // for std::swap
  369. namespace backward {
  370. namespace details {
  371. template <typename K, typename V> struct hashtable {
  372. typedef std::unordered_map<K, V> type;
  373. };
  374. using std::move;
  375. } // namespace details
  376. } // namespace backward
  377. #else // NOT BACKWARD_ATLEAST_CXX11
  378. #define nullptr NULL
  379. #define override
  380. #include <map>
  381. namespace backward {
  382. namespace details {
  383. template <typename K, typename V> struct hashtable {
  384. typedef std::map<K, V> type;
  385. };
  386. template <typename T> const T &move(const T &v) { return v; }
  387. template <typename T> T &move(T &v) { return v; }
  388. } // namespace details
  389. } // namespace backward
  390. #endif // BACKWARD_ATLEAST_CXX11
  391. namespace backward {
  392. namespace details {
  393. #if defined(BACKWARD_SYSTEM_WINDOWS)
  394. const char kBackwardPathDelimiter[] = ";";
  395. #else
  396. const char kBackwardPathDelimiter[] = ":";
  397. #endif
  398. } // namespace details
  399. } // namespace backward
  400. namespace backward {
  401. namespace system_tag {
  402. struct linux_tag; // seems that I cannot call that "linux" because the name
  403. // is already defined... so I am adding _tag everywhere.
  404. struct darwin_tag;
  405. struct windows_tag;
  406. struct unknown_tag;
  407. #if defined(BACKWARD_SYSTEM_LINUX)
  408. typedef linux_tag current_tag;
  409. #elif defined(BACKWARD_SYSTEM_DARWIN)
  410. typedef darwin_tag current_tag;
  411. #elif defined(BACKWARD_SYSTEM_WINDOWS)
  412. typedef windows_tag current_tag;
  413. #elif defined(BACKWARD_SYSTEM_UNKNOWN)
  414. typedef unknown_tag current_tag;
  415. #else
  416. #error "May I please get my system defines?"
  417. #endif
  418. } // namespace system_tag
  419. namespace trace_resolver_tag {
  420. #if defined(BACKWARD_SYSTEM_LINUX)
  421. struct libdw;
  422. struct libbfd;
  423. struct libdwarf;
  424. struct backtrace_symbol;
  425. #if BACKWARD_HAS_DW == 1
  426. typedef libdw current;
  427. #elif BACKWARD_HAS_BFD == 1
  428. typedef libbfd current;
  429. #elif BACKWARD_HAS_DWARF == 1
  430. typedef libdwarf current;
  431. #elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  432. typedef backtrace_symbol current;
  433. #else
  434. #error "You shall not pass, until you know what you want."
  435. #endif
  436. #elif defined(BACKWARD_SYSTEM_DARWIN)
  437. struct backtrace_symbol;
  438. #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  439. typedef backtrace_symbol current;
  440. #else
  441. #error "You shall not pass, until you know what you want."
  442. #endif
  443. #elif defined(BACKWARD_SYSTEM_WINDOWS)
  444. struct pdb_symbol;
  445. #if BACKWARD_HAS_PDB_SYMBOL == 1
  446. typedef pdb_symbol current;
  447. #else
  448. #error "You shall not pass, until you know what you want."
  449. #endif
  450. #endif
  451. } // namespace trace_resolver_tag
  452. namespace details {
  453. template <typename T> struct rm_ptr { typedef T type; };
  454. template <typename T> struct rm_ptr<T *> { typedef T type; };
  455. template <typename T> struct rm_ptr<const T *> { typedef const T type; };
  456. template <typename R, typename T, R (*F)(T)> struct deleter {
  457. template <typename U> void operator()(U &ptr) const { (*F)(ptr); }
  458. };
  459. template <typename T> struct default_delete {
  460. void operator()(T &ptr) const { delete ptr; }
  461. };
  462. template <typename T, typename Deleter = deleter<void, void *, &::free>>
  463. class handle {
  464. struct dummy;
  465. T _val;
  466. bool _empty;
  467. #ifdef BACKWARD_ATLEAST_CXX11
  468. handle(const handle &) = delete;
  469. handle &operator=(const handle &) = delete;
  470. #endif
  471. public:
  472. ~handle() {
  473. if (!_empty) {
  474. Deleter()(_val);
  475. }
  476. }
  477. explicit handle() : _val(), _empty(true) {}
  478. explicit handle(T val) : _val(val), _empty(false) {
  479. if (!_val)
  480. _empty = true;
  481. }
  482. #ifdef BACKWARD_ATLEAST_CXX11
  483. handle(handle &&from) : _empty(true) { swap(from); }
  484. handle &operator=(handle &&from) {
  485. swap(from);
  486. return *this;
  487. }
  488. #else
  489. explicit handle(const handle &from) : _empty(true) {
  490. // some sort of poor man's move semantic.
  491. swap(const_cast<handle &>(from));
  492. }
  493. handle &operator=(const handle &from) {
  494. // some sort of poor man's move semantic.
  495. swap(const_cast<handle &>(from));
  496. return *this;
  497. }
  498. #endif
  499. void reset(T new_val) {
  500. handle tmp(new_val);
  501. swap(tmp);
  502. }
  503. void update(T new_val) {
  504. _val = new_val;
  505. _empty = !static_cast<bool>(new_val);
  506. }
  507. operator const dummy *() const {
  508. if (_empty) {
  509. return nullptr;
  510. }
  511. return reinterpret_cast<const dummy *>(_val);
  512. }
  513. T get() { return _val; }
  514. T release() {
  515. _empty = true;
  516. return _val;
  517. }
  518. void swap(handle &b) {
  519. using std::swap;
  520. swap(b._val, _val); // can throw, we are safe here.
  521. swap(b._empty, _empty); // should not throw: if you cannot swap two
  522. // bools without throwing... It's a lost cause anyway!
  523. }
  524. T &operator->() { return _val; }
  525. const T &operator->() const { return _val; }
  526. typedef typename rm_ptr<T>::type &ref_t;
  527. typedef const typename rm_ptr<T>::type &const_ref_t;
  528. ref_t operator*() { return *_val; }
  529. const_ref_t operator*() const { return *_val; }
  530. ref_t operator[](size_t idx) { return _val[idx]; }
  531. // Watch out, we've got a badass over here
  532. T *operator&() {
  533. _empty = false;
  534. return &_val;
  535. }
  536. };
  537. // Default demangler implementation (do nothing).
  538. template <typename TAG> struct demangler_impl {
  539. static std::string demangle(const char *funcname) { return funcname; }
  540. };
  541. #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
  542. template <> struct demangler_impl<system_tag::current_tag> {
  543. demangler_impl() : _demangle_buffer_length(0) {}
  544. std::string demangle(const char *funcname) {
  545. using namespace details;
  546. char *result = abi::__cxa_demangle(funcname, _demangle_buffer.get(),
  547. &_demangle_buffer_length, nullptr);
  548. if (result) {
  549. _demangle_buffer.update(result);
  550. return result;
  551. }
  552. return funcname;
  553. }
  554. private:
  555. details::handle<char *> _demangle_buffer;
  556. size_t _demangle_buffer_length;
  557. };
  558. #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
  559. struct demangler : public demangler_impl<system_tag::current_tag> {};
  560. // Split a string on the platform's PATH delimiter. Example: if delimiter
  561. // is ":" then:
  562. // "" --> []
  563. // ":" --> ["",""]
  564. // "::" --> ["","",""]
  565. // "/a/b/c" --> ["/a/b/c"]
  566. // "/a/b/c:/d/e/f" --> ["/a/b/c","/d/e/f"]
  567. // etc.
  568. inline std::vector<std::string> split_source_prefixes(const std::string &s) {
  569. std::vector<std::string> out;
  570. size_t last = 0;
  571. size_t next = 0;
  572. size_t delimiter_size = sizeof(kBackwardPathDelimiter) - 1;
  573. while ((next = s.find(kBackwardPathDelimiter, last)) != std::string::npos) {
  574. out.push_back(s.substr(last, next - last));
  575. last = next + delimiter_size;
  576. }
  577. if (last <= s.length()) {
  578. out.push_back(s.substr(last));
  579. }
  580. return out;
  581. }
  582. } // namespace details
  583. /*************** A TRACE ***************/
  584. struct Trace {
  585. void *addr;
  586. size_t idx;
  587. Trace() : addr(nullptr), idx(0) {}
  588. explicit Trace(void *_addr, size_t _idx) : addr(_addr), idx(_idx) {}
  589. };
  590. struct ResolvedTrace : public Trace {
  591. struct SourceLoc {
  592. std::string function;
  593. std::string filename;
  594. unsigned line;
  595. unsigned col;
  596. SourceLoc() : line(0), col(0) {}
  597. bool operator==(const SourceLoc &b) const {
  598. return function == b.function && filename == b.filename &&
  599. line == b.line && col == b.col;
  600. }
  601. bool operator!=(const SourceLoc &b) const { return !(*this == b); }
  602. };
  603. // In which binary object this trace is located.
  604. std::string object_filename;
  605. // The function in the object that contain the trace. This is not the same
  606. // as source.function which can be an function inlined in object_function.
  607. std::string object_function;
  608. // The source location of this trace. It is possible for filename to be
  609. // empty and for line/col to be invalid (value 0) if this information
  610. // couldn't be deduced, for example if there is no debug information in the
  611. // binary object.
  612. SourceLoc source;
  613. // An optionals list of "inliners". All the successive sources location
  614. // from where the source location of the trace (the attribute right above)
  615. // is inlined. It is especially useful when you compiled with optimization.
  616. typedef std::vector<SourceLoc> source_locs_t;
  617. source_locs_t inliners;
  618. ResolvedTrace() : Trace() {}
  619. ResolvedTrace(const Trace &mini_trace) : Trace(mini_trace) {}
  620. };
  621. /*************** STACK TRACE ***************/
  622. // default implemention.
  623. template <typename TAG> class StackTraceImpl {
  624. public:
  625. size_t size() const { return 0; }
  626. Trace operator[](size_t) const { return Trace(); }
  627. size_t load_here(size_t = 0) { return 0; }
  628. size_t load_from(void *, size_t = 0, void * = nullptr, void * = nullptr) {
  629. return 0;
  630. }
  631. size_t thread_id() const { return 0; }
  632. void skip_n_firsts(size_t) {}
  633. };
  634. class StackTraceImplBase {
  635. public:
  636. StackTraceImplBase()
  637. : _thread_id(0), _skip(0), _context(nullptr), _error_addr(nullptr) {}
  638. size_t thread_id() const { return _thread_id; }
  639. void skip_n_firsts(size_t n) { _skip = n; }
  640. protected:
  641. void load_thread_info() {
  642. #ifdef BACKWARD_SYSTEM_LINUX
  643. #ifndef __ANDROID__
  644. _thread_id = static_cast<size_t>(syscall(SYS_gettid));
  645. #else
  646. _thread_id = static_cast<size_t>(gettid());
  647. #endif
  648. if (_thread_id == static_cast<size_t>(getpid())) {
  649. // If the thread is the main one, let's hide that.
  650. // I like to keep little secret sometimes.
  651. _thread_id = 0;
  652. }
  653. #elif defined(BACKWARD_SYSTEM_DARWIN)
  654. _thread_id = reinterpret_cast<size_t>(pthread_self());
  655. if (pthread_main_np() == 1) {
  656. // If the thread is the main one, let's hide that.
  657. _thread_id = 0;
  658. }
  659. #endif
  660. }
  661. void set_context(void *context) { _context = context; }
  662. void *context() const { return _context; }
  663. void set_error_addr(void *error_addr) { _error_addr = error_addr; }
  664. void *error_addr() const { return _error_addr; }
  665. size_t skip_n_firsts() const { return _skip; }
  666. private:
  667. size_t _thread_id;
  668. size_t _skip;
  669. void *_context;
  670. void *_error_addr;
  671. };
  672. class StackTraceImplHolder : public StackTraceImplBase {
  673. public:
  674. size_t size() const {
  675. return (_stacktrace.size() >= skip_n_firsts())
  676. ? _stacktrace.size() - skip_n_firsts()
  677. : 0;
  678. }
  679. Trace operator[](size_t idx) const {
  680. if (idx >= size()) {
  681. return Trace();
  682. }
  683. return Trace(_stacktrace[idx + skip_n_firsts()], idx);
  684. }
  685. void *const *begin() const {
  686. if (size()) {
  687. return &_stacktrace[skip_n_firsts()];
  688. }
  689. return nullptr;
  690. }
  691. protected:
  692. std::vector<void *> _stacktrace;
  693. };
  694. #if BACKWARD_HAS_UNWIND == 1
  695. namespace details {
  696. template <typename F> class Unwinder {
  697. public:
  698. size_t operator()(F &f, size_t depth) {
  699. _f = &f;
  700. _index = -1;
  701. _depth = depth;
  702. _Unwind_Backtrace(&this->backtrace_trampoline, this);
  703. return static_cast<size_t>(_index);
  704. }
  705. private:
  706. F *_f;
  707. ssize_t _index;
  708. size_t _depth;
  709. static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx,
  710. void *self) {
  711. return (static_cast<Unwinder *>(self))->backtrace(ctx);
  712. }
  713. _Unwind_Reason_Code backtrace(_Unwind_Context *ctx) {
  714. if (_index >= 0 && static_cast<size_t>(_index) >= _depth)
  715. return _URC_END_OF_STACK;
  716. int ip_before_instruction = 0;
  717. uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
  718. if (!ip_before_instruction) {
  719. // calculating 0-1 for unsigned, looks like a possible bug to sanitiziers,
  720. // so let's do it explicitly:
  721. if (ip == 0) {
  722. ip = std::numeric_limits<uintptr_t>::max(); // set it to 0xffff... (as
  723. // from casting 0-1)
  724. } else {
  725. ip -= 1; // else just normally decrement it (no overflow/underflow will
  726. // happen)
  727. }
  728. }
  729. if (_index >= 0) { // ignore first frame.
  730. (*_f)(static_cast<size_t>(_index), reinterpret_cast<void *>(ip));
  731. }
  732. _index += 1;
  733. return _URC_NO_REASON;
  734. }
  735. };
  736. template <typename F> size_t unwind(F f, size_t depth) {
  737. Unwinder<F> unwinder;
  738. return unwinder(f, depth);
  739. }
  740. } // namespace details
  741. template <>
  742. class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
  743. public:
  744. NOINLINE
  745. size_t load_here(size_t depth = 32, void *context = nullptr,
  746. void *error_addr = nullptr) {
  747. load_thread_info();
  748. set_context(context);
  749. set_error_addr(error_addr);
  750. if (depth == 0) {
  751. return 0;
  752. }
  753. _stacktrace.resize(depth);
  754. size_t trace_cnt = details::unwind(callback(*this), depth);
  755. _stacktrace.resize(trace_cnt);
  756. skip_n_firsts(0);
  757. return size();
  758. }
  759. size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
  760. void *error_addr = nullptr) {
  761. load_here(depth + 8, context, error_addr);
  762. for (size_t i = 0; i < _stacktrace.size(); ++i) {
  763. if (_stacktrace[i] == addr) {
  764. skip_n_firsts(i);
  765. break;
  766. }
  767. }
  768. _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
  769. return size();
  770. }
  771. private:
  772. struct callback {
  773. StackTraceImpl &self;
  774. callback(StackTraceImpl &_self) : self(_self) {}
  775. void operator()(size_t idx, void *addr) { self._stacktrace[idx] = addr; }
  776. };
  777. };
  778. #elif BACKWARD_HAS_LIBUNWIND == 1
  779. template <>
  780. class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
  781. public:
  782. __attribute__((noinline)) size_t load_here(size_t depth = 32,
  783. void *_context = nullptr,
  784. void *_error_addr = nullptr) {
  785. set_context(_context);
  786. set_error_addr(_error_addr);
  787. load_thread_info();
  788. if (depth == 0) {
  789. return 0;
  790. }
  791. _stacktrace.resize(depth + 1);
  792. int result = 0;
  793. unw_context_t ctx;
  794. size_t index = 0;
  795. // Add the tail call. If the Instruction Pointer is the crash address it
  796. // means we got a bad function pointer dereference, so we "unwind" the
  797. // bad pointer manually by using the return address pointed to by the
  798. // Stack Pointer as the Instruction Pointer and letting libunwind do
  799. // the rest
  800. if (context()) {
  801. ucontext_t *uctx = reinterpret_cast<ucontext_t *>(context());
  802. #ifdef REG_RIP // x86_64
  803. if (uctx->uc_mcontext.gregs[REG_RIP] ==
  804. reinterpret_cast<greg_t>(error_addr())) {
  805. uctx->uc_mcontext.gregs[REG_RIP] =
  806. *reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_RSP]);
  807. }
  808. _stacktrace[index] =
  809. reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
  810. ++index;
  811. ctx = *reinterpret_cast<unw_context_t *>(uctx);
  812. #elif defined(REG_EIP) // x86_32
  813. if (uctx->uc_mcontext.gregs[REG_EIP] ==
  814. reinterpret_cast<greg_t>(error_addr())) {
  815. uctx->uc_mcontext.gregs[REG_EIP] =
  816. *reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_ESP]);
  817. }
  818. _stacktrace[index] =
  819. reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
  820. ++index;
  821. ctx = *reinterpret_cast<unw_context_t *>(uctx);
  822. #elif defined(__arm__)
  823. // libunwind uses its own context type for ARM unwinding.
  824. // Copy the registers from the signal handler's context so we can
  825. // unwind
  826. unw_getcontext(&ctx);
  827. ctx.regs[UNW_ARM_R0] = uctx->uc_mcontext.arm_r0;
  828. ctx.regs[UNW_ARM_R1] = uctx->uc_mcontext.arm_r1;
  829. ctx.regs[UNW_ARM_R2] = uctx->uc_mcontext.arm_r2;
  830. ctx.regs[UNW_ARM_R3] = uctx->uc_mcontext.arm_r3;
  831. ctx.regs[UNW_ARM_R4] = uctx->uc_mcontext.arm_r4;
  832. ctx.regs[UNW_ARM_R5] = uctx->uc_mcontext.arm_r5;
  833. ctx.regs[UNW_ARM_R6] = uctx->uc_mcontext.arm_r6;
  834. ctx.regs[UNW_ARM_R7] = uctx->uc_mcontext.arm_r7;
  835. ctx.regs[UNW_ARM_R8] = uctx->uc_mcontext.arm_r8;
  836. ctx.regs[UNW_ARM_R9] = uctx->uc_mcontext.arm_r9;
  837. ctx.regs[UNW_ARM_R10] = uctx->uc_mcontext.arm_r10;
  838. ctx.regs[UNW_ARM_R11] = uctx->uc_mcontext.arm_fp;
  839. ctx.regs[UNW_ARM_R12] = uctx->uc_mcontext.arm_ip;
  840. ctx.regs[UNW_ARM_R13] = uctx->uc_mcontext.arm_sp;
  841. ctx.regs[UNW_ARM_R14] = uctx->uc_mcontext.arm_lr;
  842. ctx.regs[UNW_ARM_R15] = uctx->uc_mcontext.arm_pc;
  843. // If we have crashed in the PC use the LR instead, as this was
  844. // a bad function dereference
  845. if (reinterpret_cast<unsigned long>(error_addr()) ==
  846. uctx->uc_mcontext.arm_pc) {
  847. ctx.regs[UNW_ARM_R15] =
  848. uctx->uc_mcontext.arm_lr - sizeof(unsigned long);
  849. }
  850. _stacktrace[index] = reinterpret_cast<void *>(ctx.regs[UNW_ARM_R15]);
  851. ++index;
  852. #elif defined(__APPLE__) && defined(__x86_64__)
  853. unw_getcontext(&ctx);
  854. // OS X's implementation of libunwind uses its own context object
  855. // so we need to convert the passed context to libunwind's format
  856. // (information about the data layout taken from unw_getcontext.s
  857. // in Apple's libunwind source
  858. ctx.data[0] = uctx->uc_mcontext->__ss.__rax;
  859. ctx.data[1] = uctx->uc_mcontext->__ss.__rbx;
  860. ctx.data[2] = uctx->uc_mcontext->__ss.__rcx;
  861. ctx.data[3] = uctx->uc_mcontext->__ss.__rdx;
  862. ctx.data[4] = uctx->uc_mcontext->__ss.__rdi;
  863. ctx.data[5] = uctx->uc_mcontext->__ss.__rsi;
  864. ctx.data[6] = uctx->uc_mcontext->__ss.__rbp;
  865. ctx.data[7] = uctx->uc_mcontext->__ss.__rsp;
  866. ctx.data[8] = uctx->uc_mcontext->__ss.__r8;
  867. ctx.data[9] = uctx->uc_mcontext->__ss.__r9;
  868. ctx.data[10] = uctx->uc_mcontext->__ss.__r10;
  869. ctx.data[11] = uctx->uc_mcontext->__ss.__r11;
  870. ctx.data[12] = uctx->uc_mcontext->__ss.__r12;
  871. ctx.data[13] = uctx->uc_mcontext->__ss.__r13;
  872. ctx.data[14] = uctx->uc_mcontext->__ss.__r14;
  873. ctx.data[15] = uctx->uc_mcontext->__ss.__r15;
  874. ctx.data[16] = uctx->uc_mcontext->__ss.__rip;
  875. // If the IP is the same as the crash address we have a bad function
  876. // dereference The caller's address is pointed to by %rsp, so we
  877. // dereference that value and set it to be the next frame's IP.
  878. if (uctx->uc_mcontext->__ss.__rip ==
  879. reinterpret_cast<__uint64_t>(error_addr())) {
  880. ctx.data[16] =
  881. *reinterpret_cast<__uint64_t *>(uctx->uc_mcontext->__ss.__rsp);
  882. }
  883. _stacktrace[index] = reinterpret_cast<void *>(ctx.data[16]);
  884. ++index;
  885. #elif defined(__APPLE__)
  886. unw_getcontext(&ctx)
  887. // TODO: Convert the ucontext_t to libunwind's unw_context_t like
  888. // we do in 64 bits
  889. if (ctx.uc_mcontext->__ss.__eip ==
  890. reinterpret_cast<greg_t>(error_addr())) {
  891. ctx.uc_mcontext->__ss.__eip = ctx.uc_mcontext->__ss.__esp;
  892. }
  893. _stacktrace[index] =
  894. reinterpret_cast<void *>(ctx.uc_mcontext->__ss.__eip);
  895. ++index;
  896. #endif
  897. }
  898. unw_cursor_t cursor;
  899. if (context()) {
  900. #if defined(UNW_INIT_SIGNAL_FRAME)
  901. result = unw_init_local2(&cursor, &ctx, UNW_INIT_SIGNAL_FRAME);
  902. #else
  903. result = unw_init_local(&cursor, &ctx);
  904. #endif
  905. } else {
  906. unw_getcontext(&ctx);
  907. ;
  908. result = unw_init_local(&cursor, &ctx);
  909. }
  910. if (result != 0)
  911. return 1;
  912. unw_word_t ip = 0;
  913. while (index <= depth && unw_step(&cursor) > 0) {
  914. result = unw_get_reg(&cursor, UNW_REG_IP, &ip);
  915. if (result == 0) {
  916. _stacktrace[index] = reinterpret_cast<void *>(--ip);
  917. ++index;
  918. }
  919. }
  920. --index;
  921. _stacktrace.resize(index + 1);
  922. skip_n_firsts(0);
  923. return size();
  924. }
  925. size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
  926. void *error_addr = nullptr) {
  927. load_here(depth + 8, context, error_addr);
  928. for (size_t i = 0; i < _stacktrace.size(); ++i) {
  929. if (_stacktrace[i] == addr) {
  930. skip_n_firsts(i);
  931. _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i]);
  932. break;
  933. }
  934. }
  935. _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
  936. return size();
  937. }
  938. };
  939. #elif defined(BACKWARD_HAS_BACKTRACE)
  940. template <>
  941. class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
  942. public:
  943. NOINLINE
  944. size_t load_here(size_t depth = 32, void *context = nullptr,
  945. void *error_addr = nullptr) {
  946. set_context(context);
  947. set_error_addr(error_addr);
  948. load_thread_info();
  949. if (depth == 0) {
  950. return 0;
  951. }
  952. _stacktrace.resize(depth + 1);
  953. size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
  954. _stacktrace.resize(trace_cnt);
  955. skip_n_firsts(1);
  956. return size();
  957. }
  958. size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
  959. void *error_addr = nullptr) {
  960. load_here(depth + 8, contxt, error_addr);
  961. for (size_t i = 0; i < _stacktrace.size(); ++i) {
  962. if (_stacktrace[i] == addr) {
  963. skip_n_firsts(i);
  964. _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i] + 1);
  965. break;
  966. }
  967. }
  968. _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
  969. return size();
  970. }
  971. };
  972. #elif defined(BACKWARD_SYSTEM_WINDOWS)
  973. template <>
  974. class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
  975. public:
  976. // We have to load the machine type from the image info
  977. // So we first initialize the resolver, and it tells us this info
  978. void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; }
  979. void set_context(CONTEXT *ctx) { ctx_ = ctx; }
  980. void set_thread_handle(HANDLE handle) { thd_ = handle; }
  981. NOINLINE
  982. size_t load_here(size_t depth = 32, void *context = nullptr,
  983. void *error_addr = nullptr) {
  984. set_context(static_cast<CONTEXT*>(context));
  985. set_error_addr(error_addr);
  986. CONTEXT localCtx; // used when no context is provided
  987. if (depth == 0) {
  988. return 0;
  989. }
  990. if (!ctx_) {
  991. ctx_ = &localCtx;
  992. RtlCaptureContext(ctx_);
  993. }
  994. if (!thd_) {
  995. thd_ = GetCurrentThread();
  996. }
  997. HANDLE process = GetCurrentProcess();
  998. STACKFRAME64 s;
  999. memset(&s, 0, sizeof(STACKFRAME64));
  1000. // TODO: 32 bit context capture
  1001. s.AddrStack.Mode = AddrModeFlat;
  1002. s.AddrFrame.Mode = AddrModeFlat;
  1003. s.AddrPC.Mode = AddrModeFlat;
  1004. #ifdef _M_X64
  1005. s.AddrPC.Offset = ctx_->Rip;
  1006. s.AddrStack.Offset = ctx_->Rsp;
  1007. s.AddrFrame.Offset = ctx_->Rbp;
  1008. #else
  1009. s.AddrPC.Offset = ctx_->Eip;
  1010. s.AddrStack.Offset = ctx_->Esp;
  1011. s.AddrFrame.Offset = ctx_->Ebp;
  1012. #endif
  1013. if (!machine_type_) {
  1014. #ifdef _M_X64
  1015. machine_type_ = IMAGE_FILE_MACHINE_AMD64;
  1016. #else
  1017. machine_type_ = IMAGE_FILE_MACHINE_I386;
  1018. #endif
  1019. }
  1020. for (;;) {
  1021. // NOTE: this only works if PDBs are already loaded!
  1022. SetLastError(0);
  1023. if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL,
  1024. SymFunctionTableAccess64, SymGetModuleBase64, NULL))
  1025. break;
  1026. if (s.AddrReturn.Offset == 0)
  1027. break;
  1028. _stacktrace.push_back(reinterpret_cast<void *>(s.AddrPC.Offset));
  1029. if (size() >= depth)
  1030. break;
  1031. }
  1032. return size();
  1033. }
  1034. size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
  1035. void *error_addr = nullptr) {
  1036. load_here(depth + 8, context, error_addr);
  1037. for (size_t i = 0; i < _stacktrace.size(); ++i) {
  1038. if (_stacktrace[i] == addr) {
  1039. skip_n_firsts(i);
  1040. break;
  1041. }
  1042. }
  1043. _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
  1044. return size();
  1045. }
  1046. private:
  1047. DWORD machine_type_ = 0;
  1048. HANDLE thd_ = 0;
  1049. CONTEXT *ctx_ = nullptr;
  1050. };
  1051. #endif
  1052. class StackTrace : public StackTraceImpl<system_tag::current_tag> {};
  1053. /*************** TRACE RESOLVER ***************/
  1054. template <typename TAG> class TraceResolverImpl;
  1055. #ifdef BACKWARD_SYSTEM_UNKNOWN
  1056. template <> class TraceResolverImpl<system_tag::unknown_tag> {
  1057. public:
  1058. template <class ST> void load_stacktrace(ST &) {}
  1059. ResolvedTrace resolve(ResolvedTrace t) { return t; }
  1060. };
  1061. #endif
  1062. class TraceResolverImplBase {
  1063. protected:
  1064. std::string demangle(const char *funcname) {
  1065. return _demangler.demangle(funcname);
  1066. }
  1067. private:
  1068. details::demangler _demangler;
  1069. };
  1070. #ifdef BACKWARD_SYSTEM_LINUX
  1071. class TraceResolverLinuxBase : public TraceResolverImplBase {
  1072. public:
  1073. TraceResolverLinuxBase()
  1074. : argv0_(get_argv0()), exec_path_(read_symlink("/proc/self/exe")) {}
  1075. std::string resolve_exec_path(Dl_info &symbol_info) const {
  1076. // mutates symbol_info.dli_fname to be filename to open and returns filename
  1077. // to display
  1078. if (symbol_info.dli_fname == argv0_) {
  1079. // dladdr returns argv[0] in dli_fname for symbols contained in
  1080. // the main executable, which is not a valid path if the
  1081. // executable was found by a search of the PATH environment
  1082. // variable; In that case, we actually open /proc/self/exe, which
  1083. // is always the actual executable (even if it was deleted/replaced!)
  1084. // but display the path that /proc/self/exe links to.
  1085. symbol_info.dli_fname = "/proc/self/exe";
  1086. return exec_path_;
  1087. } else {
  1088. return symbol_info.dli_fname;
  1089. }
  1090. }
  1091. private:
  1092. std::string argv0_;
  1093. std::string exec_path_;
  1094. static std::string get_argv0() {
  1095. std::string argv0;
  1096. std::ifstream ifs("/proc/self/cmdline");
  1097. std::getline(ifs, argv0, '\0');
  1098. return argv0;
  1099. }
  1100. static std::string read_symlink(std::string const &symlink_path) {
  1101. std::string path;
  1102. path.resize(100);
  1103. while (true) {
  1104. ssize_t len =
  1105. ::readlink(symlink_path.c_str(), &*path.begin(), path.size());
  1106. if (len < 0) {
  1107. return "";
  1108. }
  1109. if (static_cast<size_t>(len) == path.size()) {
  1110. path.resize(path.size() * 2);
  1111. } else {
  1112. path.resize(static_cast<std::string::size_type>(len));
  1113. break;
  1114. }
  1115. }
  1116. return path;
  1117. }
  1118. };
  1119. template <typename STACKTRACE_TAG> class TraceResolverLinuxImpl;
  1120. #if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  1121. template <>
  1122. class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>
  1123. : public TraceResolverLinuxBase {
  1124. public:
  1125. template <class ST> void load_stacktrace(ST &st) {
  1126. using namespace details;
  1127. if (st.size() == 0) {
  1128. return;
  1129. }
  1130. _symbols.reset(backtrace_symbols(st.begin(), (int)st.size()));
  1131. }
  1132. ResolvedTrace resolve(ResolvedTrace trace) {
  1133. char *filename = _symbols[trace.idx];
  1134. char *funcname = filename;
  1135. while (*funcname && *funcname != '(') {
  1136. funcname += 1;
  1137. }
  1138. trace.object_filename.assign(filename,
  1139. funcname); // ok even if funcname is the ending
  1140. // \0 (then we assign entire string)
  1141. if (*funcname) { // if it's not end of string (e.g. from last frame ip==0)
  1142. funcname += 1;
  1143. char *funcname_end = funcname;
  1144. while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') {
  1145. funcname_end += 1;
  1146. }
  1147. *funcname_end = '\0';
  1148. trace.object_function = this->demangle(funcname);
  1149. trace.source.function = trace.object_function; // we cannot do better.
  1150. }
  1151. return trace;
  1152. }
  1153. private:
  1154. details::handle<char **> _symbols;
  1155. };
  1156. #endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
  1157. #if BACKWARD_HAS_BFD == 1
  1158. template <>
  1159. class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>
  1160. : public TraceResolverLinuxBase {
  1161. public:
  1162. TraceResolverLinuxImpl() : _bfd_loaded(false) {}
  1163. template <class ST> void load_stacktrace(ST &) {}
  1164. ResolvedTrace resolve(ResolvedTrace trace) {
  1165. Dl_info symbol_info;
  1166. // trace.addr is a virtual address in memory pointing to some code.
  1167. // Let's try to find from which loaded object it comes from.
  1168. // The loaded object can be yourself btw.
  1169. if (!dladdr(trace.addr, &symbol_info)) {
  1170. return trace; // dat broken trace...
  1171. }
  1172. // Now we get in symbol_info:
  1173. // .dli_fname:
  1174. // pathname of the shared object that contains the address.
  1175. // .dli_fbase:
  1176. // where the object is loaded in memory.
  1177. // .dli_sname:
  1178. // the name of the nearest symbol to trace.addr, we expect a
  1179. // function name.
  1180. // .dli_saddr:
  1181. // the exact address corresponding to .dli_sname.
  1182. if (symbol_info.dli_sname) {
  1183. trace.object_function = demangle(symbol_info.dli_sname);
  1184. }
  1185. if (!symbol_info.dli_fname) {
  1186. return trace;
  1187. }
  1188. trace.object_filename = resolve_exec_path(symbol_info);
  1189. bfd_fileobject &fobj = load_object_with_bfd(symbol_info.dli_fname);
  1190. if (!fobj.handle) {
  1191. return trace; // sad, we couldn't load the object :(
  1192. }
  1193. find_sym_result *details_selected; // to be filled.
  1194. // trace.addr is the next instruction to be executed after returning
  1195. // from the nested stack frame. In C++ this usually relate to the next
  1196. // statement right after the function call that leaded to a new stack
  1197. // frame. This is not usually what you want to see when printing out a
  1198. // stacktrace...
  1199. find_sym_result details_call_site =
  1200. find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
  1201. details_selected = &details_call_site;
  1202. #if BACKWARD_HAS_UNWIND == 0
  1203. // ...this is why we also try to resolve the symbol that is right
  1204. // before the return address. If we are lucky enough, we will get the
  1205. // line of the function that was called. But if the code is optimized,
  1206. // we might get something absolutely not related since the compiler
  1207. // can reschedule the return address with inline functions and
  1208. // tail-call optimisation (among other things that I don't even know
  1209. // or cannot even dream about with my tiny limited brain).
  1210. find_sym_result details_adjusted_call_site = find_symbol_details(
  1211. fobj, (void *)(uintptr_t(trace.addr) - 1), symbol_info.dli_fbase);
  1212. // In debug mode, we should always get the right thing(TM).
  1213. if (details_call_site.found && details_adjusted_call_site.found) {
  1214. // Ok, we assume that details_adjusted_call_site is a better estimation.
  1215. details_selected = &details_adjusted_call_site;
  1216. trace.addr = (void *)(uintptr_t(trace.addr) - 1);
  1217. }
  1218. if (details_selected == &details_call_site && details_call_site.found) {
  1219. // we have to re-resolve the symbol in order to reset some
  1220. // internal state in BFD... so we can call backtrace_inliners
  1221. // thereafter...
  1222. details_call_site =
  1223. find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
  1224. }
  1225. #endif // BACKWARD_HAS_UNWIND
  1226. if (details_selected->found) {
  1227. if (details_selected->filename) {
  1228. trace.source.filename = details_selected->filename;
  1229. }
  1230. trace.source.line = details_selected->line;
  1231. if (details_selected->funcname) {
  1232. // this time we get the name of the function where the code is
  1233. // located, instead of the function were the address is
  1234. // located. In short, if the code was inlined, we get the
  1235. // function correspoding to the code. Else we already got in
  1236. // trace.function.
  1237. trace.source.function = demangle(details_selected->funcname);
  1238. if (!symbol_info.dli_sname) {
  1239. // for the case dladdr failed to find the symbol name of
  1240. // the function, we might as well try to put something
  1241. // here.
  1242. trace.object_function = trace.source.function;
  1243. }
  1244. }
  1245. // Maybe the source of the trace got inlined inside the function
  1246. // (trace.source.function). Let's see if we can get all the inlined
  1247. // calls along the way up to the initial call site.
  1248. trace.inliners = backtrace_inliners(fobj, *details_selected);
  1249. #if 0
  1250. if (trace.inliners.size() == 0) {
  1251. // Maybe the trace was not inlined... or maybe it was and we
  1252. // are lacking the debug information. Let's try to make the
  1253. // world better and see if we can get the line number of the
  1254. // function (trace.source.function) now.
  1255. //
  1256. // We will get the location of where the function start (to be
  1257. // exact: the first instruction that really start the
  1258. // function), not where the name of the function is defined.
  1259. // This can be quite far away from the name of the function
  1260. // btw.
  1261. //
  1262. // If the source of the function is the same as the source of
  1263. // the trace, we cannot say if the trace was really inlined or
  1264. // not. However, if the filename of the source is different
  1265. // between the function and the trace... we can declare it as
  1266. // an inliner. This is not 100% accurate, but better than
  1267. // nothing.
  1268. if (symbol_info.dli_saddr) {
  1269. find_sym_result details = find_symbol_details(fobj,
  1270. symbol_info.dli_saddr,
  1271. symbol_info.dli_fbase);
  1272. if (details.found) {
  1273. ResolvedTrace::SourceLoc diy_inliner;
  1274. diy_inliner.line = details.line;
  1275. if (details.filename) {
  1276. diy_inliner.filename = details.filename;
  1277. }
  1278. if (details.funcname) {
  1279. diy_inliner.function = demangle(details.funcname);
  1280. } else {
  1281. diy_inliner.function = trace.source.function;
  1282. }
  1283. if (diy_inliner != trace.source) {
  1284. trace.inliners.push_back(diy_inliner);
  1285. }
  1286. }
  1287. }
  1288. }
  1289. #endif
  1290. }
  1291. return trace;
  1292. }
  1293. private:
  1294. bool _bfd_loaded;
  1295. typedef details::handle<bfd *,
  1296. details::deleter<bfd_boolean, bfd *, &bfd_close>>
  1297. bfd_handle_t;
  1298. typedef details::handle<asymbol **> bfd_symtab_t;
  1299. struct bfd_fileobject {
  1300. bfd_handle_t handle;
  1301. bfd_vma base_addr;
  1302. bfd_symtab_t symtab;
  1303. bfd_symtab_t dynamic_symtab;
  1304. };
  1305. typedef details::hashtable<std::string, bfd_fileobject>::type fobj_bfd_map_t;
  1306. fobj_bfd_map_t _fobj_bfd_map;
  1307. bfd_fileobject &load_object_with_bfd(const std::string &filename_object) {
  1308. using namespace details;
  1309. if (!_bfd_loaded) {
  1310. using namespace details;
  1311. bfd_init();
  1312. _bfd_loaded = true;
  1313. }
  1314. fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object);
  1315. if (it != _fobj_bfd_map.end()) {
  1316. return it->second;
  1317. }
  1318. // this new object is empty for now.
  1319. bfd_fileobject &r = _fobj_bfd_map[filename_object];
  1320. // we do the work temporary in this one;
  1321. bfd_handle_t bfd_handle;
  1322. int fd = open(filename_object.c_str(), O_RDONLY);
  1323. bfd_handle.reset(bfd_fdopenr(filename_object.c_str(), "default", fd));
  1324. if (!bfd_handle) {
  1325. close(fd);
  1326. return r;
  1327. }
  1328. if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
  1329. return r; // not an object? You lose.
  1330. }
  1331. if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
  1332. return r; // that's what happen when you forget to compile in debug.
  1333. }
  1334. ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get());
  1335. ssize_t dyn_symtab_storage_size =
  1336. bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
  1337. if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
  1338. return r; // weird, is the file is corrupted?
  1339. }
  1340. bfd_symtab_t symtab, dynamic_symtab;
  1341. ssize_t symcount = 0, dyn_symcount = 0;
  1342. if (symtab_storage_size > 0) {
  1343. symtab.reset(static_cast<bfd_symbol **>(
  1344. malloc(static_cast<size_t>(symtab_storage_size))));
  1345. symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get());
  1346. }
  1347. if (dyn_symtab_storage_size > 0) {
  1348. dynamic_symtab.reset(static_cast<bfd_symbol **>(
  1349. malloc(static_cast<size_t>(dyn_symtab_storage_size))));
  1350. dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(),
  1351. dynamic_symtab.get());
  1352. }
  1353. if (symcount <= 0 && dyn_symcount <= 0) {
  1354. return r; // damned, that's a stripped file that you got there!
  1355. }
  1356. r.handle = move(bfd_handle);
  1357. r.symtab = move(symtab);
  1358. r.dynamic_symtab = move(dynamic_symtab);
  1359. return r;
  1360. }
  1361. struct find_sym_result {
  1362. bool found;
  1363. const char *filename;
  1364. const char *funcname;
  1365. unsigned int line;
  1366. };
  1367. struct find_sym_context {
  1368. TraceResolverLinuxImpl *self;
  1369. bfd_fileobject *fobj;
  1370. void *addr;
  1371. void *base_addr;
  1372. find_sym_result result;
  1373. };
  1374. find_sym_result find_symbol_details(bfd_fileobject &fobj, void *addr,
  1375. void *base_addr) {
  1376. find_sym_context context;
  1377. context.self = this;
  1378. context.fobj = &fobj;
  1379. context.addr = addr;
  1380. context.base_addr = base_addr;
  1381. context.result.found = false;
  1382. bfd_map_over_sections(fobj.handle.get(), &find_in_section_trampoline,
  1383. static_cast<void *>(&context));
  1384. return context.result;
  1385. }
  1386. static void find_in_section_trampoline(bfd *, asection *section, void *data) {
  1387. find_sym_context *context = static_cast<find_sym_context *>(data);
  1388. context->self->find_in_section(
  1389. reinterpret_cast<bfd_vma>(context->addr),
  1390. reinterpret_cast<bfd_vma>(context->base_addr), *context->fobj, section,
  1391. context->result);
  1392. }
  1393. void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject &fobj,
  1394. asection *section, find_sym_result &result) {
  1395. if (result.found)
  1396. return;
  1397. #ifdef bfd_get_section_flags
  1398. if ((bfd_get_section_flags(fobj.handle.get(), section) & SEC_ALLOC) == 0)
  1399. #else
  1400. if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
  1401. #endif
  1402. return; // a debug section is never loaded automatically.
  1403. #ifdef bfd_get_section_vma
  1404. bfd_vma sec_addr = bfd_get_section_vma(fobj.handle.get(), section);
  1405. #else
  1406. bfd_vma sec_addr = bfd_section_vma(section);
  1407. #endif
  1408. #ifdef bfd_get_section_size
  1409. bfd_size_type size = bfd_get_section_size(section);
  1410. #else
  1411. bfd_size_type size = bfd_section_size(section);
  1412. #endif
  1413. // are we in the boundaries of the section?
  1414. if (addr < sec_addr || addr >= sec_addr + size) {
  1415. addr -= base_addr; // oups, a relocated object, lets try again...
  1416. if (addr < sec_addr || addr >= sec_addr + size) {
  1417. return;
  1418. }
  1419. }
  1420. #if defined(__clang__)
  1421. #pragma clang diagnostic push
  1422. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  1423. #endif
  1424. if (!result.found && fobj.symtab) {
  1425. result.found = bfd_find_nearest_line(
  1426. fobj.handle.get(), section, fobj.symtab.get(), addr - sec_addr,
  1427. &result.filename, &result.funcname, &result.line);
  1428. }
  1429. if (!result.found && fobj.dynamic_symtab) {
  1430. result.found = bfd_find_nearest_line(
  1431. fobj.handle.get(), section, fobj.dynamic_symtab.get(),
  1432. addr - sec_addr, &result.filename, &result.funcname, &result.line);
  1433. }
  1434. #if defined(__clang__)
  1435. #pragma clang diagnostic pop
  1436. #endif
  1437. }
  1438. ResolvedTrace::source_locs_t
  1439. backtrace_inliners(bfd_fileobject &fobj, find_sym_result previous_result) {
  1440. // This function can be called ONLY after a SUCCESSFUL call to
  1441. // find_symbol_details. The state is global to the bfd_handle.
  1442. ResolvedTrace::source_locs_t results;
  1443. while (previous_result.found) {
  1444. find_sym_result result;
  1445. result.found = bfd_find_inliner_info(fobj.handle.get(), &result.filename,
  1446. &result.funcname, &result.line);
  1447. if (result
  1448. .found) /* and not (
  1449. cstrings_eq(previous_result.filename,
  1450. result.filename) and
  1451. cstrings_eq(previous_result.funcname, result.funcname)
  1452. and result.line == previous_result.line
  1453. )) */
  1454. {
  1455. ResolvedTrace::SourceLoc src_loc;
  1456. src_loc.line = result.line;
  1457. if (result.filename) {
  1458. src_loc.filename = result.filename;
  1459. }
  1460. if (result.funcname) {
  1461. src_loc.function = demangle(result.funcname);
  1462. }
  1463. results.push_back(src_loc);
  1464. }
  1465. previous_result = result;
  1466. }
  1467. return results;
  1468. }
  1469. bool cstrings_eq(const char *a, const char *b) {
  1470. if (!a || !b) {
  1471. return false;
  1472. }
  1473. return strcmp(a, b) == 0;
  1474. }
  1475. };
  1476. #endif // BACKWARD_HAS_BFD == 1
  1477. #if BACKWARD_HAS_DW == 1
  1478. template <>
  1479. class TraceResolverLinuxImpl<trace_resolver_tag::libdw>
  1480. : public TraceResolverLinuxBase {
  1481. public:
  1482. TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {}
  1483. template <class ST> void load_stacktrace(ST &) {}
  1484. ResolvedTrace resolve(ResolvedTrace trace) {
  1485. using namespace details;
  1486. Dwarf_Addr trace_addr = (Dwarf_Addr)trace.addr;
  1487. if (!_dwfl_handle_initialized) {
  1488. // initialize dwfl...
  1489. _dwfl_cb.reset(new Dwfl_Callbacks);
  1490. _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
  1491. _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
  1492. _dwfl_cb->debuginfo_path = 0;
  1493. _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
  1494. _dwfl_handle_initialized = true;
  1495. if (!_dwfl_handle) {
  1496. return trace;
  1497. }
  1498. // ...from the current process.
  1499. dwfl_report_begin(_dwfl_handle.get());
  1500. int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid());
  1501. dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
  1502. if (r < 0) {
  1503. return trace;
  1504. }
  1505. }
  1506. if (!_dwfl_handle) {
  1507. return trace;
  1508. }
  1509. // find the module (binary object) that contains the trace's address.
  1510. // This is not using any debug information, but the addresses ranges of
  1511. // all the currently loaded binary object.
  1512. Dwfl_Module *mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
  1513. if (mod) {
  1514. // now that we found it, lets get the name of it, this will be the
  1515. // full path to the running binary or one of the loaded library.
  1516. const char *module_name = dwfl_module_info(mod, 0, 0, 0, 0, 0, 0, 0);
  1517. if (module_name) {
  1518. trace.object_filename = module_name;
  1519. }
  1520. // We also look after the name of the symbol, equal or before this
  1521. // address. This is found by walking the symtab. We should get the
  1522. // symbol corresponding to the function (mangled) containing the
  1523. // address. If the code corresponding to the address was inlined,
  1524. // this is the name of the out-most inliner function.
  1525. const char *sym_name = dwfl_module_addrname(mod, trace_addr);
  1526. if (sym_name) {
  1527. trace.object_function = demangle(sym_name);
  1528. }
  1529. }
  1530. // now let's get serious, and find out the source location (file and
  1531. // line number) of the address.
  1532. // This function will look in .debug_aranges for the address and map it
  1533. // to the location of the compilation unit DIE in .debug_info and
  1534. // return it.
  1535. Dwarf_Addr mod_bias = 0;
  1536. Dwarf_Die *cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias);
  1537. #if 1
  1538. if (!cudie) {
  1539. // Sadly clang does not generate the section .debug_aranges, thus
  1540. // dwfl_module_addrdie will fail early. Clang doesn't either set
  1541. // the lowpc/highpc/range info for every compilation unit.
  1542. //
  1543. // So in order to save the world:
  1544. // for every compilation unit, we will iterate over every single
  1545. // DIEs. Normally functions should have a lowpc/highpc/range, which
  1546. // we will use to infer the compilation unit.
  1547. // note that this is probably badly inefficient.
  1548. while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) {
  1549. Dwarf_Die die_mem;
  1550. Dwarf_Die *fundie =
  1551. find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem);
  1552. if (fundie) {
  1553. break;
  1554. }
  1555. }
  1556. }
  1557. #endif
  1558. //#define BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
  1559. #ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
  1560. if (!cudie) {
  1561. // If it's still not enough, lets dive deeper in the shit, and try
  1562. // to save the world again: for every compilation unit, we will
  1563. // load the corresponding .debug_line section, and see if we can
  1564. // find our address in it.
  1565. Dwarf_Addr cfi_bias;
  1566. Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias);
  1567. Dwarf_Addr bias;
  1568. while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) {
  1569. if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
  1570. // ...but if we get a match, it might be a false positive
  1571. // because our (address - bias) might as well be valid in a
  1572. // different compilation unit. So we throw our last card on
  1573. // the table and lookup for the address into the .eh_frame
  1574. // section.
  1575. handle<Dwarf_Frame *> frame;
  1576. dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
  1577. if (frame) {
  1578. break;
  1579. }
  1580. }
  1581. }
  1582. }
  1583. #endif
  1584. if (!cudie) {
  1585. return trace; // this time we lost the game :/
  1586. }
  1587. // Now that we have a compilation unit DIE, this function will be able
  1588. // to load the corresponding section in .debug_line (if not already
  1589. // loaded) and hopefully find the source location mapped to our
  1590. // address.
  1591. Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
  1592. if (srcloc) {
  1593. const char *srcfile = dwarf_linesrc(srcloc, 0, 0);
  1594. if (srcfile) {
  1595. trace.source.filename = srcfile;
  1596. }
  1597. int line = 0, col = 0;
  1598. dwarf_lineno(srcloc, &line);
  1599. dwarf_linecol(srcloc, &col);
  1600. trace.source.line = line;
  1601. trace.source.col = col;
  1602. }
  1603. deep_first_search_by_pc(cudie, trace_addr - mod_bias,
  1604. inliners_search_cb(trace));
  1605. if (trace.source.function.size() == 0) {
  1606. // fallback.
  1607. trace.source.function = trace.object_function;
  1608. }
  1609. return trace;
  1610. }
  1611. private:
  1612. typedef details::handle<Dwfl *, details::deleter<void, Dwfl *, &dwfl_end>>
  1613. dwfl_handle_t;
  1614. details::handle<Dwfl_Callbacks *, details::default_delete<Dwfl_Callbacks *>>
  1615. _dwfl_cb;
  1616. dwfl_handle_t _dwfl_handle;
  1617. bool _dwfl_handle_initialized;
  1618. // defined here because in C++98, template function cannot take locally
  1619. // defined types... grrr.
  1620. struct inliners_search_cb {
  1621. void operator()(Dwarf_Die *die) {
  1622. switch (dwarf_tag(die)) {
  1623. const char *name;
  1624. case DW_TAG_subprogram:
  1625. if ((name = dwarf_diename(die))) {
  1626. trace.source.function = name;
  1627. }
  1628. break;
  1629. case DW_TAG_inlined_subroutine:
  1630. ResolvedTrace::SourceLoc sloc;
  1631. Dwarf_Attribute attr_mem;
  1632. if ((name = dwarf_diename(die))) {
  1633. sloc.function = name;
  1634. }
  1635. if ((name = die_call_file(die))) {
  1636. sloc.filename = name;
  1637. }
  1638. Dwarf_Word line = 0, col = 0;
  1639. dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line);
  1640. dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col);
  1641. sloc.line = (unsigned)line;
  1642. sloc.col = (unsigned)col;
  1643. trace.inliners.push_back(sloc);
  1644. break;
  1645. };
  1646. }
  1647. ResolvedTrace &trace;
  1648. inliners_search_cb(ResolvedTrace &t) : trace(t) {}
  1649. };
  1650. static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) {
  1651. Dwarf_Addr low, high;
  1652. // continuous range
  1653. if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) {
  1654. if (dwarf_lowpc(die, &low) != 0) {
  1655. return false;
  1656. }
  1657. if (dwarf_highpc(die, &high) != 0) {
  1658. Dwarf_Attribute attr_mem;
  1659. Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
  1660. Dwarf_Word value;
  1661. if (dwarf_formudata(attr, &value) != 0) {
  1662. return false;
  1663. }
  1664. high = low + value;
  1665. }
  1666. return pc >= low && pc < high;
  1667. }
  1668. // non-continuous range.
  1669. Dwarf_Addr base;
  1670. ptrdiff_t offset = 0;
  1671. while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
  1672. if (pc >= low && pc < high) {
  1673. return true;
  1674. }
  1675. }
  1676. return false;
  1677. }
  1678. static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
  1679. Dwarf_Die *result) {
  1680. if (dwarf_child(parent_die, result) != 0) {
  1681. return 0;
  1682. }
  1683. Dwarf_Die *die = result;
  1684. do {
  1685. switch (dwarf_tag(die)) {
  1686. case DW_TAG_subprogram:
  1687. case DW_TAG_inlined_subroutine:
  1688. if (die_has_pc(die, pc)) {
  1689. return result;
  1690. }
  1691. };
  1692. bool declaration = false;
  1693. Dwarf_Attribute attr_mem;
  1694. dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
  1695. &declaration);
  1696. if (!declaration) {
  1697. // let's be curious and look deeper in the tree,
  1698. // function are not necessarily at the first level, but
  1699. // might be nested inside a namespace, structure etc.
  1700. Dwarf_Die die_mem;
  1701. Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem);
  1702. if (indie) {
  1703. *result = die_mem;
  1704. return result;
  1705. }
  1706. }
  1707. } while (dwarf_siblingof(die, result) == 0);
  1708. return 0;
  1709. }
  1710. template <typename CB>
  1711. static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
  1712. CB cb) {
  1713. Dwarf_Die die_mem;
  1714. if (dwarf_child(parent_die, &die_mem) != 0) {
  1715. return false;
  1716. }
  1717. bool branch_has_pc = false;
  1718. Dwarf_Die *die = &die_mem;
  1719. do {
  1720. bool declaration = false;
  1721. Dwarf_Attribute attr_mem;
  1722. dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
  1723. &declaration);
  1724. if (!declaration) {
  1725. // let's be curious and look deeper in the tree, function are
  1726. // not necessarily at the first level, but might be nested
  1727. // inside a namespace, structure, a function, an inlined
  1728. // function etc.
  1729. branch_has_pc = deep_first_search_by_pc(die, pc, cb);
  1730. }
  1731. if (!branch_has_pc) {
  1732. branch_has_pc = die_has_pc(die, pc);
  1733. }
  1734. if (branch_has_pc) {
  1735. cb(die);
  1736. }
  1737. } while (dwarf_siblingof(die, &die_mem) == 0);
  1738. return branch_has_pc;
  1739. }
  1740. static const char *die_call_file(Dwarf_Die *die) {
  1741. Dwarf_Attribute attr_mem;
  1742. Dwarf_Word file_idx = 0;
  1743. dwarf_formudata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx);
  1744. if (file_idx == 0) {
  1745. return 0;
  1746. }
  1747. Dwarf_Die die_mem;
  1748. Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0);
  1749. if (!cudie) {
  1750. return 0;
  1751. }
  1752. Dwarf_Files *files = 0;
  1753. size_t nfiles;
  1754. dwarf_getsrcfiles(cudie, &files, &nfiles);
  1755. if (!files) {
  1756. return 0;
  1757. }
  1758. return dwarf_filesrc(files, file_idx, 0, 0);
  1759. }
  1760. };
  1761. #endif // BACKWARD_HAS_DW == 1
  1762. #if BACKWARD_HAS_DWARF == 1
  1763. template <>
  1764. class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>
  1765. : public TraceResolverLinuxBase {
  1766. public:
  1767. TraceResolverLinuxImpl() : _dwarf_loaded(false) {}
  1768. template <class ST> void load_stacktrace(ST &) {}
  1769. ResolvedTrace resolve(ResolvedTrace trace) {
  1770. // trace.addr is a virtual address in memory pointing to some code.
  1771. // Let's try to find from which loaded object it comes from.
  1772. // The loaded object can be yourself btw.
  1773. Dl_info symbol_info;
  1774. int dladdr_result = 0;
  1775. #if defined(__GLIBC__)
  1776. link_map *link_map;
  1777. // We request the link map so we can get information about offsets
  1778. dladdr_result =
  1779. dladdr1(trace.addr, &symbol_info, reinterpret_cast<void **>(&link_map),
  1780. RTLD_DL_LINKMAP);
  1781. #else
  1782. // Android doesn't have dladdr1. Don't use the linker map.
  1783. dladdr_result = dladdr(trace.addr, &symbol_info);
  1784. #endif
  1785. if (!dladdr_result) {
  1786. return trace; // dat broken trace...
  1787. }
  1788. // Now we get in symbol_info:
  1789. // .dli_fname:
  1790. // pathname of the shared object that contains the address.
  1791. // .dli_fbase:
  1792. // where the object is loaded in memory.
  1793. // .dli_sname:
  1794. // the name of the nearest symbol to trace.addr, we expect a
  1795. // function name.
  1796. // .dli_saddr:
  1797. // the exact address corresponding to .dli_sname.
  1798. //
  1799. // And in link_map:
  1800. // .l_addr:
  1801. // difference between the address in the ELF file and the address
  1802. // in memory
  1803. // l_name:
  1804. // absolute pathname where the object was found
  1805. if (symbol_info.dli_sname) {
  1806. trace.object_function = demangle(symbol_info.dli_sname);
  1807. }
  1808. if (!symbol_info.dli_fname) {
  1809. return trace;
  1810. }
  1811. trace.object_filename = resolve_exec_path(symbol_info);
  1812. dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname);
  1813. if (!fobj.dwarf_handle) {
  1814. return trace; // sad, we couldn't load the object :(
  1815. }
  1816. #if defined(__GLIBC__)
  1817. // Convert the address to a module relative one by looking at
  1818. // the module's loading address in the link map
  1819. Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr) -
  1820. reinterpret_cast<uintptr_t>(link_map->l_addr);
  1821. #else
  1822. Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr);
  1823. #endif
  1824. if (trace.object_function.empty()) {
  1825. symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address);
  1826. if (it != fobj.symbol_cache.end()) {
  1827. if (it->first != address) {
  1828. if (it != fobj.symbol_cache.begin()) {
  1829. --it;
  1830. }
  1831. }
  1832. trace.object_function = demangle(it->second.c_str());
  1833. }
  1834. }
  1835. // Get the Compilation Unit DIE for the address
  1836. Dwarf_Die die = find_die(fobj, address);
  1837. if (!die) {
  1838. return trace; // this time we lost the game :/
  1839. }
  1840. // libdwarf doesn't give us direct access to its objects, it always
  1841. // allocates a copy for the caller. We keep that copy alive in a cache
  1842. // and we deallocate it later when it's no longer required.
  1843. die_cache_entry &die_object = get_die_cache(fobj, die);
  1844. if (die_object.isEmpty())
  1845. return trace; // We have no line section for this DIE
  1846. die_linemap_t::iterator it = die_object.line_section.lower_bound(address);
  1847. if (it != die_object.line_section.end()) {
  1848. if (it->first != address) {
  1849. if (it == die_object.line_section.begin()) {
  1850. // If we are on the first item of the line section
  1851. // but the address does not match it means that
  1852. // the address is below the range of the DIE. Give up.
  1853. return trace;
  1854. } else {
  1855. --it;
  1856. }
  1857. }
  1858. } else {
  1859. return trace; // We didn't find the address.
  1860. }
  1861. // Get the Dwarf_Line that the address points to and call libdwarf
  1862. // to get source file, line and column info.
  1863. Dwarf_Line line = die_object.line_buffer[it->second];
  1864. Dwarf_Error error = DW_DLE_NE;
  1865. char *filename;
  1866. if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) {
  1867. trace.source.filename = std::string(filename);
  1868. dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
  1869. }
  1870. Dwarf_Unsigned number = 0;
  1871. if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
  1872. trace.source.line = number;
  1873. } else {
  1874. trace.source.line = 0;
  1875. }
  1876. if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
  1877. trace.source.col = number;
  1878. } else {
  1879. trace.source.col = 0;
  1880. }
  1881. std::vector<std::string> namespace_stack;
  1882. deep_first_search_by_pc(fobj, die, address, namespace_stack,
  1883. inliners_search_cb(trace, fobj, die));
  1884. dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
  1885. return trace;
  1886. }
  1887. public:
  1888. static int close_dwarf(Dwarf_Debug dwarf) {
  1889. return dwarf_finish(dwarf, NULL);
  1890. }
  1891. private:
  1892. bool _dwarf_loaded;
  1893. typedef details::handle<int, details::deleter<int, int, &::close>>
  1894. dwarf_file_t;
  1895. typedef details::handle<Elf *, details::deleter<int, Elf *, &elf_end>>
  1896. dwarf_elf_t;
  1897. typedef details::handle<Dwarf_Debug,
  1898. details::deleter<int, Dwarf_Debug, &close_dwarf>>
  1899. dwarf_handle_t;
  1900. typedef std::map<Dwarf_Addr, int> die_linemap_t;
  1901. typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
  1902. struct die_cache_entry {
  1903. die_specmap_t spec_section;
  1904. die_linemap_t line_section;
  1905. Dwarf_Line *line_buffer;
  1906. Dwarf_Signed line_count;
  1907. Dwarf_Line_Context line_context;
  1908. inline bool isEmpty() {
  1909. return line_buffer == NULL || line_count == 0 || line_context == NULL ||
  1910. line_section.empty();
  1911. }
  1912. die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {}
  1913. ~die_cache_entry() {
  1914. if (line_context) {
  1915. dwarf_srclines_dealloc_b(line_context);
  1916. }
  1917. }
  1918. };
  1919. typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
  1920. typedef std::map<uintptr_t, std::string> symbol_cache_t;
  1921. struct dwarf_fileobject {
  1922. dwarf_file_t file_handle;
  1923. dwarf_elf_t elf_handle;
  1924. dwarf_handle_t dwarf_handle;
  1925. symbol_cache_t symbol_cache;
  1926. // Die cache
  1927. die_cache_t die_cache;
  1928. die_cache_entry *current_cu;
  1929. };
  1930. typedef details::hashtable<std::string, dwarf_fileobject>::type
  1931. fobj_dwarf_map_t;
  1932. fobj_dwarf_map_t _fobj_dwarf_map;
  1933. static bool cstrings_eq(const char *a, const char *b) {
  1934. if (!a || !b) {
  1935. return false;
  1936. }
  1937. return strcmp(a, b) == 0;
  1938. }
  1939. dwarf_fileobject &load_object_with_dwarf(const std::string &filename_object) {
  1940. if (!_dwarf_loaded) {
  1941. // Set the ELF library operating version
  1942. // If that fails there's nothing we can do
  1943. _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
  1944. }
  1945. fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object);
  1946. if (it != _fobj_dwarf_map.end()) {
  1947. return it->second;
  1948. }
  1949. // this new object is empty for now
  1950. dwarf_fileobject &r = _fobj_dwarf_map[filename_object];
  1951. dwarf_file_t file_handle;
  1952. file_handle.reset(open(filename_object.c_str(), O_RDONLY));
  1953. if (file_handle.get() < 0) {
  1954. return r;
  1955. }
  1956. // Try to get an ELF handle. We need to read the ELF sections
  1957. // because we want to see if there is a .gnu_debuglink section
  1958. // that points to a split debug file
  1959. dwarf_elf_t elf_handle;
  1960. elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
  1961. if (!elf_handle) {
  1962. return r;
  1963. }
  1964. const char *e_ident = elf_getident(elf_handle.get(), 0);
  1965. if (!e_ident) {
  1966. return r;
  1967. }
  1968. // Get the number of sections
  1969. // We use the new APIs as elf_getshnum is deprecated
  1970. size_t shdrnum = 0;
  1971. if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
  1972. return r;
  1973. }
  1974. // Get the index to the string section
  1975. size_t shdrstrndx = 0;
  1976. if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) {
  1977. return r;
  1978. }
  1979. std::string debuglink;
  1980. // Iterate through the ELF sections to try to get a gnu_debuglink
  1981. // note and also to cache the symbol table.
  1982. // We go the preprocessor way to avoid having to create templated
  1983. // classes or using gelf (which might throw a compiler error if 64 bit
  1984. // is not supported
  1985. #define ELF_GET_DATA(ARCH) \
  1986. Elf_Scn *elf_section = 0; \
  1987. Elf_Data *elf_data = 0; \
  1988. Elf##ARCH##_Shdr *section_header = 0; \
  1989. Elf_Scn *symbol_section = 0; \
  1990. size_t symbol_count = 0; \
  1991. size_t symbol_strings = 0; \
  1992. Elf##ARCH##_Sym *symbol = 0; \
  1993. const char *section_name = 0; \
  1994. \
  1995. while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \
  1996. section_header = elf##ARCH##_getshdr(elf_section); \
  1997. if (section_header == NULL) { \
  1998. return r; \
  1999. } \
  2000. \
  2001. if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \
  2002. section_header->sh_name)) == NULL) { \
  2003. return r; \
  2004. } \
  2005. \
  2006. if (cstrings_eq(section_name, ".gnu_debuglink")) { \
  2007. elf_data = elf_getdata(elf_section, NULL); \
  2008. if (elf_data && elf_data->d_size > 0) { \
  2009. debuglink = \
  2010. std::string(reinterpret_cast<const char *>(elf_data->d_buf)); \
  2011. } \
  2012. } \
  2013. \
  2014. switch (section_header->sh_type) { \
  2015. case SHT_SYMTAB: \
  2016. symbol_section = elf_section; \
  2017. symbol_count = section_header->sh_size / section_header->sh_entsize; \
  2018. symbol_strings = section_header->sh_link; \
  2019. break; \
  2020. \
  2021. /* We use .dynsyms as a last resort, we prefer .symtab */ \
  2022. case SHT_DYNSYM: \
  2023. if (!symbol_section) { \
  2024. symbol_section = elf_section; \
  2025. symbol_count = section_header->sh_size / section_header->sh_entsize; \
  2026. symbol_strings = section_header->sh_link; \
  2027. } \
  2028. break; \
  2029. } \
  2030. } \
  2031. \
  2032. if (symbol_section && symbol_count && symbol_strings) { \
  2033. elf_data = elf_getdata(symbol_section, NULL); \
  2034. symbol = reinterpret_cast<Elf##ARCH##_Sym *>(elf_data->d_buf); \
  2035. for (size_t i = 0; i < symbol_count; ++i) { \
  2036. int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
  2037. if (type == STT_FUNC && symbol->st_value > 0) { \
  2038. r.symbol_cache[symbol->st_value] = std::string( \
  2039. elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \
  2040. } \
  2041. ++symbol; \
  2042. } \
  2043. }
  2044. if (e_ident[EI_CLASS] == ELFCLASS32) {
  2045. ELF_GET_DATA(32)
  2046. } else if (e_ident[EI_CLASS] == ELFCLASS64) {
  2047. // libelf might have been built without 64 bit support
  2048. #if __LIBELF64
  2049. ELF_GET_DATA(64)
  2050. #endif
  2051. }
  2052. if (!debuglink.empty()) {
  2053. // We have a debuglink section! Open an elf instance on that
  2054. // file instead. If we can't open the file, then return
  2055. // the elf handle we had already opened.
  2056. dwarf_file_t debuglink_file;
  2057. debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
  2058. if (debuglink_file.get() > 0) {
  2059. dwarf_elf_t debuglink_elf;
  2060. debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL));
  2061. // If we have a valid elf handle, return the new elf handle
  2062. // and file handle and discard the original ones
  2063. if (debuglink_elf) {
  2064. elf_handle = move(debuglink_elf);
  2065. file_handle = move(debuglink_file);
  2066. }
  2067. }
  2068. }
  2069. // Ok, we have a valid ELF handle, let's try to get debug symbols
  2070. Dwarf_Debug dwarf_debug;
  2071. Dwarf_Error error = DW_DLE_NE;
  2072. dwarf_handle_t dwarf_handle;
  2073. int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL,
  2074. &dwarf_debug, &error);
  2075. // We don't do any special handling for DW_DLV_NO_ENTRY specially.
  2076. // If we get an error, or the file doesn't have debug information
  2077. // we just return.
  2078. if (dwarf_result != DW_DLV_OK) {
  2079. return r;
  2080. }
  2081. dwarf_handle.reset(dwarf_debug);
  2082. r.file_handle = move(file_handle);
  2083. r.elf_handle = move(elf_handle);
  2084. r.dwarf_handle = move(dwarf_handle);
  2085. return r;
  2086. }
  2087. die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) {
  2088. Dwarf_Error error = DW_DLE_NE;
  2089. // Get the die offset, we use it as the cache key
  2090. Dwarf_Off die_offset;
  2091. if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
  2092. die_offset = 0;
  2093. }
  2094. die_cache_t::iterator it = fobj.die_cache.find(die_offset);
  2095. if (it != fobj.die_cache.end()) {
  2096. fobj.current_cu = &it->second;
  2097. return it->second;
  2098. }
  2099. die_cache_entry &de = fobj.die_cache[die_offset];
  2100. fobj.current_cu = &de;
  2101. Dwarf_Addr line_addr;
  2102. Dwarf_Small table_count;
  2103. // The addresses in the line section are not fully sorted (they might
  2104. // be sorted by block of code belonging to the same file), which makes
  2105. // it necessary to do so before searching is possible.
  2106. //
  2107. // As libdwarf allocates a copy of everything, let's get the contents
  2108. // of the line section and keep it around. We also create a map of
  2109. // program counter to line table indices so we can search by address
  2110. // and get the line buffer index.
  2111. //
  2112. // To make things more difficult, the same address can span more than
  2113. // one line, so we need to keep the index pointing to the first line
  2114. // by using insert instead of the map's [ operator.
  2115. // Get the line context for the DIE
  2116. if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) ==
  2117. DW_DLV_OK) {
  2118. // Get the source lines for this line context, to be deallocated
  2119. // later
  2120. if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer,
  2121. &de.line_count,
  2122. &error) == DW_DLV_OK) {
  2123. // Add all the addresses to our map
  2124. for (int i = 0; i < de.line_count; i++) {
  2125. if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) !=
  2126. DW_DLV_OK) {
  2127. line_addr = 0;
  2128. }
  2129. de.line_section.insert(std::pair<Dwarf_Addr, int>(line_addr, i));
  2130. }
  2131. }
  2132. }
  2133. // For each CU, cache the function DIEs that contain the
  2134. // DW_AT_specification attribute. When building with -g3 the function
  2135. // DIEs are separated in declaration and specification, with the
  2136. // declaration containing only the name and parameters and the
  2137. // specification the low/high pc and other compiler attributes.
  2138. //
  2139. // We cache those specifications so we don't skip over the declarations,
  2140. // because they have no pc, and we can do namespace resolution for
  2141. // DWARF function names.
  2142. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2143. Dwarf_Die current_die = 0;
  2144. if (dwarf_child(die, &current_die, &error) == DW_DLV_OK) {
  2145. for (;;) {
  2146. Dwarf_Die sibling_die = 0;
  2147. Dwarf_Half tag_value;
  2148. dwarf_tag(current_die, &tag_value, &error);
  2149. if (tag_value == DW_TAG_subprogram ||
  2150. tag_value == DW_TAG_inlined_subroutine) {
  2151. Dwarf_Bool has_attr = 0;
  2152. if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr,
  2153. &error) == DW_DLV_OK) {
  2154. if (has_attr) {
  2155. Dwarf_Attribute attr_mem;
  2156. if (dwarf_attr(current_die, DW_AT_specification, &attr_mem,
  2157. &error) == DW_DLV_OK) {
  2158. Dwarf_Off spec_offset = 0;
  2159. if (dwarf_formref(attr_mem, &spec_offset, &error) ==
  2160. DW_DLV_OK) {
  2161. Dwarf_Off spec_die_offset;
  2162. if (dwarf_dieoffset(current_die, &spec_die_offset, &error) ==
  2163. DW_DLV_OK) {
  2164. de.spec_section[spec_offset] = spec_die_offset;
  2165. }
  2166. }
  2167. }
  2168. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2169. }
  2170. }
  2171. }
  2172. int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
  2173. if (result == DW_DLV_ERROR) {
  2174. break;
  2175. } else if (result == DW_DLV_NO_ENTRY) {
  2176. break;
  2177. }
  2178. if (current_die != die) {
  2179. dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
  2180. current_die = 0;
  2181. }
  2182. current_die = sibling_die;
  2183. }
  2184. }
  2185. return de;
  2186. }
  2187. static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die,
  2188. Dwarf_Half attr, bool global) {
  2189. Dwarf_Error error = DW_DLE_NE;
  2190. Dwarf_Attribute attr_mem;
  2191. Dwarf_Die found_die = NULL;
  2192. if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
  2193. Dwarf_Off offset;
  2194. int result = 0;
  2195. if (global) {
  2196. result = dwarf_global_formref(attr_mem, &offset, &error);
  2197. } else {
  2198. result = dwarf_formref(attr_mem, &offset, &error);
  2199. }
  2200. if (result == DW_DLV_OK) {
  2201. if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) {
  2202. found_die = NULL;
  2203. }
  2204. }
  2205. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2206. }
  2207. return found_die;
  2208. }
  2209. static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die,
  2210. Dwarf_Half attr, bool global) {
  2211. Dwarf_Error error = DW_DLE_NE;
  2212. std::string value;
  2213. Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
  2214. if (found_die) {
  2215. char *name;
  2216. if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
  2217. if (name) {
  2218. value = std::string(name);
  2219. }
  2220. dwarf_dealloc(dwarf, name, DW_DLA_STRING);
  2221. }
  2222. dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
  2223. }
  2224. return value;
  2225. }
  2226. // Returns a spec DIE linked to the passed one. The caller should
  2227. // deallocate the DIE
  2228. static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) {
  2229. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2230. Dwarf_Error error = DW_DLE_NE;
  2231. Dwarf_Off die_offset;
  2232. if (fobj.current_cu &&
  2233. dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) {
  2234. die_specmap_t::iterator it =
  2235. fobj.current_cu->spec_section.find(die_offset);
  2236. // If we have a DIE that completes the current one, check if
  2237. // that one has the pc we are looking for
  2238. if (it != fobj.current_cu->spec_section.end()) {
  2239. Dwarf_Die spec_die = 0;
  2240. if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) {
  2241. return spec_die;
  2242. }
  2243. }
  2244. }
  2245. // Maybe we have an abstract origin DIE with the function information?
  2246. return get_referenced_die(fobj.dwarf_handle.get(), die,
  2247. DW_AT_abstract_origin, true);
  2248. }
  2249. static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) {
  2250. Dwarf_Addr low_pc = 0, high_pc = 0;
  2251. Dwarf_Half high_pc_form = 0;
  2252. Dwarf_Form_Class return_class;
  2253. Dwarf_Error error = DW_DLE_NE;
  2254. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2255. bool has_lowpc = false;
  2256. bool has_highpc = false;
  2257. bool has_ranges = false;
  2258. if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
  2259. // If we have a low_pc check if there is a high pc.
  2260. // If we don't have a high pc this might mean we have a base
  2261. // address for the ranges list or just an address.
  2262. has_lowpc = true;
  2263. if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) ==
  2264. DW_DLV_OK) {
  2265. // We do have a high pc. In DWARF 4+ this is an offset from the
  2266. // low pc, but in earlier versions it's an absolute address.
  2267. has_highpc = true;
  2268. // In DWARF 2/3 this would be a DW_FORM_CLASS_ADDRESS
  2269. if (return_class == DW_FORM_CLASS_CONSTANT) {
  2270. high_pc = low_pc + high_pc;
  2271. }
  2272. // We have low and high pc, check if our address
  2273. // is in that range
  2274. return pc >= low_pc && pc < high_pc;
  2275. }
  2276. } else {
  2277. // Reset the low_pc, in case dwarf_lowpc failing set it to some
  2278. // undefined value.
  2279. low_pc = 0;
  2280. }
  2281. // Check if DW_AT_ranges is present and search for the PC in the
  2282. // returned ranges list. We always add the low_pc, as it not set it will
  2283. // be 0, in case we had a DW_AT_low_pc and DW_AT_ranges pair
  2284. bool result = false;
  2285. Dwarf_Attribute attr;
  2286. if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
  2287. Dwarf_Off offset;
  2288. if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
  2289. Dwarf_Ranges *ranges;
  2290. Dwarf_Signed ranges_count = 0;
  2291. Dwarf_Unsigned byte_count = 0;
  2292. if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count,
  2293. &byte_count, &error) == DW_DLV_OK) {
  2294. has_ranges = ranges_count != 0;
  2295. for (int i = 0; i < ranges_count; i++) {
  2296. if (ranges[i].dwr_addr1 != 0 &&
  2297. pc >= ranges[i].dwr_addr1 + low_pc &&
  2298. pc < ranges[i].dwr_addr2 + low_pc) {
  2299. result = true;
  2300. break;
  2301. }
  2302. }
  2303. dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
  2304. }
  2305. }
  2306. }
  2307. // Last attempt. We might have a single address set as low_pc.
  2308. if (!result && low_pc != 0 && pc == low_pc) {
  2309. result = true;
  2310. }
  2311. // If we don't have lowpc, highpc and ranges maybe this DIE is a
  2312. // declaration that relies on a DW_AT_specification DIE that happens
  2313. // later. Use the specification cache we filled when we loaded this CU.
  2314. if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
  2315. Dwarf_Die spec_die = get_spec_die(fobj, die);
  2316. if (spec_die) {
  2317. result = die_has_pc(fobj, spec_die, pc);
  2318. dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
  2319. }
  2320. }
  2321. return result;
  2322. }
  2323. static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &type) {
  2324. Dwarf_Error error = DW_DLE_NE;
  2325. Dwarf_Die child = 0;
  2326. if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
  2327. get_type(dwarf, child, type);
  2328. }
  2329. if (child) {
  2330. type.insert(0, "::");
  2331. dwarf_dealloc(dwarf, child, DW_DLA_DIE);
  2332. }
  2333. char *name;
  2334. if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
  2335. type.insert(0, std::string(name));
  2336. dwarf_dealloc(dwarf, name, DW_DLA_STRING);
  2337. } else {
  2338. type.insert(0, "<unknown>");
  2339. }
  2340. }
  2341. static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
  2342. Dwarf_Error error = DW_DLE_NE;
  2343. Dwarf_Sig8 signature;
  2344. Dwarf_Bool has_attr = 0;
  2345. if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) {
  2346. if (has_attr) {
  2347. Dwarf_Attribute attr_mem;
  2348. if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) {
  2349. if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) {
  2350. return std::string("<no type signature>");
  2351. }
  2352. }
  2353. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2354. }
  2355. }
  2356. Dwarf_Unsigned next_cu_header;
  2357. Dwarf_Sig8 tu_signature;
  2358. std::string result;
  2359. bool found = false;
  2360. while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0,
  2361. &next_cu_header, 0, &error) == DW_DLV_OK) {
  2362. if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
  2363. Dwarf_Die type_cu_die = 0;
  2364. if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) {
  2365. Dwarf_Die child_die = 0;
  2366. if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) {
  2367. get_type(dwarf, child_die, result);
  2368. found = !result.empty();
  2369. dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
  2370. }
  2371. dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
  2372. }
  2373. }
  2374. }
  2375. if (found) {
  2376. while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2377. &next_cu_header, 0, &error) == DW_DLV_OK) {
  2378. // Reset the cu header state. Unfortunately, libdwarf's
  2379. // next_cu_header API keeps its own iterator per Dwarf_Debug
  2380. // that can't be reset. We need to keep fetching elements until
  2381. // the end.
  2382. }
  2383. } else {
  2384. // If we couldn't resolve the type just print out the signature
  2385. std::ostringstream string_stream;
  2386. string_stream << "<0x" << std::hex << std::setfill('0');
  2387. for (int i = 0; i < 8; ++i) {
  2388. string_stream << std::setw(2) << std::hex
  2389. << (int)(unsigned char)(signature.signature[i]);
  2390. }
  2391. string_stream << ">";
  2392. result = string_stream.str();
  2393. }
  2394. return result;
  2395. }
  2396. struct type_context_t {
  2397. bool is_const;
  2398. bool is_typedef;
  2399. bool has_type;
  2400. bool has_name;
  2401. std::string text;
  2402. type_context_t()
  2403. : is_const(false), is_typedef(false), has_type(false), has_name(false) {
  2404. }
  2405. };
  2406. // Types are resolved from right to left: we get the variable name first
  2407. // and then all specifiers (like const or pointer) in a chain of DW_AT_type
  2408. // DIEs. Call this function recursively until we get a complete type
  2409. // string.
  2410. static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die,
  2411. type_context_t &context) {
  2412. char *name;
  2413. Dwarf_Error error = DW_DLE_NE;
  2414. // typedefs contain also the base type, so we skip it and only
  2415. // print the typedef name
  2416. if (!context.is_typedef) {
  2417. if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
  2418. if (!context.text.empty()) {
  2419. context.text.insert(0, " ");
  2420. }
  2421. context.text.insert(0, std::string(name));
  2422. dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
  2423. }
  2424. } else {
  2425. context.is_typedef = false;
  2426. context.has_type = true;
  2427. if (context.is_const) {
  2428. context.text.insert(0, "const ");
  2429. context.is_const = false;
  2430. }
  2431. }
  2432. bool next_type_is_const = false;
  2433. bool is_keyword = true;
  2434. Dwarf_Half tag = 0;
  2435. Dwarf_Bool has_attr = 0;
  2436. if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
  2437. switch (tag) {
  2438. case DW_TAG_structure_type:
  2439. case DW_TAG_union_type:
  2440. case DW_TAG_class_type:
  2441. case DW_TAG_enumeration_type:
  2442. context.has_type = true;
  2443. if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) ==
  2444. DW_DLV_OK) {
  2445. // If we have a signature it means the type is defined
  2446. // in .debug_types, so we need to load the DIE pointed
  2447. // at by the signature and resolve it
  2448. if (has_attr) {
  2449. std::string type =
  2450. get_type_by_signature(fobj.dwarf_handle.get(), die);
  2451. if (context.is_const)
  2452. type.insert(0, "const ");
  2453. if (!context.text.empty())
  2454. context.text.insert(0, " ");
  2455. context.text.insert(0, type);
  2456. }
  2457. // Treat enums like typedefs, and skip printing its
  2458. // base type
  2459. context.is_typedef = (tag == DW_TAG_enumeration_type);
  2460. }
  2461. break;
  2462. case DW_TAG_const_type:
  2463. next_type_is_const = true;
  2464. break;
  2465. case DW_TAG_pointer_type:
  2466. context.text.insert(0, "*");
  2467. break;
  2468. case DW_TAG_reference_type:
  2469. context.text.insert(0, "&");
  2470. break;
  2471. case DW_TAG_restrict_type:
  2472. context.text.insert(0, "restrict ");
  2473. break;
  2474. case DW_TAG_rvalue_reference_type:
  2475. context.text.insert(0, "&&");
  2476. break;
  2477. case DW_TAG_volatile_type:
  2478. context.text.insert(0, "volatile ");
  2479. break;
  2480. case DW_TAG_typedef:
  2481. // Propagate the const-ness to the next type
  2482. // as typedefs are linked to its base type
  2483. next_type_is_const = context.is_const;
  2484. context.is_typedef = true;
  2485. context.has_type = true;
  2486. break;
  2487. case DW_TAG_base_type:
  2488. context.has_type = true;
  2489. break;
  2490. case DW_TAG_formal_parameter:
  2491. context.has_name = true;
  2492. break;
  2493. default:
  2494. is_keyword = false;
  2495. break;
  2496. }
  2497. }
  2498. if (!is_keyword && context.is_const) {
  2499. context.text.insert(0, "const ");
  2500. }
  2501. context.is_const = next_type_is_const;
  2502. Dwarf_Die ref =
  2503. get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type, true);
  2504. if (ref) {
  2505. set_parameter_string(fobj, ref, context);
  2506. dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
  2507. }
  2508. if (!context.has_type && context.has_name) {
  2509. context.text.insert(0, "void ");
  2510. context.has_type = true;
  2511. }
  2512. }
  2513. // Resolve the function return type and parameters
  2514. static void set_function_parameters(std::string &function_name,
  2515. std::vector<std::string> &ns,
  2516. dwarf_fileobject &fobj, Dwarf_Die die) {
  2517. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2518. Dwarf_Error error = DW_DLE_NE;
  2519. Dwarf_Die current_die = 0;
  2520. std::string parameters;
  2521. bool has_spec = true;
  2522. // Check if we have a spec DIE. If we do we use it as it contains
  2523. // more information, like parameter names.
  2524. Dwarf_Die spec_die = get_spec_die(fobj, die);
  2525. if (!spec_die) {
  2526. has_spec = false;
  2527. spec_die = die;
  2528. }
  2529. std::vector<std::string>::const_iterator it = ns.begin();
  2530. std::string ns_name;
  2531. for (it = ns.begin(); it < ns.end(); ++it) {
  2532. ns_name.append(*it).append("::");
  2533. }
  2534. if (!ns_name.empty()) {
  2535. function_name.insert(0, ns_name);
  2536. }
  2537. // See if we have a function return type. It can be either on the
  2538. // current die or in its spec one (usually true for inlined functions)
  2539. std::string return_type =
  2540. get_referenced_die_name(dwarf, die, DW_AT_type, true);
  2541. if (return_type.empty()) {
  2542. return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type, true);
  2543. }
  2544. if (!return_type.empty()) {
  2545. return_type.append(" ");
  2546. function_name.insert(0, return_type);
  2547. }
  2548. if (dwarf_child(spec_die, &current_die, &error) == DW_DLV_OK) {
  2549. for (;;) {
  2550. Dwarf_Die sibling_die = 0;
  2551. Dwarf_Half tag_value;
  2552. dwarf_tag(current_die, &tag_value, &error);
  2553. if (tag_value == DW_TAG_formal_parameter) {
  2554. // Ignore artificial (ie, compiler generated) parameters
  2555. bool is_artificial = false;
  2556. Dwarf_Attribute attr_mem;
  2557. if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) ==
  2558. DW_DLV_OK) {
  2559. Dwarf_Bool flag = 0;
  2560. if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
  2561. is_artificial = flag != 0;
  2562. }
  2563. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2564. }
  2565. if (!is_artificial) {
  2566. type_context_t context;
  2567. set_parameter_string(fobj, current_die, context);
  2568. if (parameters.empty()) {
  2569. parameters.append("(");
  2570. } else {
  2571. parameters.append(", ");
  2572. }
  2573. parameters.append(context.text);
  2574. }
  2575. }
  2576. int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
  2577. if (result == DW_DLV_ERROR) {
  2578. break;
  2579. } else if (result == DW_DLV_NO_ENTRY) {
  2580. break;
  2581. }
  2582. if (current_die != die) {
  2583. dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
  2584. current_die = 0;
  2585. }
  2586. current_die = sibling_die;
  2587. }
  2588. }
  2589. if (parameters.empty())
  2590. parameters = "(";
  2591. parameters.append(")");
  2592. // If we got a spec DIE we need to deallocate it
  2593. if (has_spec)
  2594. dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
  2595. function_name.append(parameters);
  2596. }
  2597. // defined here because in C++98, template function cannot take locally
  2598. // defined types... grrr.
  2599. struct inliners_search_cb {
  2600. void operator()(Dwarf_Die die, std::vector<std::string> &ns) {
  2601. Dwarf_Error error = DW_DLE_NE;
  2602. Dwarf_Half tag_value;
  2603. Dwarf_Attribute attr_mem;
  2604. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2605. dwarf_tag(die, &tag_value, &error);
  2606. switch (tag_value) {
  2607. char *name;
  2608. case DW_TAG_subprogram:
  2609. if (!trace.source.function.empty())
  2610. break;
  2611. if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
  2612. trace.source.function = std::string(name);
  2613. dwarf_dealloc(dwarf, name, DW_DLA_STRING);
  2614. } else {
  2615. // We don't have a function name in this DIE.
  2616. // Check if there is a referenced non-defining
  2617. // declaration.
  2618. trace.source.function =
  2619. get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
  2620. if (trace.source.function.empty()) {
  2621. trace.source.function =
  2622. get_referenced_die_name(dwarf, die, DW_AT_specification, true);
  2623. }
  2624. }
  2625. // Append the function parameters, if available
  2626. set_function_parameters(trace.source.function, ns, fobj, die);
  2627. // If the object function name is empty, it's possible that
  2628. // there is no dynamic symbol table (maybe the executable
  2629. // was stripped or not built with -rdynamic). See if we have
  2630. // a DWARF linkage name to use instead. We try both
  2631. // linkage_name and MIPS_linkage_name because the MIPS tag
  2632. // was the unofficial one until it was adopted in DWARF4.
  2633. // Old gcc versions generate MIPS_linkage_name
  2634. if (trace.object_function.empty()) {
  2635. details::demangler demangler;
  2636. if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) !=
  2637. DW_DLV_OK) {
  2638. if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) !=
  2639. DW_DLV_OK) {
  2640. break;
  2641. }
  2642. }
  2643. char *linkage;
  2644. if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) {
  2645. trace.object_function = demangler.demangle(linkage);
  2646. dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
  2647. }
  2648. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2649. }
  2650. break;
  2651. case DW_TAG_inlined_subroutine:
  2652. ResolvedTrace::SourceLoc sloc;
  2653. if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
  2654. sloc.function = std::string(name);
  2655. dwarf_dealloc(dwarf, name, DW_DLA_STRING);
  2656. } else {
  2657. // We don't have a name for this inlined DIE, it could
  2658. // be that there is an abstract origin instead.
  2659. // Get the DW_AT_abstract_origin value, which is a
  2660. // reference to the source DIE and try to get its name
  2661. sloc.function =
  2662. get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
  2663. }
  2664. set_function_parameters(sloc.function, ns, fobj, die);
  2665. std::string file = die_call_file(dwarf, die, cu_die);
  2666. if (!file.empty())
  2667. sloc.filename = file;
  2668. Dwarf_Unsigned number = 0;
  2669. if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) {
  2670. if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
  2671. sloc.line = number;
  2672. }
  2673. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2674. }
  2675. if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) ==
  2676. DW_DLV_OK) {
  2677. if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
  2678. sloc.col = number;
  2679. }
  2680. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2681. }
  2682. trace.inliners.push_back(sloc);
  2683. break;
  2684. };
  2685. }
  2686. ResolvedTrace &trace;
  2687. dwarf_fileobject &fobj;
  2688. Dwarf_Die cu_die;
  2689. inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &f, Dwarf_Die c)
  2690. : trace(t), fobj(f), cu_die(c) {}
  2691. };
  2692. static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj,
  2693. Dwarf_Die parent_die, Dwarf_Addr pc,
  2694. Dwarf_Die result) {
  2695. Dwarf_Die current_die = 0;
  2696. Dwarf_Error error = DW_DLE_NE;
  2697. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2698. if (dwarf_child(parent_die, &current_die, &error) != DW_DLV_OK) {
  2699. return NULL;
  2700. }
  2701. for (;;) {
  2702. Dwarf_Die sibling_die = 0;
  2703. Dwarf_Half tag_value;
  2704. dwarf_tag(current_die, &tag_value, &error);
  2705. switch (tag_value) {
  2706. case DW_TAG_subprogram:
  2707. case DW_TAG_inlined_subroutine:
  2708. if (die_has_pc(fobj, current_die, pc)) {
  2709. return current_die;
  2710. }
  2711. };
  2712. bool declaration = false;
  2713. Dwarf_Attribute attr_mem;
  2714. if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
  2715. DW_DLV_OK) {
  2716. Dwarf_Bool flag = 0;
  2717. if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
  2718. declaration = flag != 0;
  2719. }
  2720. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2721. }
  2722. if (!declaration) {
  2723. // let's be curious and look deeper in the tree, functions are
  2724. // not necessarily at the first level, but might be nested
  2725. // inside a namespace, structure, a function, an inlined
  2726. // function etc.
  2727. Dwarf_Die die_mem = 0;
  2728. Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem);
  2729. if (indie) {
  2730. result = die_mem;
  2731. return result;
  2732. }
  2733. }
  2734. int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
  2735. if (res == DW_DLV_ERROR) {
  2736. return NULL;
  2737. } else if (res == DW_DLV_NO_ENTRY) {
  2738. break;
  2739. }
  2740. if (current_die != parent_die) {
  2741. dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
  2742. current_die = 0;
  2743. }
  2744. current_die = sibling_die;
  2745. }
  2746. return NULL;
  2747. }
  2748. template <typename CB>
  2749. static bool deep_first_search_by_pc(dwarf_fileobject &fobj,
  2750. Dwarf_Die parent_die, Dwarf_Addr pc,
  2751. std::vector<std::string> &ns, CB cb) {
  2752. Dwarf_Die current_die = 0;
  2753. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2754. Dwarf_Error error = DW_DLE_NE;
  2755. if (dwarf_child(parent_die, &current_die, &error) != DW_DLV_OK) {
  2756. return false;
  2757. }
  2758. bool branch_has_pc = false;
  2759. bool has_namespace = false;
  2760. for (;;) {
  2761. Dwarf_Die sibling_die = 0;
  2762. Dwarf_Half tag;
  2763. if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
  2764. if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
  2765. char *ns_name = NULL;
  2766. if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) {
  2767. if (ns_name) {
  2768. ns.push_back(std::string(ns_name));
  2769. } else {
  2770. ns.push_back("<unknown>");
  2771. }
  2772. dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
  2773. } else {
  2774. ns.push_back("<unknown>");
  2775. }
  2776. has_namespace = true;
  2777. }
  2778. }
  2779. bool declaration = false;
  2780. Dwarf_Attribute attr_mem;
  2781. if (tag != DW_TAG_class_type &&
  2782. dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
  2783. DW_DLV_OK) {
  2784. Dwarf_Bool flag = 0;
  2785. if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
  2786. declaration = flag != 0;
  2787. }
  2788. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2789. }
  2790. if (!declaration) {
  2791. // let's be curious and look deeper in the tree, function are
  2792. // not necessarily at the first level, but might be nested
  2793. // inside a namespace, structure, a function, an inlined
  2794. // function etc.
  2795. branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb);
  2796. }
  2797. if (!branch_has_pc) {
  2798. branch_has_pc = die_has_pc(fobj, current_die, pc);
  2799. }
  2800. if (branch_has_pc) {
  2801. cb(current_die, ns);
  2802. }
  2803. int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
  2804. if (result == DW_DLV_ERROR) {
  2805. return false;
  2806. } else if (result == DW_DLV_NO_ENTRY) {
  2807. break;
  2808. }
  2809. if (current_die != parent_die) {
  2810. dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
  2811. current_die = 0;
  2812. }
  2813. if (has_namespace) {
  2814. has_namespace = false;
  2815. ns.pop_back();
  2816. }
  2817. current_die = sibling_die;
  2818. }
  2819. if (has_namespace) {
  2820. ns.pop_back();
  2821. }
  2822. return branch_has_pc;
  2823. }
  2824. static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die,
  2825. Dwarf_Die cu_die) {
  2826. Dwarf_Attribute attr_mem;
  2827. Dwarf_Error error = DW_DLE_NE;
  2828. Dwarf_Unsigned file_index;
  2829. std::string file;
  2830. if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
  2831. if (dwarf_formudata(attr_mem, &file_index, &error) != DW_DLV_OK) {
  2832. file_index = 0;
  2833. }
  2834. dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
  2835. if (file_index == 0) {
  2836. return file;
  2837. }
  2838. char **srcfiles = 0;
  2839. Dwarf_Signed file_count = 0;
  2840. if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) {
  2841. if (file_count > 0 && file_index <= static_cast<Dwarf_Unsigned>(file_count)) {
  2842. file = std::string(srcfiles[file_index - 1]);
  2843. }
  2844. // Deallocate all strings!
  2845. for (int i = 0; i < file_count; ++i) {
  2846. dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
  2847. }
  2848. dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
  2849. }
  2850. }
  2851. return file;
  2852. }
  2853. Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) {
  2854. // Let's get to work! First see if we have a debug_aranges section so
  2855. // we can speed up the search
  2856. Dwarf_Debug dwarf = fobj.dwarf_handle.get();
  2857. Dwarf_Error error = DW_DLE_NE;
  2858. Dwarf_Arange *aranges;
  2859. Dwarf_Signed arange_count;
  2860. Dwarf_Die returnDie;
  2861. bool found = false;
  2862. if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) !=
  2863. DW_DLV_OK) {
  2864. aranges = NULL;
  2865. }
  2866. if (aranges) {
  2867. // We have aranges. Get the one where our address is.
  2868. Dwarf_Arange arange;
  2869. if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) ==
  2870. DW_DLV_OK) {
  2871. // We found our address. Get the compilation-unit DIE offset
  2872. // represented by the given address range.
  2873. Dwarf_Off cu_die_offset;
  2874. if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) ==
  2875. DW_DLV_OK) {
  2876. // Get the DIE at the offset returned by the aranges search.
  2877. // We set is_info to 1 to specify that the offset is from
  2878. // the .debug_info section (and not .debug_types)
  2879. int dwarf_result =
  2880. dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error);
  2881. found = dwarf_result == DW_DLV_OK;
  2882. }
  2883. dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
  2884. }
  2885. }
  2886. if (found)
  2887. return returnDie; // The caller is responsible for freeing the die
  2888. // The search for aranges failed. Try to find our address by scanning
  2889. // all compilation units.
  2890. Dwarf_Unsigned next_cu_header;
  2891. Dwarf_Half tag = 0;
  2892. returnDie = 0;
  2893. while (!found &&
  2894. dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  2895. &next_cu_header, 0, &error) == DW_DLV_OK) {
  2896. if (returnDie)
  2897. dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
  2898. if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
  2899. if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) &&
  2900. tag == DW_TAG_compile_unit) {
  2901. if (die_has_pc(fobj, returnDie, addr)) {
  2902. found = true;
  2903. }
  2904. }
  2905. }
  2906. }
  2907. if (found) {
  2908. while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  2909. &next_cu_header, 0, &error) == DW_DLV_OK) {
  2910. // Reset the cu header state. Libdwarf's next_cu_header API
  2911. // keeps its own iterator per Dwarf_Debug that can't be reset.
  2912. // We need to keep fetching elements until the end.
  2913. }
  2914. }
  2915. if (found)
  2916. return returnDie;
  2917. // We couldn't find any compilation units with ranges or a high/low pc.
  2918. // Try again by looking at all DIEs in all compilation units.
  2919. Dwarf_Die cudie;
  2920. while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  2921. &next_cu_header, 0, &error) == DW_DLV_OK) {
  2922. if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
  2923. Dwarf_Die die_mem = 0;
  2924. Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem);
  2925. if (resultDie) {
  2926. found = true;
  2927. break;
  2928. }
  2929. }
  2930. }
  2931. if (found) {
  2932. while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  2933. &next_cu_header, 0, &error) == DW_DLV_OK) {
  2934. // Reset the cu header state. Libdwarf's next_cu_header API
  2935. // keeps its own iterator per Dwarf_Debug that can't be reset.
  2936. // We need to keep fetching elements until the end.
  2937. }
  2938. }
  2939. if (found)
  2940. return cudie;
  2941. // We failed.
  2942. return NULL;
  2943. }
  2944. };
  2945. #endif // BACKWARD_HAS_DWARF == 1
  2946. template <>
  2947. class TraceResolverImpl<system_tag::linux_tag>
  2948. : public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
  2949. #endif // BACKWARD_SYSTEM_LINUX
  2950. #ifdef BACKWARD_SYSTEM_DARWIN
  2951. template <typename STACKTRACE_TAG> class TraceResolverDarwinImpl;
  2952. template <>
  2953. class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>
  2954. : public TraceResolverImplBase {
  2955. public:
  2956. template <class ST> void load_stacktrace(ST &st) {
  2957. using namespace details;
  2958. if (st.size() == 0) {
  2959. return;
  2960. }
  2961. _symbols.reset(backtrace_symbols(st.begin(), st.size()));
  2962. }
  2963. ResolvedTrace resolve(ResolvedTrace trace) {
  2964. // parse:
  2965. // <n> <file> <addr> <mangled-name> + <offset>
  2966. char *filename = _symbols[trace.idx];
  2967. // skip "<n> "
  2968. while (*filename && *filename != ' ')
  2969. filename++;
  2970. while (*filename == ' ')
  2971. filename++;
  2972. // find start of <mangled-name> from end (<file> may contain a space)
  2973. char *p = filename + strlen(filename) - 1;
  2974. // skip to start of " + <offset>"
  2975. while (p > filename && *p != ' ')
  2976. p--;
  2977. while (p > filename && *p == ' ')
  2978. p--;
  2979. while (p > filename && *p != ' ')
  2980. p--;
  2981. while (p > filename && *p == ' ')
  2982. p--;
  2983. char *funcname_end = p + 1;
  2984. // skip to start of "<manged-name>"
  2985. while (p > filename && *p != ' ')
  2986. p--;
  2987. char *funcname = p + 1;
  2988. // skip to start of " <addr> "
  2989. while (p > filename && *p == ' ')
  2990. p--;
  2991. while (p > filename && *p != ' ')
  2992. p--;
  2993. while (p > filename && *p == ' ')
  2994. p--;
  2995. // skip "<file>", handling the case where it contains a
  2996. char *filename_end = p + 1;
  2997. if (p == filename) {
  2998. // something went wrong, give up
  2999. filename_end = filename + strlen(filename);
  3000. funcname = filename_end;
  3001. }
  3002. trace.object_filename.assign(
  3003. filename, filename_end); // ok even if filename_end is the ending \0
  3004. // (then we assign entire string)
  3005. if (*funcname) { // if it's not end of string
  3006. *funcname_end = '\0';
  3007. trace.object_function = this->demangle(funcname);
  3008. trace.object_function += " ";
  3009. trace.object_function += (funcname_end + 1);
  3010. trace.source.function = trace.object_function; // we cannot do better.
  3011. }
  3012. return trace;
  3013. }
  3014. private:
  3015. details::handle<char **> _symbols;
  3016. };
  3017. template <>
  3018. class TraceResolverImpl<system_tag::darwin_tag>
  3019. : public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
  3020. #endif // BACKWARD_SYSTEM_DARWIN
  3021. #ifdef BACKWARD_SYSTEM_WINDOWS
  3022. // Load all symbol info
  3023. // Based on:
  3024. // https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
  3025. struct module_data {
  3026. std::string image_name;
  3027. std::string module_name;
  3028. void *base_address;
  3029. DWORD load_size;
  3030. };
  3031. class get_mod_info {
  3032. HANDLE process;
  3033. static const int buffer_length = 4096;
  3034. public:
  3035. get_mod_info(HANDLE h) : process(h) {}
  3036. module_data operator()(HMODULE module) {
  3037. module_data ret;
  3038. char temp[buffer_length];
  3039. MODULEINFO mi;
  3040. GetModuleInformation(process, module, &mi, sizeof(mi));
  3041. ret.base_address = mi.lpBaseOfDll;
  3042. ret.load_size = mi.SizeOfImage;
  3043. GetModuleFileNameExA(process, module, temp, sizeof(temp));
  3044. ret.image_name = temp;
  3045. GetModuleBaseNameA(process, module, temp, sizeof(temp));
  3046. ret.module_name = temp;
  3047. std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
  3048. std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
  3049. SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address,
  3050. ret.load_size);
  3051. return ret;
  3052. }
  3053. };
  3054. template <> class TraceResolverImpl<system_tag::windows_tag> {
  3055. public:
  3056. TraceResolverImpl() {
  3057. HANDLE process = GetCurrentProcess();
  3058. std::vector<module_data> modules;
  3059. DWORD cbNeeded;
  3060. std::vector<HMODULE> module_handles(1);
  3061. SymInitialize(process, NULL, false);
  3062. DWORD symOptions = SymGetOptions();
  3063. symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME;
  3064. SymSetOptions(symOptions);
  3065. EnumProcessModules(process, &module_handles[0],
  3066. module_handles.size() * sizeof(HMODULE), &cbNeeded);
  3067. module_handles.resize(cbNeeded / sizeof(HMODULE));
  3068. EnumProcessModules(process, &module_handles[0],
  3069. module_handles.size() * sizeof(HMODULE), &cbNeeded);
  3070. std::transform(module_handles.begin(), module_handles.end(),
  3071. std::back_inserter(modules), get_mod_info(process));
  3072. void *base = modules[0].base_address;
  3073. IMAGE_NT_HEADERS *h = ImageNtHeader(base);
  3074. image_type = h->FileHeader.Machine;
  3075. }
  3076. template <class ST> void load_stacktrace(ST &) {}
  3077. static const int max_sym_len = 255;
  3078. struct symbol_t {
  3079. SYMBOL_INFO sym;
  3080. char buffer[max_sym_len];
  3081. } sym;
  3082. DWORD64 displacement;
  3083. ResolvedTrace resolve(ResolvedTrace t) {
  3084. HANDLE process = GetCurrentProcess();
  3085. char name[256];
  3086. memset(&sym, 0, sizeof(sym));
  3087. sym.sym.SizeOfStruct = sizeof(SYMBOL_INFO);
  3088. sym.sym.MaxNameLen = max_sym_len;
  3089. if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) {
  3090. // TODO: error handling everywhere
  3091. char* lpMsgBuf;
  3092. DWORD dw = GetLastError();
  3093. FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  3094. FORMAT_MESSAGE_FROM_SYSTEM |
  3095. FORMAT_MESSAGE_IGNORE_INSERTS,
  3096. NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  3097. (char*)&lpMsgBuf, 0, NULL);
  3098. printf(lpMsgBuf);
  3099. // abort();
  3100. }
  3101. UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE);
  3102. DWORD offset = 0;
  3103. IMAGEHLP_LINE line;
  3104. if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) {
  3105. t.object_filename = line.FileName;
  3106. t.source.filename = line.FileName;
  3107. t.source.line = line.LineNumber;
  3108. t.source.col = offset;
  3109. }
  3110. t.source.function = name;
  3111. t.object_filename = "";
  3112. t.object_function = name;
  3113. return t;
  3114. }
  3115. DWORD machine_type() const { return image_type; }
  3116. private:
  3117. DWORD image_type;
  3118. };
  3119. #endif
  3120. class TraceResolver : public TraceResolverImpl<system_tag::current_tag> {};
  3121. /*************** CODE SNIPPET ***************/
  3122. class SourceFile {
  3123. public:
  3124. typedef std::vector<std::pair<unsigned, std::string>> lines_t;
  3125. SourceFile() {}
  3126. SourceFile(const std::string &path) {
  3127. // 1. If BACKWARD_CXX_SOURCE_PREFIXES is set then assume it contains
  3128. // a colon-separated list of path prefixes. Try prepending each
  3129. // to the given path until a valid file is found.
  3130. const std::vector<std::string> &prefixes = get_paths_from_env_variable();
  3131. for (size_t i = 0; i < prefixes.size(); ++i) {
  3132. // Double slashes (//) should not be a problem.
  3133. std::string new_path = prefixes[i] + '/' + path;
  3134. _file.reset(new std::ifstream(new_path.c_str()));
  3135. if (is_open())
  3136. break;
  3137. }
  3138. // 2. If no valid file found then fallback to opening the path as-is.
  3139. if (!_file || !is_open()) {
  3140. _file.reset(new std::ifstream(path.c_str()));
  3141. }
  3142. }
  3143. bool is_open() const { return _file->is_open(); }
  3144. lines_t &get_lines(unsigned line_start, unsigned line_count, lines_t &lines) {
  3145. using namespace std;
  3146. // This function make uses of the dumbest algo ever:
  3147. // 1) seek(0)
  3148. // 2) read lines one by one and discard until line_start
  3149. // 3) read line one by one until line_start + line_count
  3150. //
  3151. // If you are getting snippets many time from the same file, it is
  3152. // somewhat a waste of CPU, feel free to benchmark and propose a
  3153. // better solution ;)
  3154. _file->clear();
  3155. _file->seekg(0);
  3156. string line;
  3157. unsigned line_idx;
  3158. for (line_idx = 1; line_idx < line_start; ++line_idx) {
  3159. std::getline(*_file, line);
  3160. if (!*_file) {
  3161. return lines;
  3162. }
  3163. }
  3164. // think of it like a lambda in C++98 ;)
  3165. // but look, I will reuse it two times!
  3166. // What a good boy am I.
  3167. struct isspace {
  3168. bool operator()(char c) { return std::isspace(c); }
  3169. };
  3170. bool started = false;
  3171. for (; line_idx < line_start + line_count; ++line_idx) {
  3172. getline(*_file, line);
  3173. if (!*_file) {
  3174. return lines;
  3175. }
  3176. if (!started) {
  3177. if (std::find_if(line.begin(), line.end(), not_isspace()) == line.end())
  3178. continue;
  3179. started = true;
  3180. }
  3181. lines.push_back(make_pair(line_idx, line));
  3182. }
  3183. lines.erase(
  3184. std::find_if(lines.rbegin(), lines.rend(), not_isempty()).base(),
  3185. lines.end());
  3186. return lines;
  3187. }
  3188. lines_t get_lines(unsigned line_start, unsigned line_count) {
  3189. lines_t lines;
  3190. return get_lines(line_start, line_count, lines);
  3191. }
  3192. // there is no find_if_not in C++98, lets do something crappy to
  3193. // workaround.
  3194. struct not_isspace {
  3195. bool operator()(char c) { return !std::isspace(c); }
  3196. };
  3197. // and define this one here because C++98 is not happy with local defined
  3198. // struct passed to template functions, fuuuu.
  3199. struct not_isempty {
  3200. bool operator()(const lines_t::value_type &p) {
  3201. return !(std::find_if(p.second.begin(), p.second.end(), not_isspace()) ==
  3202. p.second.end());
  3203. }
  3204. };
  3205. void swap(SourceFile &b) { _file.swap(b._file); }
  3206. #ifdef BACKWARD_ATLEAST_CXX11
  3207. SourceFile(SourceFile &&from) : _file(nullptr) { swap(from); }
  3208. SourceFile &operator=(SourceFile &&from) {
  3209. swap(from);
  3210. return *this;
  3211. }
  3212. #else
  3213. explicit SourceFile(const SourceFile &from) {
  3214. // some sort of poor man's move semantic.
  3215. swap(const_cast<SourceFile &>(from));
  3216. }
  3217. SourceFile &operator=(const SourceFile &from) {
  3218. // some sort of poor man's move semantic.
  3219. swap(const_cast<SourceFile &>(from));
  3220. return *this;
  3221. }
  3222. #endif
  3223. private:
  3224. details::handle<std::ifstream *, details::default_delete<std::ifstream *>>
  3225. _file;
  3226. std::vector<std::string> get_paths_from_env_variable_impl() {
  3227. std::vector<std::string> paths;
  3228. const char *prefixes_str = std::getenv("BACKWARD_CXX_SOURCE_PREFIXES");
  3229. if (prefixes_str && prefixes_str[0]) {
  3230. paths = details::split_source_prefixes(prefixes_str);
  3231. }
  3232. return paths;
  3233. }
  3234. const std::vector<std::string> &get_paths_from_env_variable() {
  3235. static std::vector<std::string> paths = get_paths_from_env_variable_impl();
  3236. return paths;
  3237. }
  3238. #ifdef BACKWARD_ATLEAST_CXX11
  3239. SourceFile(const SourceFile &) = delete;
  3240. SourceFile &operator=(const SourceFile &) = delete;
  3241. #endif
  3242. };
  3243. class SnippetFactory {
  3244. public:
  3245. typedef SourceFile::lines_t lines_t;
  3246. lines_t get_snippet(const std::string &filename, unsigned line_start,
  3247. unsigned context_size) {
  3248. SourceFile &src_file = get_src_file(filename);
  3249. unsigned start = line_start - context_size / 2;
  3250. return src_file.get_lines(start, context_size);
  3251. }
  3252. lines_t get_combined_snippet(const std::string &filename_a, unsigned line_a,
  3253. const std::string &filename_b, unsigned line_b,
  3254. unsigned context_size) {
  3255. SourceFile &src_file_a = get_src_file(filename_a);
  3256. SourceFile &src_file_b = get_src_file(filename_b);
  3257. lines_t lines =
  3258. src_file_a.get_lines(line_a - context_size / 4, context_size / 2);
  3259. src_file_b.get_lines(line_b - context_size / 4, context_size / 2, lines);
  3260. return lines;
  3261. }
  3262. lines_t get_coalesced_snippet(const std::string &filename, unsigned line_a,
  3263. unsigned line_b, unsigned context_size) {
  3264. SourceFile &src_file = get_src_file(filename);
  3265. using std::max;
  3266. using std::min;
  3267. unsigned a = min(line_a, line_b);
  3268. unsigned b = max(line_a, line_b);
  3269. if ((b - a) < (context_size / 3)) {
  3270. return src_file.get_lines((a + b - context_size + 1) / 2, context_size);
  3271. }
  3272. lines_t lines = src_file.get_lines(a - context_size / 4, context_size / 2);
  3273. src_file.get_lines(b - context_size / 4, context_size / 2, lines);
  3274. return lines;
  3275. }
  3276. private:
  3277. typedef details::hashtable<std::string, SourceFile>::type src_files_t;
  3278. src_files_t _src_files;
  3279. SourceFile &get_src_file(const std::string &filename) {
  3280. src_files_t::iterator it = _src_files.find(filename);
  3281. if (it != _src_files.end()) {
  3282. return it->second;
  3283. }
  3284. SourceFile &new_src_file = _src_files[filename];
  3285. new_src_file = SourceFile(filename);
  3286. return new_src_file;
  3287. }
  3288. };
  3289. /*************** PRINTER ***************/
  3290. namespace ColorMode {
  3291. enum type { automatic, never, always };
  3292. }
  3293. class cfile_streambuf : public std::streambuf {
  3294. public:
  3295. cfile_streambuf(FILE *_sink) : sink(_sink) {}
  3296. int_type underflow() override { return traits_type::eof(); }
  3297. int_type overflow(int_type ch) override {
  3298. if (traits_type::not_eof(ch) && fwrite(&ch, sizeof ch, 1, sink) == 1) {
  3299. return ch;
  3300. }
  3301. return traits_type::eof();
  3302. }
  3303. std::streamsize xsputn(const char_type *s, std::streamsize count) override {
  3304. return static_cast<std::streamsize>(
  3305. fwrite(s, sizeof *s, static_cast<size_t>(count), sink));
  3306. }
  3307. #ifdef BACKWARD_ATLEAST_CXX11
  3308. public:
  3309. cfile_streambuf(const cfile_streambuf &) = delete;
  3310. cfile_streambuf &operator=(const cfile_streambuf &) = delete;
  3311. #else
  3312. private:
  3313. cfile_streambuf(const cfile_streambuf &);
  3314. cfile_streambuf &operator=(const cfile_streambuf &);
  3315. #endif
  3316. private:
  3317. FILE *sink;
  3318. std::vector<char> buffer;
  3319. };
  3320. #ifdef BACKWARD_SYSTEM_LINUX
  3321. namespace Color {
  3322. enum type { yellow = 33, purple = 35, reset = 39 };
  3323. } // namespace Color
  3324. class Colorize {
  3325. public:
  3326. Colorize(std::ostream &os) : _os(os), _reset(false), _enabled(false) {}
  3327. void activate(ColorMode::type mode) { _enabled = mode == ColorMode::always; }
  3328. void activate(ColorMode::type mode, FILE *fp) { activate(mode, fileno(fp)); }
  3329. void set_color(Color::type ccode) {
  3330. if (!_enabled)
  3331. return;
  3332. // I assume that the terminal can handle basic colors. Seriously I
  3333. // don't want to deal with all the termcap shit.
  3334. _os << "\033[" << static_cast<int>(ccode) << "m";
  3335. _reset = (ccode != Color::reset);
  3336. }
  3337. ~Colorize() {
  3338. if (_reset) {
  3339. set_color(Color::reset);
  3340. }
  3341. }
  3342. private:
  3343. void activate(ColorMode::type mode, int fd) {
  3344. activate(mode == ColorMode::automatic && isatty(fd) ? ColorMode::always
  3345. : mode);
  3346. }
  3347. std::ostream &_os;
  3348. bool _reset;
  3349. bool _enabled;
  3350. };
  3351. #else // ndef BACKWARD_SYSTEM_LINUX
  3352. namespace Color {
  3353. enum type { yellow = 0, purple = 0, reset = 0 };
  3354. } // namespace Color
  3355. class Colorize {
  3356. public:
  3357. Colorize(std::ostream &) {}
  3358. void activate(ColorMode::type) {}
  3359. void activate(ColorMode::type, FILE *) {}
  3360. void set_color(Color::type) {}
  3361. };
  3362. #endif // BACKWARD_SYSTEM_LINUX
  3363. class Printer {
  3364. public:
  3365. bool snippet;
  3366. ColorMode::type color_mode;
  3367. bool address;
  3368. bool object;
  3369. int inliner_context_size;
  3370. int trace_context_size;
  3371. Printer()
  3372. : snippet(true), color_mode(ColorMode::automatic), address(false),
  3373. object(false), inliner_context_size(5), trace_context_size(7) {}
  3374. template <typename ST> FILE *print(ST &st, FILE *fp = stderr) {
  3375. cfile_streambuf obuf(fp);
  3376. std::ostream os(&obuf);
  3377. Colorize colorize(os);
  3378. colorize.activate(color_mode, fp);
  3379. print_stacktrace(st, os, colorize);
  3380. return fp;
  3381. }
  3382. template <typename ST> std::ostream &print(ST &st, std::ostream &os) {
  3383. Colorize colorize(os);
  3384. colorize.activate(color_mode);
  3385. print_stacktrace(st, os, colorize);
  3386. return os;
  3387. }
  3388. template <typename IT>
  3389. FILE *print(IT begin, IT end, FILE *fp = stderr, size_t thread_id = 0) {
  3390. cfile_streambuf obuf(fp);
  3391. std::ostream os(&obuf);
  3392. Colorize colorize(os);
  3393. colorize.activate(color_mode, fp);
  3394. print_stacktrace(begin, end, os, thread_id, colorize);
  3395. return fp;
  3396. }
  3397. template <typename IT>
  3398. std::ostream &print(IT begin, IT end, std::ostream &os,
  3399. size_t thread_id = 0) {
  3400. Colorize colorize(os);
  3401. colorize.activate(color_mode);
  3402. print_stacktrace(begin, end, os, thread_id, colorize);
  3403. return os;
  3404. }
  3405. TraceResolver const &resolver() const { return _resolver; }
  3406. private:
  3407. TraceResolver _resolver;
  3408. SnippetFactory _snippets;
  3409. template <typename ST>
  3410. void print_stacktrace(ST &st, std::ostream &os, Colorize &colorize) {
  3411. print_header(os, st.thread_id());
  3412. _resolver.load_stacktrace(st);
  3413. for (size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
  3414. print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize);
  3415. }
  3416. }
  3417. template <typename IT>
  3418. void print_stacktrace(IT begin, IT end, std::ostream &os, size_t thread_id,
  3419. Colorize &colorize) {
  3420. print_header(os, thread_id);
  3421. for (; begin != end; ++begin) {
  3422. print_trace(os, *begin, colorize);
  3423. }
  3424. }
  3425. void print_header(std::ostream &os, size_t thread_id) {
  3426. os << "Stack trace (most recent call last)";
  3427. if (thread_id) {
  3428. os << " in thread " << thread_id;
  3429. }
  3430. os << ":\n";
  3431. }
  3432. void print_trace(std::ostream &os, const ResolvedTrace &trace,
  3433. Colorize &colorize) {
  3434. os << "#" << std::left << std::setw(2) << trace.idx << std::right;
  3435. bool already_indented = true;
  3436. if (!trace.source.filename.size() || object) {
  3437. os << " \"" << trace.object_filename << "\", at " << trace.addr
  3438. << ", in " << trace.object_function << "\n";
  3439. already_indented = false;
  3440. }
  3441. for (size_t inliner_idx = trace.inliners.size(); inliner_idx > 0;
  3442. --inliner_idx) {
  3443. if (!already_indented) {
  3444. os << " ";
  3445. }
  3446. const ResolvedTrace::SourceLoc &inliner_loc =
  3447. trace.inliners[inliner_idx - 1];
  3448. print_source_loc(os, " | ", inliner_loc);
  3449. if (snippet) {
  3450. print_snippet(os, " | ", inliner_loc, colorize, Color::purple,
  3451. inliner_context_size);
  3452. }
  3453. already_indented = false;
  3454. }
  3455. if (trace.source.filename.size()) {
  3456. if (!already_indented) {
  3457. os << " ";
  3458. }
  3459. print_source_loc(os, " ", trace.source, trace.addr);
  3460. if (snippet) {
  3461. print_snippet(os, " ", trace.source, colorize, Color::yellow,
  3462. trace_context_size);
  3463. }
  3464. }
  3465. }
  3466. void print_snippet(std::ostream &os, const char *indent,
  3467. const ResolvedTrace::SourceLoc &source_loc,
  3468. Colorize &colorize, Color::type color_code,
  3469. int context_size) {
  3470. using namespace std;
  3471. typedef SnippetFactory::lines_t lines_t;
  3472. lines_t lines = _snippets.get_snippet(source_loc.filename, source_loc.line,
  3473. static_cast<unsigned>(context_size));
  3474. for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) {
  3475. if (it->first == source_loc.line) {
  3476. colorize.set_color(color_code);
  3477. os << indent << ">";
  3478. } else {
  3479. os << indent << " ";
  3480. }
  3481. os << std::setw(4) << it->first << ": " << it->second << "\n";
  3482. if (it->first == source_loc.line) {
  3483. colorize.set_color(Color::reset);
  3484. }
  3485. }
  3486. }
  3487. void print_source_loc(std::ostream &os, const char *indent,
  3488. const ResolvedTrace::SourceLoc &source_loc,
  3489. void *addr = nullptr) {
  3490. os << indent << "Source \"" << source_loc.filename << "\", line "
  3491. << source_loc.line << ", in " << source_loc.function;
  3492. if (address && addr != nullptr) {
  3493. os << " [" << addr << "]";
  3494. }
  3495. os << "\n";
  3496. }
  3497. };
  3498. /*************** SIGNALS HANDLING ***************/
  3499. #if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
  3500. class SignalHandling {
  3501. public:
  3502. static std::vector<int> make_default_signals() {
  3503. const int posix_signals[] = {
  3504. // Signals for which the default action is "Core".
  3505. SIGABRT, // Abort signal from abort(3)
  3506. SIGBUS, // Bus error (bad memory access)
  3507. SIGFPE, // Floating point exception
  3508. SIGILL, // Illegal Instruction
  3509. SIGIOT, // IOT trap. A synonym for SIGABRT
  3510. SIGQUIT, // Quit from keyboard
  3511. SIGSEGV, // Invalid memory reference
  3512. SIGSYS, // Bad argument to routine (SVr4)
  3513. SIGTRAP, // Trace/breakpoint trap
  3514. SIGXCPU, // CPU time limit exceeded (4.2BSD)
  3515. SIGXFSZ, // File size limit exceeded (4.2BSD)
  3516. #if defined(BACKWARD_SYSTEM_DARWIN)
  3517. SIGEMT, // emulation instruction executed
  3518. #endif
  3519. };
  3520. return std::vector<int>(posix_signals,
  3521. posix_signals +
  3522. sizeof posix_signals / sizeof posix_signals[0]);
  3523. }
  3524. SignalHandling(const std::vector<int> &posix_signals = make_default_signals())
  3525. : _loaded(false) {
  3526. bool success = true;
  3527. const size_t stack_size = 1024 * 1024 * 8;
  3528. _stack_content.reset(static_cast<char *>(malloc(stack_size)));
  3529. if (_stack_content) {
  3530. stack_t ss;
  3531. ss.ss_sp = _stack_content.get();
  3532. ss.ss_size = stack_size;
  3533. ss.ss_flags = 0;
  3534. if (sigaltstack(&ss, nullptr) < 0) {
  3535. success = false;
  3536. }
  3537. } else {
  3538. success = false;
  3539. }
  3540. for (size_t i = 0; i < posix_signals.size(); ++i) {
  3541. struct sigaction action;
  3542. memset(&action, 0, sizeof action);
  3543. action.sa_flags =
  3544. static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
  3545. sigfillset(&action.sa_mask);
  3546. sigdelset(&action.sa_mask, posix_signals[i]);
  3547. #if defined(__clang__)
  3548. #pragma clang diagnostic push
  3549. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  3550. #endif
  3551. action.sa_sigaction = &sig_handler;
  3552. #if defined(__clang__)
  3553. #pragma clang diagnostic pop
  3554. #endif
  3555. int r = sigaction(posix_signals[i], &action, nullptr);
  3556. if (r < 0)
  3557. success = false;
  3558. }
  3559. _loaded = success;
  3560. }
  3561. bool loaded() const { return _loaded; }
  3562. static void handleSignal(int, siginfo_t *info, void *_ctx) {
  3563. ucontext_t *uctx = static_cast<ucontext_t *>(_ctx);
  3564. StackTrace st;
  3565. void *error_addr = nullptr;
  3566. #ifdef REG_RIP // x86_64
  3567. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
  3568. #elif defined(REG_EIP) // x86_32
  3569. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
  3570. #elif defined(__arm__)
  3571. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.arm_pc);
  3572. #elif defined(__aarch64__)
  3573. #if defined(__APPLE__)
  3574. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__pc);
  3575. #else
  3576. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.pc);
  3577. #endif
  3578. #elif defined(__mips__)
  3579. error_addr = reinterpret_cast<void *>(
  3580. reinterpret_cast<struct sigcontext *>(&uctx->uc_mcontext)->sc_pc);
  3581. #elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
  3582. defined(__POWERPC__)
  3583. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.regs->nip);
  3584. #elif defined(__s390x__)
  3585. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.psw.addr);
  3586. #elif defined(__APPLE__) && defined(__x86_64__)
  3587. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__rip);
  3588. #elif defined(__APPLE__)
  3589. error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__eip);
  3590. #else
  3591. #warning ":/ sorry, ain't know no nothing none not of your architecture!"
  3592. #endif
  3593. if (error_addr) {
  3594. st.load_from(error_addr, 32, reinterpret_cast<void *>(uctx),
  3595. info->si_addr);
  3596. } else {
  3597. st.load_here(32, reinterpret_cast<void *>(uctx), info->si_addr);
  3598. }
  3599. Printer printer;
  3600. printer.address = true;
  3601. printer.print(st, stderr);
  3602. #if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
  3603. psiginfo(info, nullptr);
  3604. #else
  3605. (void)info;
  3606. #endif
  3607. }
  3608. private:
  3609. details::handle<char *> _stack_content;
  3610. bool _loaded;
  3611. #ifdef __GNUC__
  3612. __attribute__((noreturn))
  3613. #endif
  3614. static void
  3615. sig_handler(int signo, siginfo_t *info, void *_ctx) {
  3616. handleSignal(signo, info, _ctx);
  3617. // try to forward the signal.
  3618. raise(info->si_signo);
  3619. // terminate the process immediately.
  3620. puts("watf? exit");
  3621. _exit(EXIT_FAILURE);
  3622. }
  3623. };
  3624. #endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
  3625. #ifdef BACKWARD_SYSTEM_WINDOWS
  3626. class SignalHandling {
  3627. public:
  3628. SignalHandling(const std::vector<int> & = std::vector<int>())
  3629. : reporter_thread_([]() {
  3630. /* We handle crashes in a utility thread:
  3631. backward structures and some Windows functions called here
  3632. need stack space, which we do not have when we encounter a
  3633. stack overflow.
  3634. To support reporting stack traces during a stack overflow,
  3635. we create a utility thread at startup, which waits until a
  3636. crash happens or the program exits normally. */
  3637. {
  3638. std::unique_lock<std::mutex> lk(mtx());
  3639. cv().wait(lk, [] { return crashed() != crash_status::running; });
  3640. }
  3641. if (crashed() == crash_status::crashed) {
  3642. handle_stacktrace(skip_recs());
  3643. }
  3644. {
  3645. std::unique_lock<std::mutex> lk(mtx());
  3646. crashed() = crash_status::ending;
  3647. }
  3648. cv().notify_one();
  3649. }) {
  3650. SetUnhandledExceptionFilter(crash_handler);
  3651. signal(SIGABRT, signal_handler);
  3652. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  3653. std::set_terminate(&terminator);
  3654. std::set_unexpected(&terminator);
  3655. _set_purecall_handler(&terminator);
  3656. _set_invalid_parameter_handler(&invalid_parameter_handler);
  3657. }
  3658. bool loaded() const { return true; }
  3659. ~SignalHandling() {
  3660. {
  3661. std::unique_lock<std::mutex> lk(mtx());
  3662. crashed() = crash_status::normal_exit;
  3663. }
  3664. cv().notify_one();
  3665. reporter_thread_.join();
  3666. }
  3667. private:
  3668. static CONTEXT *ctx() {
  3669. static CONTEXT data;
  3670. return &data;
  3671. }
  3672. enum class crash_status { running, crashed, normal_exit, ending };
  3673. static crash_status &crashed() {
  3674. static crash_status data;
  3675. return data;
  3676. }
  3677. static std::mutex &mtx() {
  3678. static std::mutex data;
  3679. return data;
  3680. }
  3681. static std::condition_variable &cv() {
  3682. static std::condition_variable data;
  3683. return data;
  3684. }
  3685. static HANDLE &thread_handle() {
  3686. static HANDLE handle;
  3687. return handle;
  3688. }
  3689. std::thread reporter_thread_;
  3690. // TODO: how not to hardcode these?
  3691. static const constexpr int signal_skip_recs =
  3692. #ifdef __clang__
  3693. // With clang, RtlCaptureContext also captures the stack frame of the
  3694. // current function Below that, there ar 3 internal Windows functions
  3695. 4
  3696. #else
  3697. // With MSVC cl, RtlCaptureContext misses the stack frame of the current
  3698. // function The first entries during StackWalk are the 3 internal Windows
  3699. // functions
  3700. 3
  3701. #endif
  3702. ;
  3703. static int &skip_recs() {
  3704. static int data;
  3705. return data;
  3706. }
  3707. static inline void terminator() {
  3708. crash_handler(signal_skip_recs);
  3709. abort();
  3710. }
  3711. static inline void signal_handler(int) {
  3712. crash_handler(signal_skip_recs);
  3713. abort();
  3714. }
  3715. static inline void __cdecl invalid_parameter_handler(const wchar_t *,
  3716. const wchar_t *,
  3717. const wchar_t *,
  3718. unsigned int,
  3719. uintptr_t) {
  3720. crash_handler(signal_skip_recs);
  3721. abort();
  3722. }
  3723. NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) {
  3724. // The exception info supplies a trace from exactly where the issue was,
  3725. // no need to skip records
  3726. crash_handler(0, info->ContextRecord);
  3727. return EXCEPTION_CONTINUE_SEARCH;
  3728. }
  3729. NOINLINE static void crash_handler(int skip, CONTEXT *ct = nullptr) {
  3730. if (ct == nullptr) {
  3731. RtlCaptureContext(ctx());
  3732. } else {
  3733. memcpy(ctx(), ct, sizeof(CONTEXT));
  3734. }
  3735. DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
  3736. GetCurrentProcess(), &thread_handle(), 0, FALSE,
  3737. DUPLICATE_SAME_ACCESS);
  3738. skip_recs() = skip;
  3739. {
  3740. std::unique_lock<std::mutex> lk(mtx());
  3741. crashed() = crash_status::crashed;
  3742. }
  3743. cv().notify_one();
  3744. {
  3745. std::unique_lock<std::mutex> lk(mtx());
  3746. cv().wait(lk, [] { return crashed() != crash_status::crashed; });
  3747. }
  3748. }
  3749. static void handle_stacktrace(int skip_frames = 0) {
  3750. // printer creates the TraceResolver, which can supply us a machine type
  3751. // for stack walking. Without this, StackTrace can only guess using some
  3752. // macros.
  3753. // StackTrace also requires that the PDBs are already loaded, which is done
  3754. // in the constructor of TraceResolver
  3755. Printer printer;
  3756. StackTrace st;
  3757. st.set_machine_type(printer.resolver().machine_type());
  3758. st.set_context(ctx());
  3759. st.set_thread_handle(thread_handle());
  3760. st.load_here(32 + skip_frames);
  3761. st.skip_n_firsts(skip_frames);
  3762. printer.address = true;
  3763. printer.print(st, std::cerr);
  3764. }
  3765. };
  3766. #endif // BACKWARD_SYSTEM_WINDOWS
  3767. #ifdef BACKWARD_SYSTEM_UNKNOWN
  3768. class SignalHandling {
  3769. public:
  3770. SignalHandling(const std::vector<int> & = std::vector<int>()) {}
  3771. bool init() { return false; }
  3772. bool loaded() { return false; }
  3773. };
  3774. #endif // BACKWARD_SYSTEM_UNKNOWN
  3775. } // namespace backward
  3776. #endif /* H_GUARD */