You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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