2
0

jeprof.in 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510
  1. #! /usr/bin/env perl
  2. # Copyright (c) 1998-2007, Google Inc.
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. # ---
  31. # Program for printing the profile generated by common/profiler.cc,
  32. # or by the heap profiler (common/debugallocation.cc)
  33. #
  34. # The profile contains a sequence of entries of the form:
  35. # <count> <stack trace>
  36. # This program parses the profile, and generates user-readable
  37. # output.
  38. #
  39. # Examples:
  40. #
  41. # % tools/jeprof "program" "profile"
  42. # Enters "interactive" mode
  43. #
  44. # % tools/jeprof --text "program" "profile"
  45. # Generates one line per procedure
  46. #
  47. # % tools/jeprof --gv "program" "profile"
  48. # Generates annotated call-graph and displays via "gv"
  49. #
  50. # % tools/jeprof --gv --focus=Mutex "program" "profile"
  51. # Restrict to code paths that involve an entry that matches "Mutex"
  52. #
  53. # % tools/jeprof --gv --focus=Mutex --ignore=string "program" "profile"
  54. # Restrict to code paths that involve an entry that matches "Mutex"
  55. # and does not match "string"
  56. #
  57. # % tools/jeprof --list=IBF_CheckDocid "program" "profile"
  58. # Generates disassembly listing of all routines with at least one
  59. # sample that match the --list=<regexp> pattern. The listing is
  60. # annotated with the flat and cumulative sample counts at each line.
  61. #
  62. # % tools/jeprof --disasm=IBF_CheckDocid "program" "profile"
  63. # Generates disassembly listing of all routines with at least one
  64. # sample that match the --disasm=<regexp> pattern. The listing is
  65. # annotated with the flat and cumulative sample counts at each PC value.
  66. #
  67. # TODO: Use color to indicate files?
  68. use strict;
  69. use warnings;
  70. use Getopt::Long;
  71. my $JEPROF_VERSION = "@jemalloc_version@";
  72. my $PPROF_VERSION = "2.0";
  73. # These are the object tools we use which can come from a
  74. # user-specified location using --tools, from the JEPROF_TOOLS
  75. # environment variable, or from the environment.
  76. my %obj_tool_map = (
  77. "objdump" => "objdump",
  78. "nm" => "nm",
  79. "addr2line" => "addr2line",
  80. "c++filt" => "c++filt",
  81. ## ConfigureObjTools may add architecture-specific entries:
  82. #"nm_pdb" => "nm-pdb", # for reading windows (PDB-format) executables
  83. #"addr2line_pdb" => "addr2line-pdb", # ditto
  84. #"otool" => "otool", # equivalent of objdump on OS X
  85. );
  86. # NOTE: these are lists, so you can put in commandline flags if you want.
  87. my @DOT = ("dot"); # leave non-absolute, since it may be in /usr/local
  88. my @GV = ("gv");
  89. my @EVINCE = ("evince"); # could also be xpdf or perhaps acroread
  90. my @KCACHEGRIND = ("kcachegrind");
  91. my @PS2PDF = ("ps2pdf");
  92. # These are used for dynamic profiles
  93. my @URL_FETCHER = ("curl", "-s");
  94. # These are the web pages that servers need to support for dynamic profiles
  95. my $HEAP_PAGE = "/pprof/heap";
  96. my $PROFILE_PAGE = "/pprof/profile"; # must support cgi-param "?seconds=#"
  97. my $PMUPROFILE_PAGE = "/pprof/pmuprofile(?:\\?.*)?"; # must support cgi-param
  98. # ?seconds=#&event=x&period=n
  99. my $GROWTH_PAGE = "/pprof/growth";
  100. my $CONTENTION_PAGE = "/pprof/contention";
  101. my $WALL_PAGE = "/pprof/wall(?:\\?.*)?"; # accepts options like namefilter
  102. my $FILTEREDPROFILE_PAGE = "/pprof/filteredprofile(?:\\?.*)?";
  103. my $CENSUSPROFILE_PAGE = "/pprof/censusprofile(?:\\?.*)?"; # must support cgi-param
  104. # "?seconds=#",
  105. # "?tags_regexp=#" and
  106. # "?type=#".
  107. my $SYMBOL_PAGE = "/pprof/symbol"; # must support symbol lookup via POST
  108. my $PROGRAM_NAME_PAGE = "/pprof/cmdline";
  109. # These are the web pages that can be named on the command line.
  110. # All the alternatives must begin with /.
  111. my $PROFILES = "($HEAP_PAGE|$PROFILE_PAGE|$PMUPROFILE_PAGE|" .
  112. "$GROWTH_PAGE|$CONTENTION_PAGE|$WALL_PAGE|" .
  113. "$FILTEREDPROFILE_PAGE|$CENSUSPROFILE_PAGE)";
  114. # default binary name
  115. my $UNKNOWN_BINARY = "(unknown)";
  116. # There is a pervasive dependency on the length (in hex characters,
  117. # i.e., nibbles) of an address, distinguishing between 32-bit and
  118. # 64-bit profiles. To err on the safe size, default to 64-bit here:
  119. my $address_length = 16;
  120. my $dev_null = "/dev/null";
  121. if (! -e $dev_null && $^O =~ /MSWin/) { # $^O is the OS perl was built for
  122. $dev_null = "nul";
  123. }
  124. # A list of paths to search for shared object files
  125. my @prefix_list = ();
  126. # Special routine name that should not have any symbols.
  127. # Used as separator to parse "addr2line -i" output.
  128. my $sep_symbol = '_fini';
  129. my $sep_address = undef;
  130. ##### Argument parsing #####
  131. sub usage_string {
  132. return <<EOF;
  133. Usage:
  134. jeprof [options] <program> <profiles>
  135. <profiles> is a space separated list of profile names.
  136. jeprof [options] <symbolized-profiles>
  137. <symbolized-profiles> is a list of profile files where each file contains
  138. the necessary symbol mappings as well as profile data (likely generated
  139. with --raw).
  140. jeprof [options] <profile>
  141. <profile> is a remote form. Symbols are obtained from host:port$SYMBOL_PAGE
  142. Each name can be:
  143. /path/to/profile - a path to a profile file
  144. host:port[/<service>] - a location of a service to get profile from
  145. The /<service> can be $HEAP_PAGE, $PROFILE_PAGE, /pprof/pmuprofile,
  146. $GROWTH_PAGE, $CONTENTION_PAGE, /pprof/wall,
  147. $CENSUSPROFILE_PAGE, or /pprof/filteredprofile.
  148. For instance:
  149. jeprof http://myserver.com:80$HEAP_PAGE
  150. If /<service> is omitted, the service defaults to $PROFILE_PAGE (cpu profiling).
  151. jeprof --symbols <program>
  152. Maps addresses to symbol names. In this mode, stdin should be a
  153. list of library mappings, in the same format as is found in the heap-
  154. and cpu-profile files (this loosely matches that of /proc/self/maps
  155. on linux), followed by a list of hex addresses to map, one per line.
  156. For more help with querying remote servers, including how to add the
  157. necessary server-side support code, see this filename (or one like it):
  158. /usr/doc/gperftools-$PPROF_VERSION/pprof_remote_servers.html
  159. Options:
  160. --cum Sort by cumulative data
  161. --base=<base> Subtract <base> from <profile> before display
  162. --interactive Run in interactive mode (interactive "help" gives help) [default]
  163. --seconds=<n> Length of time for dynamic profiles [default=30 secs]
  164. --add_lib=<file> Read additional symbols and line info from the given library
  165. --lib_prefix=<dir> Comma separated list of library path prefixes
  166. Reporting Granularity:
  167. --addresses Report at address level
  168. --lines Report at source line level
  169. --functions Report at function level [default]
  170. --files Report at source file level
  171. Output type:
  172. --text Generate text report
  173. --callgrind Generate callgrind format to stdout
  174. --gv Generate Postscript and display
  175. --evince Generate PDF and display
  176. --web Generate SVG and display
  177. --list=<regexp> Generate source listing of matching routines
  178. --disasm=<regexp> Generate disassembly of matching routines
  179. --symbols Print demangled symbol names found at given addresses
  180. --dot Generate DOT file to stdout
  181. --ps Generate Postcript to stdout
  182. --pdf Generate PDF to stdout
  183. --svg Generate SVG to stdout
  184. --gif Generate GIF to stdout
  185. --raw Generate symbolized jeprof data (useful with remote fetch)
  186. Heap-Profile Options:
  187. --inuse_space Display in-use (mega)bytes [default]
  188. --inuse_objects Display in-use objects
  189. --alloc_space Display allocated (mega)bytes
  190. --alloc_objects Display allocated objects
  191. --show_bytes Display space in bytes
  192. --drop_negative Ignore negative differences
  193. Contention-profile options:
  194. --total_delay Display total delay at each region [default]
  195. --contentions Display number of delays at each region
  196. --mean_delay Display mean delay at each region
  197. Call-graph Options:
  198. --nodecount=<n> Show at most so many nodes [default=80]
  199. --nodefraction=<f> Hide nodes below <f>*total [default=.005]
  200. --edgefraction=<f> Hide edges below <f>*total [default=.001]
  201. --maxdegree=<n> Max incoming/outgoing edges per node [default=8]
  202. --focus=<regexp> Focus on nodes matching <regexp>
  203. --thread=<n> Show profile for thread <n>
  204. --ignore=<regexp> Ignore nodes matching <regexp>
  205. --scale=<n> Set GV scaling [default=0]
  206. --heapcheck Make nodes with non-0 object counts
  207. (i.e. direct leak generators) more visible
  208. Miscellaneous:
  209. --tools=<prefix or binary:fullpath>[,...] \$PATH for object tool pathnames
  210. --test Run unit tests
  211. --help This message
  212. --version Version information
  213. Environment Variables:
  214. JEPROF_TMPDIR Profiles directory. Defaults to \$HOME/jeprof
  215. JEPROF_TOOLS Prefix for object tools pathnames
  216. Examples:
  217. jeprof /bin/ls ls.prof
  218. Enters "interactive" mode
  219. jeprof --text /bin/ls ls.prof
  220. Outputs one line per procedure
  221. jeprof --web /bin/ls ls.prof
  222. Displays annotated call-graph in web browser
  223. jeprof --gv /bin/ls ls.prof
  224. Displays annotated call-graph via 'gv'
  225. jeprof --gv --focus=Mutex /bin/ls ls.prof
  226. Restricts to code paths including a .*Mutex.* entry
  227. jeprof --gv --focus=Mutex --ignore=string /bin/ls ls.prof
  228. Code paths including Mutex but not string
  229. jeprof --list=getdir /bin/ls ls.prof
  230. (Per-line) annotated source listing for getdir()
  231. jeprof --disasm=getdir /bin/ls ls.prof
  232. (Per-PC) annotated disassembly for getdir()
  233. jeprof http://localhost:1234/
  234. Enters "interactive" mode
  235. jeprof --text localhost:1234
  236. Outputs one line per procedure for localhost:1234
  237. jeprof --raw localhost:1234 > ./local.raw
  238. jeprof --text ./local.raw
  239. Fetches a remote profile for later analysis and then
  240. analyzes it in text mode.
  241. EOF
  242. }
  243. sub version_string {
  244. return <<EOF
  245. jeprof (part of jemalloc $JEPROF_VERSION)
  246. based on pprof (part of gperftools $PPROF_VERSION)
  247. Copyright 1998-2007 Google Inc.
  248. This is BSD licensed software; see the source for copying conditions
  249. and license information.
  250. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
  251. PARTICULAR PURPOSE.
  252. EOF
  253. }
  254. sub usage {
  255. my $msg = shift;
  256. print STDERR "$msg\n\n";
  257. print STDERR usage_string();
  258. print STDERR "\nFATAL ERROR: $msg\n"; # just as a reminder
  259. exit(1);
  260. }
  261. sub Init() {
  262. # Setup tmp-file name and handler to clean it up.
  263. # We do this in the very beginning so that we can use
  264. # error() and cleanup() function anytime here after.
  265. $main::tmpfile_sym = "/tmp/jeprof$$.sym";
  266. $main::tmpfile_ps = "/tmp/jeprof$$";
  267. $main::next_tmpfile = 0;
  268. $SIG{'INT'} = \&sighandler;
  269. # Cache from filename/linenumber to source code
  270. $main::source_cache = ();
  271. $main::opt_help = 0;
  272. $main::opt_version = 0;
  273. $main::opt_cum = 0;
  274. $main::opt_base = '';
  275. $main::opt_addresses = 0;
  276. $main::opt_lines = 0;
  277. $main::opt_functions = 0;
  278. $main::opt_files = 0;
  279. $main::opt_lib_prefix = "";
  280. $main::opt_text = 0;
  281. $main::opt_callgrind = 0;
  282. $main::opt_list = "";
  283. $main::opt_disasm = "";
  284. $main::opt_symbols = 0;
  285. $main::opt_gv = 0;
  286. $main::opt_evince = 0;
  287. $main::opt_web = 0;
  288. $main::opt_dot = 0;
  289. $main::opt_ps = 0;
  290. $main::opt_pdf = 0;
  291. $main::opt_gif = 0;
  292. $main::opt_svg = 0;
  293. $main::opt_raw = 0;
  294. $main::opt_nodecount = 80;
  295. $main::opt_nodefraction = 0.005;
  296. $main::opt_edgefraction = 0.001;
  297. $main::opt_maxdegree = 8;
  298. $main::opt_focus = '';
  299. $main::opt_thread = undef;
  300. $main::opt_ignore = '';
  301. $main::opt_scale = 0;
  302. $main::opt_heapcheck = 0;
  303. $main::opt_seconds = 30;
  304. $main::opt_lib = "";
  305. $main::opt_inuse_space = 0;
  306. $main::opt_inuse_objects = 0;
  307. $main::opt_alloc_space = 0;
  308. $main::opt_alloc_objects = 0;
  309. $main::opt_show_bytes = 0;
  310. $main::opt_drop_negative = 0;
  311. $main::opt_interactive = 0;
  312. $main::opt_total_delay = 0;
  313. $main::opt_contentions = 0;
  314. $main::opt_mean_delay = 0;
  315. $main::opt_tools = "";
  316. $main::opt_debug = 0;
  317. $main::opt_test = 0;
  318. # These are undocumented flags used only by unittests.
  319. $main::opt_test_stride = 0;
  320. # Are we using $SYMBOL_PAGE?
  321. $main::use_symbol_page = 0;
  322. # Files returned by TempName.
  323. %main::tempnames = ();
  324. # Type of profile we are dealing with
  325. # Supported types:
  326. # cpu
  327. # heap
  328. # growth
  329. # contention
  330. $main::profile_type = ''; # Empty type means "unknown"
  331. GetOptions("help!" => \$main::opt_help,
  332. "version!" => \$main::opt_version,
  333. "cum!" => \$main::opt_cum,
  334. "base=s" => \$main::opt_base,
  335. "seconds=i" => \$main::opt_seconds,
  336. "add_lib=s" => \$main::opt_lib,
  337. "lib_prefix=s" => \$main::opt_lib_prefix,
  338. "functions!" => \$main::opt_functions,
  339. "lines!" => \$main::opt_lines,
  340. "addresses!" => \$main::opt_addresses,
  341. "files!" => \$main::opt_files,
  342. "text!" => \$main::opt_text,
  343. "callgrind!" => \$main::opt_callgrind,
  344. "list=s" => \$main::opt_list,
  345. "disasm=s" => \$main::opt_disasm,
  346. "symbols!" => \$main::opt_symbols,
  347. "gv!" => \$main::opt_gv,
  348. "evince!" => \$main::opt_evince,
  349. "web!" => \$main::opt_web,
  350. "dot!" => \$main::opt_dot,
  351. "ps!" => \$main::opt_ps,
  352. "pdf!" => \$main::opt_pdf,
  353. "svg!" => \$main::opt_svg,
  354. "gif!" => \$main::opt_gif,
  355. "raw!" => \$main::opt_raw,
  356. "interactive!" => \$main::opt_interactive,
  357. "nodecount=i" => \$main::opt_nodecount,
  358. "nodefraction=f" => \$main::opt_nodefraction,
  359. "edgefraction=f" => \$main::opt_edgefraction,
  360. "maxdegree=i" => \$main::opt_maxdegree,
  361. "focus=s" => \$main::opt_focus,
  362. "thread=s" => \$main::opt_thread,
  363. "ignore=s" => \$main::opt_ignore,
  364. "scale=i" => \$main::opt_scale,
  365. "heapcheck" => \$main::opt_heapcheck,
  366. "inuse_space!" => \$main::opt_inuse_space,
  367. "inuse_objects!" => \$main::opt_inuse_objects,
  368. "alloc_space!" => \$main::opt_alloc_space,
  369. "alloc_objects!" => \$main::opt_alloc_objects,
  370. "show_bytes!" => \$main::opt_show_bytes,
  371. "drop_negative!" => \$main::opt_drop_negative,
  372. "total_delay!" => \$main::opt_total_delay,
  373. "contentions!" => \$main::opt_contentions,
  374. "mean_delay!" => \$main::opt_mean_delay,
  375. "tools=s" => \$main::opt_tools,
  376. "test!" => \$main::opt_test,
  377. "debug!" => \$main::opt_debug,
  378. # Undocumented flags used only by unittests:
  379. "test_stride=i" => \$main::opt_test_stride,
  380. ) || usage("Invalid option(s)");
  381. # Deal with the standard --help and --version
  382. if ($main::opt_help) {
  383. print usage_string();
  384. exit(0);
  385. }
  386. if ($main::opt_version) {
  387. print version_string();
  388. exit(0);
  389. }
  390. # Disassembly/listing/symbols mode requires address-level info
  391. if ($main::opt_disasm || $main::opt_list || $main::opt_symbols) {
  392. $main::opt_functions = 0;
  393. $main::opt_lines = 0;
  394. $main::opt_addresses = 1;
  395. $main::opt_files = 0;
  396. }
  397. # Check heap-profiling flags
  398. if ($main::opt_inuse_space +
  399. $main::opt_inuse_objects +
  400. $main::opt_alloc_space +
  401. $main::opt_alloc_objects > 1) {
  402. usage("Specify at most on of --inuse/--alloc options");
  403. }
  404. # Check output granularities
  405. my $grains =
  406. $main::opt_functions +
  407. $main::opt_lines +
  408. $main::opt_addresses +
  409. $main::opt_files +
  410. 0;
  411. if ($grains > 1) {
  412. usage("Only specify one output granularity option");
  413. }
  414. if ($grains == 0) {
  415. $main::opt_functions = 1;
  416. }
  417. # Check output modes
  418. my $modes =
  419. $main::opt_text +
  420. $main::opt_callgrind +
  421. ($main::opt_list eq '' ? 0 : 1) +
  422. ($main::opt_disasm eq '' ? 0 : 1) +
  423. ($main::opt_symbols == 0 ? 0 : 1) +
  424. $main::opt_gv +
  425. $main::opt_evince +
  426. $main::opt_web +
  427. $main::opt_dot +
  428. $main::opt_ps +
  429. $main::opt_pdf +
  430. $main::opt_svg +
  431. $main::opt_gif +
  432. $main::opt_raw +
  433. $main::opt_interactive +
  434. 0;
  435. if ($modes > 1) {
  436. usage("Only specify one output mode");
  437. }
  438. if ($modes == 0) {
  439. if (-t STDOUT) { # If STDOUT is a tty, activate interactive mode
  440. $main::opt_interactive = 1;
  441. } else {
  442. $main::opt_text = 1;
  443. }
  444. }
  445. if ($main::opt_test) {
  446. RunUnitTests();
  447. # Should not return
  448. exit(1);
  449. }
  450. # Binary name and profile arguments list
  451. $main::prog = "";
  452. @main::pfile_args = ();
  453. # Remote profiling without a binary (using $SYMBOL_PAGE instead)
  454. if (@ARGV > 0) {
  455. if (IsProfileURL($ARGV[0])) {
  456. $main::use_symbol_page = 1;
  457. } elsif (IsSymbolizedProfileFile($ARGV[0])) {
  458. $main::use_symbolized_profile = 1;
  459. $main::prog = $UNKNOWN_BINARY; # will be set later from the profile file
  460. }
  461. }
  462. if ($main::use_symbol_page || $main::use_symbolized_profile) {
  463. # We don't need a binary!
  464. my %disabled = ('--lines' => $main::opt_lines,
  465. '--disasm' => $main::opt_disasm);
  466. for my $option (keys %disabled) {
  467. usage("$option cannot be used without a binary") if $disabled{$option};
  468. }
  469. # Set $main::prog later...
  470. scalar(@ARGV) || usage("Did not specify profile file");
  471. } elsif ($main::opt_symbols) {
  472. # --symbols needs a binary-name (to run nm on, etc) but not profiles
  473. $main::prog = shift(@ARGV) || usage("Did not specify program");
  474. } else {
  475. $main::prog = shift(@ARGV) || usage("Did not specify program");
  476. scalar(@ARGV) || usage("Did not specify profile file");
  477. }
  478. # Parse profile file/location arguments
  479. foreach my $farg (@ARGV) {
  480. if ($farg =~ m/(.*)\@([0-9]+)(|\/.*)$/ ) {
  481. my $machine = $1;
  482. my $num_machines = $2;
  483. my $path = $3;
  484. for (my $i = 0; $i < $num_machines; $i++) {
  485. unshift(@main::pfile_args, "$i.$machine$path");
  486. }
  487. } else {
  488. unshift(@main::pfile_args, $farg);
  489. }
  490. }
  491. if ($main::use_symbol_page) {
  492. unless (IsProfileURL($main::pfile_args[0])) {
  493. error("The first profile should be a remote form to use $SYMBOL_PAGE\n");
  494. }
  495. CheckSymbolPage();
  496. $main::prog = FetchProgramName();
  497. } elsif (!$main::use_symbolized_profile) { # may not need objtools!
  498. ConfigureObjTools($main::prog)
  499. }
  500. # Break the opt_lib_prefix into the prefix_list array
  501. @prefix_list = split (',', $main::opt_lib_prefix);
  502. # Remove trailing / from the prefixes, in the list to prevent
  503. # searching things like /my/path//lib/mylib.so
  504. foreach (@prefix_list) {
  505. s|/+$||;
  506. }
  507. }
  508. sub FilterAndPrint {
  509. my ($profile, $symbols, $libs, $thread) = @_;
  510. # Get total data in profile
  511. my $total = TotalProfile($profile);
  512. # Remove uniniteresting stack items
  513. $profile = RemoveUninterestingFrames($symbols, $profile);
  514. # Focus?
  515. if ($main::opt_focus ne '') {
  516. $profile = FocusProfile($symbols, $profile, $main::opt_focus);
  517. }
  518. # Ignore?
  519. if ($main::opt_ignore ne '') {
  520. $profile = IgnoreProfile($symbols, $profile, $main::opt_ignore);
  521. }
  522. my $calls = ExtractCalls($symbols, $profile);
  523. # Reduce profiles to required output granularity, and also clean
  524. # each stack trace so a given entry exists at most once.
  525. my $reduced = ReduceProfile($symbols, $profile);
  526. # Get derived profiles
  527. my $flat = FlatProfile($reduced);
  528. my $cumulative = CumulativeProfile($reduced);
  529. # Print
  530. if (!$main::opt_interactive) {
  531. if ($main::opt_disasm) {
  532. PrintDisassembly($libs, $flat, $cumulative, $main::opt_disasm);
  533. } elsif ($main::opt_list) {
  534. PrintListing($total, $libs, $flat, $cumulative, $main::opt_list, 0);
  535. } elsif ($main::opt_text) {
  536. # Make sure the output is empty when have nothing to report
  537. # (only matters when --heapcheck is given but we must be
  538. # compatible with old branches that did not pass --heapcheck always):
  539. if ($total != 0) {
  540. printf("Total%s: %s %s\n",
  541. (defined($thread) ? " (t$thread)" : ""),
  542. Unparse($total), Units());
  543. }
  544. PrintText($symbols, $flat, $cumulative, -1);
  545. } elsif ($main::opt_raw) {
  546. PrintSymbolizedProfile($symbols, $profile, $main::prog);
  547. } elsif ($main::opt_callgrind) {
  548. PrintCallgrind($calls);
  549. } else {
  550. if (PrintDot($main::prog, $symbols, $profile, $flat, $cumulative, $total)) {
  551. if ($main::opt_gv) {
  552. RunGV(TempName($main::next_tmpfile, "ps"), "");
  553. } elsif ($main::opt_evince) {
  554. RunEvince(TempName($main::next_tmpfile, "pdf"), "");
  555. } elsif ($main::opt_web) {
  556. my $tmp = TempName($main::next_tmpfile, "svg");
  557. RunWeb($tmp);
  558. # The command we run might hand the file name off
  559. # to an already running browser instance and then exit.
  560. # Normally, we'd remove $tmp on exit (right now),
  561. # but fork a child to remove $tmp a little later, so that the
  562. # browser has time to load it first.
  563. delete $main::tempnames{$tmp};
  564. if (fork() == 0) {
  565. sleep 5;
  566. unlink($tmp);
  567. exit(0);
  568. }
  569. }
  570. } else {
  571. cleanup();
  572. exit(1);
  573. }
  574. }
  575. } else {
  576. InteractiveMode($profile, $symbols, $libs, $total);
  577. }
  578. }
  579. sub Main() {
  580. Init();
  581. $main::collected_profile = undef;
  582. @main::profile_files = ();
  583. $main::op_time = time();
  584. # Printing symbols is special and requires a lot less info that most.
  585. if ($main::opt_symbols) {
  586. PrintSymbols(*STDIN); # Get /proc/maps and symbols output from stdin
  587. return;
  588. }
  589. # Fetch all profile data
  590. FetchDynamicProfiles();
  591. # this will hold symbols that we read from the profile files
  592. my $symbol_map = {};
  593. # Read one profile, pick the last item on the list
  594. my $data = ReadProfile($main::prog, pop(@main::profile_files));
  595. my $profile = $data->{profile};
  596. my $pcs = $data->{pcs};
  597. my $libs = $data->{libs}; # Info about main program and shared libraries
  598. $symbol_map = MergeSymbols($symbol_map, $data->{symbols});
  599. # Add additional profiles, if available.
  600. if (scalar(@main::profile_files) > 0) {
  601. foreach my $pname (@main::profile_files) {
  602. my $data2 = ReadProfile($main::prog, $pname);
  603. $profile = AddProfile($profile, $data2->{profile});
  604. $pcs = AddPcs($pcs, $data2->{pcs});
  605. $symbol_map = MergeSymbols($symbol_map, $data2->{symbols});
  606. }
  607. }
  608. # Subtract base from profile, if specified
  609. if ($main::opt_base ne '') {
  610. my $base = ReadProfile($main::prog, $main::opt_base);
  611. $profile = SubtractProfile($profile, $base->{profile});
  612. $pcs = AddPcs($pcs, $base->{pcs});
  613. $symbol_map = MergeSymbols($symbol_map, $base->{symbols});
  614. }
  615. # Collect symbols
  616. my $symbols;
  617. if ($main::use_symbolized_profile) {
  618. $symbols = FetchSymbols($pcs, $symbol_map);
  619. } elsif ($main::use_symbol_page) {
  620. $symbols = FetchSymbols($pcs);
  621. } else {
  622. # TODO(csilvers): $libs uses the /proc/self/maps data from profile1,
  623. # which may differ from the data from subsequent profiles, especially
  624. # if they were run on different machines. Use appropriate libs for
  625. # each pc somehow.
  626. $symbols = ExtractSymbols($libs, $pcs);
  627. }
  628. if (!defined($main::opt_thread)) {
  629. FilterAndPrint($profile, $symbols, $libs);
  630. }
  631. if (defined($data->{threads})) {
  632. foreach my $thread (sort { $a <=> $b } keys(%{$data->{threads}})) {
  633. if (defined($main::opt_thread) &&
  634. ($main::opt_thread eq '*' || $main::opt_thread == $thread)) {
  635. my $thread_profile = $data->{threads}{$thread};
  636. FilterAndPrint($thread_profile, $symbols, $libs, $thread);
  637. }
  638. }
  639. }
  640. cleanup();
  641. exit(0);
  642. }
  643. ##### Entry Point #####
  644. Main();
  645. # Temporary code to detect if we're running on a Goobuntu system.
  646. # These systems don't have the right stuff installed for the special
  647. # Readline libraries to work, so as a temporary workaround, we default
  648. # to using the normal stdio code, rather than the fancier readline-based
  649. # code
  650. sub ReadlineMightFail {
  651. if (-e '/lib/libtermcap.so.2') {
  652. return 0; # libtermcap exists, so readline should be okay
  653. } else {
  654. return 1;
  655. }
  656. }
  657. sub RunGV {
  658. my $fname = shift;
  659. my $bg = shift; # "" or " &" if we should run in background
  660. if (!system(ShellEscape(@GV, "--version") . " >$dev_null 2>&1")) {
  661. # Options using double dash are supported by this gv version.
  662. # Also, turn on noantialias to better handle bug in gv for
  663. # postscript files with large dimensions.
  664. # TODO: Maybe we should not pass the --noantialias flag
  665. # if the gv version is known to work properly without the flag.
  666. system(ShellEscape(@GV, "--scale=$main::opt_scale", "--noantialias", $fname)
  667. . $bg);
  668. } else {
  669. # Old gv version - only supports options that use single dash.
  670. print STDERR ShellEscape(@GV, "-scale", $main::opt_scale) . "\n";
  671. system(ShellEscape(@GV, "-scale", "$main::opt_scale", $fname) . $bg);
  672. }
  673. }
  674. sub RunEvince {
  675. my $fname = shift;
  676. my $bg = shift; # "" or " &" if we should run in background
  677. system(ShellEscape(@EVINCE, $fname) . $bg);
  678. }
  679. sub RunWeb {
  680. my $fname = shift;
  681. print STDERR "Loading web page file:///$fname\n";
  682. if (`uname` =~ /Darwin/) {
  683. # OS X: open will use standard preference for SVG files.
  684. system("/usr/bin/open", $fname);
  685. return;
  686. }
  687. # Some kind of Unix; try generic symlinks, then specific browsers.
  688. # (Stop once we find one.)
  689. # Works best if the browser is already running.
  690. my @alt = (
  691. "/etc/alternatives/gnome-www-browser",
  692. "/etc/alternatives/x-www-browser",
  693. "google-chrome",
  694. "firefox",
  695. );
  696. foreach my $b (@alt) {
  697. if (system($b, $fname) == 0) {
  698. return;
  699. }
  700. }
  701. print STDERR "Could not load web browser.\n";
  702. }
  703. sub RunKcachegrind {
  704. my $fname = shift;
  705. my $bg = shift; # "" or " &" if we should run in background
  706. print STDERR "Starting '@KCACHEGRIND " . $fname . $bg . "'\n";
  707. system(ShellEscape(@KCACHEGRIND, $fname) . $bg);
  708. }
  709. ##### Interactive helper routines #####
  710. sub InteractiveMode {
  711. $| = 1; # Make output unbuffered for interactive mode
  712. my ($orig_profile, $symbols, $libs, $total) = @_;
  713. print STDERR "Welcome to jeprof! For help, type 'help'.\n";
  714. # Use ReadLine if it's installed and input comes from a console.
  715. if ( -t STDIN &&
  716. !ReadlineMightFail() &&
  717. defined(eval {require Term::ReadLine}) ) {
  718. my $term = new Term::ReadLine 'jeprof';
  719. while ( defined ($_ = $term->readline('(jeprof) '))) {
  720. $term->addhistory($_) if /\S/;
  721. if (!InteractiveCommand($orig_profile, $symbols, $libs, $total, $_)) {
  722. last; # exit when we get an interactive command to quit
  723. }
  724. }
  725. } else { # don't have readline
  726. while (1) {
  727. print STDERR "(jeprof) ";
  728. $_ = <STDIN>;
  729. last if ! defined $_ ;
  730. s/\r//g; # turn windows-looking lines into unix-looking lines
  731. # Save some flags that might be reset by InteractiveCommand()
  732. my $save_opt_lines = $main::opt_lines;
  733. if (!InteractiveCommand($orig_profile, $symbols, $libs, $total, $_)) {
  734. last; # exit when we get an interactive command to quit
  735. }
  736. # Restore flags
  737. $main::opt_lines = $save_opt_lines;
  738. }
  739. }
  740. }
  741. # Takes two args: orig profile, and command to run.
  742. # Returns 1 if we should keep going, or 0 if we were asked to quit
  743. sub InteractiveCommand {
  744. my($orig_profile, $symbols, $libs, $total, $command) = @_;
  745. $_ = $command; # just to make future m//'s easier
  746. if (!defined($_)) {
  747. print STDERR "\n";
  748. return 0;
  749. }
  750. if (m/^\s*quit/) {
  751. return 0;
  752. }
  753. if (m/^\s*help/) {
  754. InteractiveHelpMessage();
  755. return 1;
  756. }
  757. # Clear all the mode options -- mode is controlled by "$command"
  758. $main::opt_text = 0;
  759. $main::opt_callgrind = 0;
  760. $main::opt_disasm = 0;
  761. $main::opt_list = 0;
  762. $main::opt_gv = 0;
  763. $main::opt_evince = 0;
  764. $main::opt_cum = 0;
  765. if (m/^\s*(text|top)(\d*)\s*(.*)/) {
  766. $main::opt_text = 1;
  767. my $line_limit = ($2 ne "") ? int($2) : 10;
  768. my $routine;
  769. my $ignore;
  770. ($routine, $ignore) = ParseInteractiveArgs($3);
  771. my $profile = ProcessProfile($total, $orig_profile, $symbols, "", $ignore);
  772. my $reduced = ReduceProfile($symbols, $profile);
  773. # Get derived profiles
  774. my $flat = FlatProfile($reduced);
  775. my $cumulative = CumulativeProfile($reduced);
  776. PrintText($symbols, $flat, $cumulative, $line_limit);
  777. return 1;
  778. }
  779. if (m/^\s*callgrind\s*([^ \n]*)/) {
  780. $main::opt_callgrind = 1;
  781. # Get derived profiles
  782. my $calls = ExtractCalls($symbols, $orig_profile);
  783. my $filename = $1;
  784. if ( $1 eq '' ) {
  785. $filename = TempName($main::next_tmpfile, "callgrind");
  786. }
  787. PrintCallgrind($calls, $filename);
  788. if ( $1 eq '' ) {
  789. RunKcachegrind($filename, " & ");
  790. $main::next_tmpfile++;
  791. }
  792. return 1;
  793. }
  794. if (m/^\s*(web)?list\s*(.+)/) {
  795. my $html = (defined($1) && ($1 eq "web"));
  796. $main::opt_list = 1;
  797. my $routine;
  798. my $ignore;
  799. ($routine, $ignore) = ParseInteractiveArgs($2);
  800. my $profile = ProcessProfile($total, $orig_profile, $symbols, "", $ignore);
  801. my $reduced = ReduceProfile($symbols, $profile);
  802. # Get derived profiles
  803. my $flat = FlatProfile($reduced);
  804. my $cumulative = CumulativeProfile($reduced);
  805. PrintListing($total, $libs, $flat, $cumulative, $routine, $html);
  806. return 1;
  807. }
  808. if (m/^\s*disasm\s*(.+)/) {
  809. $main::opt_disasm = 1;
  810. my $routine;
  811. my $ignore;
  812. ($routine, $ignore) = ParseInteractiveArgs($1);
  813. # Process current profile to account for various settings
  814. my $profile = ProcessProfile($total, $orig_profile, $symbols, "", $ignore);
  815. my $reduced = ReduceProfile($symbols, $profile);
  816. # Get derived profiles
  817. my $flat = FlatProfile($reduced);
  818. my $cumulative = CumulativeProfile($reduced);
  819. PrintDisassembly($libs, $flat, $cumulative, $routine);
  820. return 1;
  821. }
  822. if (m/^\s*(gv|web|evince)\s*(.*)/) {
  823. $main::opt_gv = 0;
  824. $main::opt_evince = 0;
  825. $main::opt_web = 0;
  826. if ($1 eq "gv") {
  827. $main::opt_gv = 1;
  828. } elsif ($1 eq "evince") {
  829. $main::opt_evince = 1;
  830. } elsif ($1 eq "web") {
  831. $main::opt_web = 1;
  832. }
  833. my $focus;
  834. my $ignore;
  835. ($focus, $ignore) = ParseInteractiveArgs($2);
  836. # Process current profile to account for various settings
  837. my $profile = ProcessProfile($total, $orig_profile, $symbols,
  838. $focus, $ignore);
  839. my $reduced = ReduceProfile($symbols, $profile);
  840. # Get derived profiles
  841. my $flat = FlatProfile($reduced);
  842. my $cumulative = CumulativeProfile($reduced);
  843. if (PrintDot($main::prog, $symbols, $profile, $flat, $cumulative, $total)) {
  844. if ($main::opt_gv) {
  845. RunGV(TempName($main::next_tmpfile, "ps"), " &");
  846. } elsif ($main::opt_evince) {
  847. RunEvince(TempName($main::next_tmpfile, "pdf"), " &");
  848. } elsif ($main::opt_web) {
  849. RunWeb(TempName($main::next_tmpfile, "svg"));
  850. }
  851. $main::next_tmpfile++;
  852. }
  853. return 1;
  854. }
  855. if (m/^\s*$/) {
  856. return 1;
  857. }
  858. print STDERR "Unknown command: try 'help'.\n";
  859. return 1;
  860. }
  861. sub ProcessProfile {
  862. my $total_count = shift;
  863. my $orig_profile = shift;
  864. my $symbols = shift;
  865. my $focus = shift;
  866. my $ignore = shift;
  867. # Process current profile to account for various settings
  868. my $profile = $orig_profile;
  869. printf("Total: %s %s\n", Unparse($total_count), Units());
  870. if ($focus ne '') {
  871. $profile = FocusProfile($symbols, $profile, $focus);
  872. my $focus_count = TotalProfile($profile);
  873. printf("After focusing on '%s': %s %s of %s (%0.1f%%)\n",
  874. $focus,
  875. Unparse($focus_count), Units(),
  876. Unparse($total_count), ($focus_count*100.0) / $total_count);
  877. }
  878. if ($ignore ne '') {
  879. $profile = IgnoreProfile($symbols, $profile, $ignore);
  880. my $ignore_count = TotalProfile($profile);
  881. printf("After ignoring '%s': %s %s of %s (%0.1f%%)\n",
  882. $ignore,
  883. Unparse($ignore_count), Units(),
  884. Unparse($total_count),
  885. ($ignore_count*100.0) / $total_count);
  886. }
  887. return $profile;
  888. }
  889. sub InteractiveHelpMessage {
  890. print STDERR <<ENDOFHELP;
  891. Interactive jeprof mode
  892. Commands:
  893. gv
  894. gv [focus] [-ignore1] [-ignore2]
  895. Show graphical hierarchical display of current profile. Without
  896. any arguments, shows all samples in the profile. With the optional
  897. "focus" argument, restricts the samples shown to just those where
  898. the "focus" regular expression matches a routine name on the stack
  899. trace.
  900. web
  901. web [focus] [-ignore1] [-ignore2]
  902. Like GV, but displays profile in your web browser instead of using
  903. Ghostview. Works best if your web browser is already running.
  904. To change the browser that gets used:
  905. On Linux, set the /etc/alternatives/gnome-www-browser symlink.
  906. On OS X, change the Finder association for SVG files.
  907. list [routine_regexp] [-ignore1] [-ignore2]
  908. Show source listing of routines whose names match "routine_regexp"
  909. weblist [routine_regexp] [-ignore1] [-ignore2]
  910. Displays a source listing of routines whose names match "routine_regexp"
  911. in a web browser. You can click on source lines to view the
  912. corresponding disassembly.
  913. top [--cum] [-ignore1] [-ignore2]
  914. top20 [--cum] [-ignore1] [-ignore2]
  915. top37 [--cum] [-ignore1] [-ignore2]
  916. Show top lines ordered by flat profile count, or cumulative count
  917. if --cum is specified. If a number is present after 'top', the
  918. top K routines will be shown (defaults to showing the top 10)
  919. disasm [routine_regexp] [-ignore1] [-ignore2]
  920. Show disassembly of routines whose names match "routine_regexp",
  921. annotated with sample counts.
  922. callgrind
  923. callgrind [filename]
  924. Generates callgrind file. If no filename is given, kcachegrind is called.
  925. help - This listing
  926. quit or ^D - End jeprof
  927. For commands that accept optional -ignore tags, samples where any routine in
  928. the stack trace matches the regular expression in any of the -ignore
  929. parameters will be ignored.
  930. Further pprof details are available at this location (or one similar):
  931. /usr/doc/gperftools-$PPROF_VERSION/cpu_profiler.html
  932. /usr/doc/gperftools-$PPROF_VERSION/heap_profiler.html
  933. ENDOFHELP
  934. }
  935. sub ParseInteractiveArgs {
  936. my $args = shift;
  937. my $focus = "";
  938. my $ignore = "";
  939. my @x = split(/ +/, $args);
  940. foreach $a (@x) {
  941. if ($a =~ m/^(--|-)lines$/) {
  942. $main::opt_lines = 1;
  943. } elsif ($a =~ m/^(--|-)cum$/) {
  944. $main::opt_cum = 1;
  945. } elsif ($a =~ m/^-(.*)/) {
  946. $ignore .= (($ignore ne "") ? "|" : "" ) . $1;
  947. } else {
  948. $focus .= (($focus ne "") ? "|" : "" ) . $a;
  949. }
  950. }
  951. if ($ignore ne "") {
  952. print STDERR "Ignoring samples in call stacks that match '$ignore'\n";
  953. }
  954. return ($focus, $ignore);
  955. }
  956. ##### Output code #####
  957. sub TempName {
  958. my $fnum = shift;
  959. my $ext = shift;
  960. my $file = "$main::tmpfile_ps.$fnum.$ext";
  961. $main::tempnames{$file} = 1;
  962. return $file;
  963. }
  964. # Print profile data in packed binary format (64-bit) to standard out
  965. sub PrintProfileData {
  966. my $profile = shift;
  967. # print header (64-bit style)
  968. # (zero) (header-size) (version) (sample-period) (zero)
  969. print pack('L*', 0, 0, 3, 0, 0, 0, 1, 0, 0, 0);
  970. foreach my $k (keys(%{$profile})) {
  971. my $count = $profile->{$k};
  972. my @addrs = split(/\n/, $k);
  973. if ($#addrs >= 0) {
  974. my $depth = $#addrs + 1;
  975. # int(foo / 2**32) is the only reliable way to get rid of bottom
  976. # 32 bits on both 32- and 64-bit systems.
  977. print pack('L*', $count & 0xFFFFFFFF, int($count / 2**32));
  978. print pack('L*', $depth & 0xFFFFFFFF, int($depth / 2**32));
  979. foreach my $full_addr (@addrs) {
  980. my $addr = $full_addr;
  981. $addr =~ s/0x0*//; # strip off leading 0x, zeroes
  982. if (length($addr) > 16) {
  983. print STDERR "Invalid address in profile: $full_addr\n";
  984. next;
  985. }
  986. my $low_addr = substr($addr, -8); # get last 8 hex chars
  987. my $high_addr = substr($addr, -16, 8); # get up to 8 more hex chars
  988. print pack('L*', hex('0x' . $low_addr), hex('0x' . $high_addr));
  989. }
  990. }
  991. }
  992. }
  993. # Print symbols and profile data
  994. sub PrintSymbolizedProfile {
  995. my $symbols = shift;
  996. my $profile = shift;
  997. my $prog = shift;
  998. $SYMBOL_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  999. my $symbol_marker = $&;
  1000. print '--- ', $symbol_marker, "\n";
  1001. if (defined($prog)) {
  1002. print 'binary=', $prog, "\n";
  1003. }
  1004. while (my ($pc, $name) = each(%{$symbols})) {
  1005. my $sep = ' ';
  1006. print '0x', $pc;
  1007. # We have a list of function names, which include the inlined
  1008. # calls. They are separated (and terminated) by --, which is
  1009. # illegal in function names.
  1010. for (my $j = 2; $j <= $#{$name}; $j += 3) {
  1011. print $sep, $name->[$j];
  1012. $sep = '--';
  1013. }
  1014. print "\n";
  1015. }
  1016. print '---', "\n";
  1017. $PROFILE_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  1018. my $profile_marker = $&;
  1019. print '--- ', $profile_marker, "\n";
  1020. if (defined($main::collected_profile)) {
  1021. # if used with remote fetch, simply dump the collected profile to output.
  1022. open(SRC, "<$main::collected_profile");
  1023. while (<SRC>) {
  1024. print $_;
  1025. }
  1026. close(SRC);
  1027. } else {
  1028. # dump a cpu-format profile to standard out
  1029. PrintProfileData($profile);
  1030. }
  1031. }
  1032. # Print text output
  1033. sub PrintText {
  1034. my $symbols = shift;
  1035. my $flat = shift;
  1036. my $cumulative = shift;
  1037. my $line_limit = shift;
  1038. my $total = TotalProfile($flat);
  1039. # Which profile to sort by?
  1040. my $s = $main::opt_cum ? $cumulative : $flat;
  1041. my $running_sum = 0;
  1042. my $lines = 0;
  1043. foreach my $k (sort { GetEntry($s, $b) <=> GetEntry($s, $a) || $a cmp $b }
  1044. keys(%{$cumulative})) {
  1045. my $f = GetEntry($flat, $k);
  1046. my $c = GetEntry($cumulative, $k);
  1047. $running_sum += $f;
  1048. my $sym = $k;
  1049. if (exists($symbols->{$k})) {
  1050. $sym = $symbols->{$k}->[0] . " " . $symbols->{$k}->[1];
  1051. if ($main::opt_addresses) {
  1052. $sym = $k . " " . $sym;
  1053. }
  1054. }
  1055. if ($f != 0 || $c != 0) {
  1056. printf("%8s %6s %6s %8s %6s %s\n",
  1057. Unparse($f),
  1058. Percent($f, $total),
  1059. Percent($running_sum, $total),
  1060. Unparse($c),
  1061. Percent($c, $total),
  1062. $sym);
  1063. }
  1064. $lines++;
  1065. last if ($line_limit >= 0 && $lines >= $line_limit);
  1066. }
  1067. }
  1068. # Callgrind format has a compression for repeated function and file
  1069. # names. You show the name the first time, and just use its number
  1070. # subsequently. This can cut down the file to about a third or a
  1071. # quarter of its uncompressed size. $key and $val are the key/value
  1072. # pair that would normally be printed by callgrind; $map is a map from
  1073. # value to number.
  1074. sub CompressedCGName {
  1075. my($key, $val, $map) = @_;
  1076. my $idx = $map->{$val};
  1077. # For very short keys, providing an index hurts rather than helps.
  1078. if (length($val) <= 3) {
  1079. return "$key=$val\n";
  1080. } elsif (defined($idx)) {
  1081. return "$key=($idx)\n";
  1082. } else {
  1083. # scalar(keys $map) gives the number of items in the map.
  1084. $idx = scalar(keys(%{$map})) + 1;
  1085. $map->{$val} = $idx;
  1086. return "$key=($idx) $val\n";
  1087. }
  1088. }
  1089. # Print the call graph in a way that's suiteable for callgrind.
  1090. sub PrintCallgrind {
  1091. my $calls = shift;
  1092. my $filename;
  1093. my %filename_to_index_map;
  1094. my %fnname_to_index_map;
  1095. if ($main::opt_interactive) {
  1096. $filename = shift;
  1097. print STDERR "Writing callgrind file to '$filename'.\n"
  1098. } else {
  1099. $filename = "&STDOUT";
  1100. }
  1101. open(CG, ">$filename");
  1102. printf CG ("events: Hits\n\n");
  1103. foreach my $call ( map { $_->[0] }
  1104. sort { $a->[1] cmp $b ->[1] ||
  1105. $a->[2] <=> $b->[2] }
  1106. map { /([^:]+):(\d+):([^ ]+)( -> ([^:]+):(\d+):(.+))?/;
  1107. [$_, $1, $2] }
  1108. keys %$calls ) {
  1109. my $count = int($calls->{$call});
  1110. $call =~ /([^:]+):(\d+):([^ ]+)( -> ([^:]+):(\d+):(.+))?/;
  1111. my ( $caller_file, $caller_line, $caller_function,
  1112. $callee_file, $callee_line, $callee_function ) =
  1113. ( $1, $2, $3, $5, $6, $7 );
  1114. # TODO(csilvers): for better compression, collect all the
  1115. # caller/callee_files and functions first, before printing
  1116. # anything, and only compress those referenced more than once.
  1117. printf CG CompressedCGName("fl", $caller_file, \%filename_to_index_map);
  1118. printf CG CompressedCGName("fn", $caller_function, \%fnname_to_index_map);
  1119. if (defined $6) {
  1120. printf CG CompressedCGName("cfl", $callee_file, \%filename_to_index_map);
  1121. printf CG CompressedCGName("cfn", $callee_function, \%fnname_to_index_map);
  1122. printf CG ("calls=$count $callee_line\n");
  1123. }
  1124. printf CG ("$caller_line $count\n\n");
  1125. }
  1126. }
  1127. # Print disassembly for all all routines that match $main::opt_disasm
  1128. sub PrintDisassembly {
  1129. my $libs = shift;
  1130. my $flat = shift;
  1131. my $cumulative = shift;
  1132. my $disasm_opts = shift;
  1133. my $total = TotalProfile($flat);
  1134. foreach my $lib (@{$libs}) {
  1135. my $symbol_table = GetProcedureBoundaries($lib->[0], $disasm_opts);
  1136. my $offset = AddressSub($lib->[1], $lib->[3]);
  1137. foreach my $routine (sort ByName keys(%{$symbol_table})) {
  1138. my $start_addr = $symbol_table->{$routine}->[0];
  1139. my $end_addr = $symbol_table->{$routine}->[1];
  1140. # See if there are any samples in this routine
  1141. my $length = hex(AddressSub($end_addr, $start_addr));
  1142. my $addr = AddressAdd($start_addr, $offset);
  1143. for (my $i = 0; $i < $length; $i++) {
  1144. if (defined($cumulative->{$addr})) {
  1145. PrintDisassembledFunction($lib->[0], $offset,
  1146. $routine, $flat, $cumulative,
  1147. $start_addr, $end_addr, $total);
  1148. last;
  1149. }
  1150. $addr = AddressInc($addr);
  1151. }
  1152. }
  1153. }
  1154. }
  1155. # Return reference to array of tuples of the form:
  1156. # [start_address, filename, linenumber, instruction, limit_address]
  1157. # E.g.,
  1158. # ["0x806c43d", "/foo/bar.cc", 131, "ret", "0x806c440"]
  1159. sub Disassemble {
  1160. my $prog = shift;
  1161. my $offset = shift;
  1162. my $start_addr = shift;
  1163. my $end_addr = shift;
  1164. my $objdump = $obj_tool_map{"objdump"};
  1165. my $cmd = ShellEscape($objdump, "-C", "-d", "-l", "--no-show-raw-insn",
  1166. "--start-address=0x$start_addr",
  1167. "--stop-address=0x$end_addr", $prog);
  1168. open(OBJDUMP, "$cmd |") || error("$cmd: $!\n");
  1169. my @result = ();
  1170. my $filename = "";
  1171. my $linenumber = -1;
  1172. my $last = ["", "", "", ""];
  1173. while (<OBJDUMP>) {
  1174. s/\r//g; # turn windows-looking lines into unix-looking lines
  1175. chop;
  1176. if (m|\s*([^:\s]+):(\d+)\s*$|) {
  1177. # Location line of the form:
  1178. # <filename>:<linenumber>
  1179. $filename = $1;
  1180. $linenumber = $2;
  1181. } elsif (m/^ +([0-9a-f]+):\s*(.*)/) {
  1182. # Disassembly line -- zero-extend address to full length
  1183. my $addr = HexExtend($1);
  1184. my $k = AddressAdd($addr, $offset);
  1185. $last->[4] = $k; # Store ending address for previous instruction
  1186. $last = [$k, $filename, $linenumber, $2, $end_addr];
  1187. push(@result, $last);
  1188. }
  1189. }
  1190. close(OBJDUMP);
  1191. return @result;
  1192. }
  1193. # The input file should contain lines of the form /proc/maps-like
  1194. # output (same format as expected from the profiles) or that looks
  1195. # like hex addresses (like "0xDEADBEEF"). We will parse all
  1196. # /proc/maps output, and for all the hex addresses, we will output
  1197. # "short" symbol names, one per line, in the same order as the input.
  1198. sub PrintSymbols {
  1199. my $maps_and_symbols_file = shift;
  1200. # ParseLibraries expects pcs to be in a set. Fine by us...
  1201. my @pclist = (); # pcs in sorted order
  1202. my $pcs = {};
  1203. my $map = "";
  1204. foreach my $line (<$maps_and_symbols_file>) {
  1205. $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
  1206. if ($line =~ /\b(0x[0-9a-f]+)\b/i) {
  1207. push(@pclist, HexExtend($1));
  1208. $pcs->{$pclist[-1]} = 1;
  1209. } else {
  1210. $map .= $line;
  1211. }
  1212. }
  1213. my $libs = ParseLibraries($main::prog, $map, $pcs);
  1214. my $symbols = ExtractSymbols($libs, $pcs);
  1215. foreach my $pc (@pclist) {
  1216. # ->[0] is the shortname, ->[2] is the full name
  1217. print(($symbols->{$pc}->[0] || "??") . "\n");
  1218. }
  1219. }
  1220. # For sorting functions by name
  1221. sub ByName {
  1222. return ShortFunctionName($a) cmp ShortFunctionName($b);
  1223. }
  1224. # Print source-listing for all all routines that match $list_opts
  1225. sub PrintListing {
  1226. my $total = shift;
  1227. my $libs = shift;
  1228. my $flat = shift;
  1229. my $cumulative = shift;
  1230. my $list_opts = shift;
  1231. my $html = shift;
  1232. my $output = \*STDOUT;
  1233. my $fname = "";
  1234. if ($html) {
  1235. # Arrange to write the output to a temporary file
  1236. $fname = TempName($main::next_tmpfile, "html");
  1237. $main::next_tmpfile++;
  1238. if (!open(TEMP, ">$fname")) {
  1239. print STDERR "$fname: $!\n";
  1240. return;
  1241. }
  1242. $output = \*TEMP;
  1243. print $output HtmlListingHeader();
  1244. printf $output ("<div class=\"legend\">%s<br>Total: %s %s</div>\n",
  1245. $main::prog, Unparse($total), Units());
  1246. }
  1247. my $listed = 0;
  1248. foreach my $lib (@{$libs}) {
  1249. my $symbol_table = GetProcedureBoundaries($lib->[0], $list_opts);
  1250. my $offset = AddressSub($lib->[1], $lib->[3]);
  1251. foreach my $routine (sort ByName keys(%{$symbol_table})) {
  1252. # Print if there are any samples in this routine
  1253. my $start_addr = $symbol_table->{$routine}->[0];
  1254. my $end_addr = $symbol_table->{$routine}->[1];
  1255. my $length = hex(AddressSub($end_addr, $start_addr));
  1256. my $addr = AddressAdd($start_addr, $offset);
  1257. for (my $i = 0; $i < $length; $i++) {
  1258. if (defined($cumulative->{$addr})) {
  1259. $listed += PrintSource(
  1260. $lib->[0], $offset,
  1261. $routine, $flat, $cumulative,
  1262. $start_addr, $end_addr,
  1263. $html,
  1264. $output);
  1265. last;
  1266. }
  1267. $addr = AddressInc($addr);
  1268. }
  1269. }
  1270. }
  1271. if ($html) {
  1272. if ($listed > 0) {
  1273. print $output HtmlListingFooter();
  1274. close($output);
  1275. RunWeb($fname);
  1276. } else {
  1277. close($output);
  1278. unlink($fname);
  1279. }
  1280. }
  1281. }
  1282. sub HtmlListingHeader {
  1283. return <<'EOF';
  1284. <DOCTYPE html>
  1285. <html>
  1286. <head>
  1287. <title>Pprof listing</title>
  1288. <style type="text/css">
  1289. body {
  1290. font-family: sans-serif;
  1291. }
  1292. h1 {
  1293. font-size: 1.5em;
  1294. margin-bottom: 4px;
  1295. }
  1296. .legend {
  1297. font-size: 1.25em;
  1298. }
  1299. .line {
  1300. color: #aaaaaa;
  1301. }
  1302. .nop {
  1303. color: #aaaaaa;
  1304. }
  1305. .unimportant {
  1306. color: #cccccc;
  1307. }
  1308. .disasmloc {
  1309. color: #000000;
  1310. }
  1311. .deadsrc {
  1312. cursor: pointer;
  1313. }
  1314. .deadsrc:hover {
  1315. background-color: #eeeeee;
  1316. }
  1317. .livesrc {
  1318. color: #0000ff;
  1319. cursor: pointer;
  1320. }
  1321. .livesrc:hover {
  1322. background-color: #eeeeee;
  1323. }
  1324. .asm {
  1325. color: #008800;
  1326. display: none;
  1327. }
  1328. </style>
  1329. <script type="text/javascript">
  1330. function jeprof_toggle_asm(e) {
  1331. var target;
  1332. if (!e) e = window.event;
  1333. if (e.target) target = e.target;
  1334. else if (e.srcElement) target = e.srcElement;
  1335. if (target) {
  1336. var asm = target.nextSibling;
  1337. if (asm && asm.className == "asm") {
  1338. asm.style.display = (asm.style.display == "block" ? "" : "block");
  1339. e.preventDefault();
  1340. return false;
  1341. }
  1342. }
  1343. }
  1344. </script>
  1345. </head>
  1346. <body>
  1347. EOF
  1348. }
  1349. sub HtmlListingFooter {
  1350. return <<'EOF';
  1351. </body>
  1352. </html>
  1353. EOF
  1354. }
  1355. sub HtmlEscape {
  1356. my $text = shift;
  1357. $text =~ s/&/&amp;/g;
  1358. $text =~ s/</&lt;/g;
  1359. $text =~ s/>/&gt;/g;
  1360. return $text;
  1361. }
  1362. # Returns the indentation of the line, if it has any non-whitespace
  1363. # characters. Otherwise, returns -1.
  1364. sub Indentation {
  1365. my $line = shift;
  1366. if (m/^(\s*)\S/) {
  1367. return length($1);
  1368. } else {
  1369. return -1;
  1370. }
  1371. }
  1372. # If the symbol table contains inlining info, Disassemble() may tag an
  1373. # instruction with a location inside an inlined function. But for
  1374. # source listings, we prefer to use the location in the function we
  1375. # are listing. So use MapToSymbols() to fetch full location
  1376. # information for each instruction and then pick out the first
  1377. # location from a location list (location list contains callers before
  1378. # callees in case of inlining).
  1379. #
  1380. # After this routine has run, each entry in $instructions contains:
  1381. # [0] start address
  1382. # [1] filename for function we are listing
  1383. # [2] line number for function we are listing
  1384. # [3] disassembly
  1385. # [4] limit address
  1386. # [5] most specific filename (may be different from [1] due to inlining)
  1387. # [6] most specific line number (may be different from [2] due to inlining)
  1388. sub GetTopLevelLineNumbers {
  1389. my ($lib, $offset, $instructions) = @_;
  1390. my $pcs = [];
  1391. for (my $i = 0; $i <= $#{$instructions}; $i++) {
  1392. push(@{$pcs}, $instructions->[$i]->[0]);
  1393. }
  1394. my $symbols = {};
  1395. MapToSymbols($lib, $offset, $pcs, $symbols);
  1396. for (my $i = 0; $i <= $#{$instructions}; $i++) {
  1397. my $e = $instructions->[$i];
  1398. push(@{$e}, $e->[1]);
  1399. push(@{$e}, $e->[2]);
  1400. my $addr = $e->[0];
  1401. my $sym = $symbols->{$addr};
  1402. if (defined($sym)) {
  1403. if ($#{$sym} >= 2 && $sym->[1] =~ m/^(.*):(\d+)$/) {
  1404. $e->[1] = $1; # File name
  1405. $e->[2] = $2; # Line number
  1406. }
  1407. }
  1408. }
  1409. }
  1410. # Print source-listing for one routine
  1411. sub PrintSource {
  1412. my $prog = shift;
  1413. my $offset = shift;
  1414. my $routine = shift;
  1415. my $flat = shift;
  1416. my $cumulative = shift;
  1417. my $start_addr = shift;
  1418. my $end_addr = shift;
  1419. my $html = shift;
  1420. my $output = shift;
  1421. # Disassemble all instructions (just to get line numbers)
  1422. my @instructions = Disassemble($prog, $offset, $start_addr, $end_addr);
  1423. GetTopLevelLineNumbers($prog, $offset, \@instructions);
  1424. # Hack 1: assume that the first source file encountered in the
  1425. # disassembly contains the routine
  1426. my $filename = undef;
  1427. for (my $i = 0; $i <= $#instructions; $i++) {
  1428. if ($instructions[$i]->[2] >= 0) {
  1429. $filename = $instructions[$i]->[1];
  1430. last;
  1431. }
  1432. }
  1433. if (!defined($filename)) {
  1434. print STDERR "no filename found in $routine\n";
  1435. return 0;
  1436. }
  1437. # Hack 2: assume that the largest line number from $filename is the
  1438. # end of the procedure. This is typically safe since if P1 contains
  1439. # an inlined call to P2, then P2 usually occurs earlier in the
  1440. # source file. If this does not work, we might have to compute a
  1441. # density profile or just print all regions we find.
  1442. my $lastline = 0;
  1443. for (my $i = 0; $i <= $#instructions; $i++) {
  1444. my $f = $instructions[$i]->[1];
  1445. my $l = $instructions[$i]->[2];
  1446. if (($f eq $filename) && ($l > $lastline)) {
  1447. $lastline = $l;
  1448. }
  1449. }
  1450. # Hack 3: assume the first source location from "filename" is the start of
  1451. # the source code.
  1452. my $firstline = 1;
  1453. for (my $i = 0; $i <= $#instructions; $i++) {
  1454. if ($instructions[$i]->[1] eq $filename) {
  1455. $firstline = $instructions[$i]->[2];
  1456. last;
  1457. }
  1458. }
  1459. # Hack 4: Extend last line forward until its indentation is less than
  1460. # the indentation we saw on $firstline
  1461. my $oldlastline = $lastline;
  1462. {
  1463. if (!open(FILE, "<$filename")) {
  1464. print STDERR "$filename: $!\n";
  1465. return 0;
  1466. }
  1467. my $l = 0;
  1468. my $first_indentation = -1;
  1469. while (<FILE>) {
  1470. s/\r//g; # turn windows-looking lines into unix-looking lines
  1471. $l++;
  1472. my $indent = Indentation($_);
  1473. if ($l >= $firstline) {
  1474. if ($first_indentation < 0 && $indent >= 0) {
  1475. $first_indentation = $indent;
  1476. last if ($first_indentation == 0);
  1477. }
  1478. }
  1479. if ($l >= $lastline && $indent >= 0) {
  1480. if ($indent >= $first_indentation) {
  1481. $lastline = $l+1;
  1482. } else {
  1483. last;
  1484. }
  1485. }
  1486. }
  1487. close(FILE);
  1488. }
  1489. # Assign all samples to the range $firstline,$lastline,
  1490. # Hack 4: If an instruction does not occur in the range, its samples
  1491. # are moved to the next instruction that occurs in the range.
  1492. my $samples1 = {}; # Map from line number to flat count
  1493. my $samples2 = {}; # Map from line number to cumulative count
  1494. my $running1 = 0; # Unassigned flat counts
  1495. my $running2 = 0; # Unassigned cumulative counts
  1496. my $total1 = 0; # Total flat counts
  1497. my $total2 = 0; # Total cumulative counts
  1498. my %disasm = (); # Map from line number to disassembly
  1499. my $running_disasm = ""; # Unassigned disassembly
  1500. my $skip_marker = "---\n";
  1501. if ($html) {
  1502. $skip_marker = "";
  1503. for (my $l = $firstline; $l <= $lastline; $l++) {
  1504. $disasm{$l} = "";
  1505. }
  1506. }
  1507. my $last_dis_filename = '';
  1508. my $last_dis_linenum = -1;
  1509. my $last_touched_line = -1; # To detect gaps in disassembly for a line
  1510. foreach my $e (@instructions) {
  1511. # Add up counts for all address that fall inside this instruction
  1512. my $c1 = 0;
  1513. my $c2 = 0;
  1514. for (my $a = $e->[0]; $a lt $e->[4]; $a = AddressInc($a)) {
  1515. $c1 += GetEntry($flat, $a);
  1516. $c2 += GetEntry($cumulative, $a);
  1517. }
  1518. if ($html) {
  1519. my $dis = sprintf(" %6s %6s \t\t%8s: %s ",
  1520. HtmlPrintNumber($c1),
  1521. HtmlPrintNumber($c2),
  1522. UnparseAddress($offset, $e->[0]),
  1523. CleanDisassembly($e->[3]));
  1524. # Append the most specific source line associated with this instruction
  1525. if (length($dis) < 80) { $dis .= (' ' x (80 - length($dis))) };
  1526. $dis = HtmlEscape($dis);
  1527. my $f = $e->[5];
  1528. my $l = $e->[6];
  1529. if ($f ne $last_dis_filename) {
  1530. $dis .= sprintf("<span class=disasmloc>%s:%d</span>",
  1531. HtmlEscape(CleanFileName($f)), $l);
  1532. } elsif ($l ne $last_dis_linenum) {
  1533. # De-emphasize the unchanged file name portion
  1534. $dis .= sprintf("<span class=unimportant>%s</span>" .
  1535. "<span class=disasmloc>:%d</span>",
  1536. HtmlEscape(CleanFileName($f)), $l);
  1537. } else {
  1538. # De-emphasize the entire location
  1539. $dis .= sprintf("<span class=unimportant>%s:%d</span>",
  1540. HtmlEscape(CleanFileName($f)), $l);
  1541. }
  1542. $last_dis_filename = $f;
  1543. $last_dis_linenum = $l;
  1544. $running_disasm .= $dis;
  1545. $running_disasm .= "\n";
  1546. }
  1547. $running1 += $c1;
  1548. $running2 += $c2;
  1549. $total1 += $c1;
  1550. $total2 += $c2;
  1551. my $file = $e->[1];
  1552. my $line = $e->[2];
  1553. if (($file eq $filename) &&
  1554. ($line >= $firstline) &&
  1555. ($line <= $lastline)) {
  1556. # Assign all accumulated samples to this line
  1557. AddEntry($samples1, $line, $running1);
  1558. AddEntry($samples2, $line, $running2);
  1559. $running1 = 0;
  1560. $running2 = 0;
  1561. if ($html) {
  1562. if ($line != $last_touched_line && $disasm{$line} ne '') {
  1563. $disasm{$line} .= "\n";
  1564. }
  1565. $disasm{$line} .= $running_disasm;
  1566. $running_disasm = '';
  1567. $last_touched_line = $line;
  1568. }
  1569. }
  1570. }
  1571. # Assign any leftover samples to $lastline
  1572. AddEntry($samples1, $lastline, $running1);
  1573. AddEntry($samples2, $lastline, $running2);
  1574. if ($html) {
  1575. if ($lastline != $last_touched_line && $disasm{$lastline} ne '') {
  1576. $disasm{$lastline} .= "\n";
  1577. }
  1578. $disasm{$lastline} .= $running_disasm;
  1579. }
  1580. if ($html) {
  1581. printf $output (
  1582. "<h1>%s</h1>%s\n<pre onClick=\"jeprof_toggle_asm()\">\n" .
  1583. "Total:%6s %6s (flat / cumulative %s)\n",
  1584. HtmlEscape(ShortFunctionName($routine)),
  1585. HtmlEscape(CleanFileName($filename)),
  1586. Unparse($total1),
  1587. Unparse($total2),
  1588. Units());
  1589. } else {
  1590. printf $output (
  1591. "ROUTINE ====================== %s in %s\n" .
  1592. "%6s %6s Total %s (flat / cumulative)\n",
  1593. ShortFunctionName($routine),
  1594. CleanFileName($filename),
  1595. Unparse($total1),
  1596. Unparse($total2),
  1597. Units());
  1598. }
  1599. if (!open(FILE, "<$filename")) {
  1600. print STDERR "$filename: $!\n";
  1601. return 0;
  1602. }
  1603. my $l = 0;
  1604. while (<FILE>) {
  1605. s/\r//g; # turn windows-looking lines into unix-looking lines
  1606. $l++;
  1607. if ($l >= $firstline - 5 &&
  1608. (($l <= $oldlastline + 5) || ($l <= $lastline))) {
  1609. chop;
  1610. my $text = $_;
  1611. if ($l == $firstline) { print $output $skip_marker; }
  1612. my $n1 = GetEntry($samples1, $l);
  1613. my $n2 = GetEntry($samples2, $l);
  1614. if ($html) {
  1615. # Emit a span that has one of the following classes:
  1616. # livesrc -- has samples
  1617. # deadsrc -- has disassembly, but with no samples
  1618. # nop -- has no matching disasembly
  1619. # Also emit an optional span containing disassembly.
  1620. my $dis = $disasm{$l};
  1621. my $asm = "";
  1622. if (defined($dis) && $dis ne '') {
  1623. $asm = "<span class=\"asm\">" . $dis . "</span>";
  1624. }
  1625. my $source_class = (($n1 + $n2 > 0)
  1626. ? "livesrc"
  1627. : (($asm ne "") ? "deadsrc" : "nop"));
  1628. printf $output (
  1629. "<span class=\"line\">%5d</span> " .
  1630. "<span class=\"%s\">%6s %6s %s</span>%s\n",
  1631. $l, $source_class,
  1632. HtmlPrintNumber($n1),
  1633. HtmlPrintNumber($n2),
  1634. HtmlEscape($text),
  1635. $asm);
  1636. } else {
  1637. printf $output(
  1638. "%6s %6s %4d: %s\n",
  1639. UnparseAlt($n1),
  1640. UnparseAlt($n2),
  1641. $l,
  1642. $text);
  1643. }
  1644. if ($l == $lastline) { print $output $skip_marker; }
  1645. };
  1646. }
  1647. close(FILE);
  1648. if ($html) {
  1649. print $output "</pre>\n";
  1650. }
  1651. return 1;
  1652. }
  1653. # Return the source line for the specified file/linenumber.
  1654. # Returns undef if not found.
  1655. sub SourceLine {
  1656. my $file = shift;
  1657. my $line = shift;
  1658. # Look in cache
  1659. if (!defined($main::source_cache{$file})) {
  1660. if (100 < scalar keys(%main::source_cache)) {
  1661. # Clear the cache when it gets too big
  1662. $main::source_cache = ();
  1663. }
  1664. # Read all lines from the file
  1665. if (!open(FILE, "<$file")) {
  1666. print STDERR "$file: $!\n";
  1667. $main::source_cache{$file} = []; # Cache the negative result
  1668. return undef;
  1669. }
  1670. my $lines = [];
  1671. push(@{$lines}, ""); # So we can use 1-based line numbers as indices
  1672. while (<FILE>) {
  1673. push(@{$lines}, $_);
  1674. }
  1675. close(FILE);
  1676. # Save the lines in the cache
  1677. $main::source_cache{$file} = $lines;
  1678. }
  1679. my $lines = $main::source_cache{$file};
  1680. if (($line < 0) || ($line > $#{$lines})) {
  1681. return undef;
  1682. } else {
  1683. return $lines->[$line];
  1684. }
  1685. }
  1686. # Print disassembly for one routine with interspersed source if available
  1687. sub PrintDisassembledFunction {
  1688. my $prog = shift;
  1689. my $offset = shift;
  1690. my $routine = shift;
  1691. my $flat = shift;
  1692. my $cumulative = shift;
  1693. my $start_addr = shift;
  1694. my $end_addr = shift;
  1695. my $total = shift;
  1696. # Disassemble all instructions
  1697. my @instructions = Disassemble($prog, $offset, $start_addr, $end_addr);
  1698. # Make array of counts per instruction
  1699. my @flat_count = ();
  1700. my @cum_count = ();
  1701. my $flat_total = 0;
  1702. my $cum_total = 0;
  1703. foreach my $e (@instructions) {
  1704. # Add up counts for all address that fall inside this instruction
  1705. my $c1 = 0;
  1706. my $c2 = 0;
  1707. for (my $a = $e->[0]; $a lt $e->[4]; $a = AddressInc($a)) {
  1708. $c1 += GetEntry($flat, $a);
  1709. $c2 += GetEntry($cumulative, $a);
  1710. }
  1711. push(@flat_count, $c1);
  1712. push(@cum_count, $c2);
  1713. $flat_total += $c1;
  1714. $cum_total += $c2;
  1715. }
  1716. # Print header with total counts
  1717. printf("ROUTINE ====================== %s\n" .
  1718. "%6s %6s %s (flat, cumulative) %.1f%% of total\n",
  1719. ShortFunctionName($routine),
  1720. Unparse($flat_total),
  1721. Unparse($cum_total),
  1722. Units(),
  1723. ($cum_total * 100.0) / $total);
  1724. # Process instructions in order
  1725. my $current_file = "";
  1726. for (my $i = 0; $i <= $#instructions; ) {
  1727. my $e = $instructions[$i];
  1728. # Print the new file name whenever we switch files
  1729. if ($e->[1] ne $current_file) {
  1730. $current_file = $e->[1];
  1731. my $fname = $current_file;
  1732. $fname =~ s|^\./||; # Trim leading "./"
  1733. # Shorten long file names
  1734. if (length($fname) >= 58) {
  1735. $fname = "..." . substr($fname, -55);
  1736. }
  1737. printf("-------------------- %s\n", $fname);
  1738. }
  1739. # TODO: Compute range of lines to print together to deal with
  1740. # small reorderings.
  1741. my $first_line = $e->[2];
  1742. my $last_line = $first_line;
  1743. my %flat_sum = ();
  1744. my %cum_sum = ();
  1745. for (my $l = $first_line; $l <= $last_line; $l++) {
  1746. $flat_sum{$l} = 0;
  1747. $cum_sum{$l} = 0;
  1748. }
  1749. # Find run of instructions for this range of source lines
  1750. my $first_inst = $i;
  1751. while (($i <= $#instructions) &&
  1752. ($instructions[$i]->[2] >= $first_line) &&
  1753. ($instructions[$i]->[2] <= $last_line)) {
  1754. $e = $instructions[$i];
  1755. $flat_sum{$e->[2]} += $flat_count[$i];
  1756. $cum_sum{$e->[2]} += $cum_count[$i];
  1757. $i++;
  1758. }
  1759. my $last_inst = $i - 1;
  1760. # Print source lines
  1761. for (my $l = $first_line; $l <= $last_line; $l++) {
  1762. my $line = SourceLine($current_file, $l);
  1763. if (!defined($line)) {
  1764. $line = "?\n";
  1765. next;
  1766. } else {
  1767. $line =~ s/^\s+//;
  1768. }
  1769. printf("%6s %6s %5d: %s",
  1770. UnparseAlt($flat_sum{$l}),
  1771. UnparseAlt($cum_sum{$l}),
  1772. $l,
  1773. $line);
  1774. }
  1775. # Print disassembly
  1776. for (my $x = $first_inst; $x <= $last_inst; $x++) {
  1777. my $e = $instructions[$x];
  1778. printf("%6s %6s %8s: %6s\n",
  1779. UnparseAlt($flat_count[$x]),
  1780. UnparseAlt($cum_count[$x]),
  1781. UnparseAddress($offset, $e->[0]),
  1782. CleanDisassembly($e->[3]));
  1783. }
  1784. }
  1785. }
  1786. # Print DOT graph
  1787. sub PrintDot {
  1788. my $prog = shift;
  1789. my $symbols = shift;
  1790. my $raw = shift;
  1791. my $flat = shift;
  1792. my $cumulative = shift;
  1793. my $overall_total = shift;
  1794. # Get total
  1795. my $local_total = TotalProfile($flat);
  1796. my $nodelimit = int($main::opt_nodefraction * $local_total);
  1797. my $edgelimit = int($main::opt_edgefraction * $local_total);
  1798. my $nodecount = $main::opt_nodecount;
  1799. # Find nodes to include
  1800. my @list = (sort { abs(GetEntry($cumulative, $b)) <=>
  1801. abs(GetEntry($cumulative, $a))
  1802. || $a cmp $b }
  1803. keys(%{$cumulative}));
  1804. my $last = $nodecount - 1;
  1805. if ($last > $#list) {
  1806. $last = $#list;
  1807. }
  1808. while (($last >= 0) &&
  1809. (abs(GetEntry($cumulative, $list[$last])) <= $nodelimit)) {
  1810. $last--;
  1811. }
  1812. if ($last < 0) {
  1813. print STDERR "No nodes to print\n";
  1814. return 0;
  1815. }
  1816. if ($nodelimit > 0 || $edgelimit > 0) {
  1817. printf STDERR ("Dropping nodes with <= %s %s; edges with <= %s abs(%s)\n",
  1818. Unparse($nodelimit), Units(),
  1819. Unparse($edgelimit), Units());
  1820. }
  1821. # Open DOT output file
  1822. my $output;
  1823. my $escaped_dot = ShellEscape(@DOT);
  1824. my $escaped_ps2pdf = ShellEscape(@PS2PDF);
  1825. if ($main::opt_gv) {
  1826. my $escaped_outfile = ShellEscape(TempName($main::next_tmpfile, "ps"));
  1827. $output = "| $escaped_dot -Tps2 >$escaped_outfile";
  1828. } elsif ($main::opt_evince) {
  1829. my $escaped_outfile = ShellEscape(TempName($main::next_tmpfile, "pdf"));
  1830. $output = "| $escaped_dot -Tps2 | $escaped_ps2pdf - $escaped_outfile";
  1831. } elsif ($main::opt_ps) {
  1832. $output = "| $escaped_dot -Tps2";
  1833. } elsif ($main::opt_pdf) {
  1834. $output = "| $escaped_dot -Tps2 | $escaped_ps2pdf - -";
  1835. } elsif ($main::opt_web || $main::opt_svg) {
  1836. # We need to post-process the SVG, so write to a temporary file always.
  1837. my $escaped_outfile = ShellEscape(TempName($main::next_tmpfile, "svg"));
  1838. $output = "| $escaped_dot -Tsvg >$escaped_outfile";
  1839. } elsif ($main::opt_gif) {
  1840. $output = "| $escaped_dot -Tgif";
  1841. } else {
  1842. $output = ">&STDOUT";
  1843. }
  1844. open(DOT, $output) || error("$output: $!\n");
  1845. # Title
  1846. printf DOT ("digraph \"%s; %s %s\" {\n",
  1847. $prog,
  1848. Unparse($overall_total),
  1849. Units());
  1850. if ($main::opt_pdf) {
  1851. # The output is more printable if we set the page size for dot.
  1852. printf DOT ("size=\"8,11\"\n");
  1853. }
  1854. printf DOT ("node [width=0.375,height=0.25];\n");
  1855. # Print legend
  1856. printf DOT ("Legend [shape=box,fontsize=24,shape=plaintext," .
  1857. "label=\"%s\\l%s\\l%s\\l%s\\l%s\\l\"];\n",
  1858. $prog,
  1859. sprintf("Total %s: %s", Units(), Unparse($overall_total)),
  1860. sprintf("Focusing on: %s", Unparse($local_total)),
  1861. sprintf("Dropped nodes with <= %s abs(%s)",
  1862. Unparse($nodelimit), Units()),
  1863. sprintf("Dropped edges with <= %s %s",
  1864. Unparse($edgelimit), Units())
  1865. );
  1866. # Print nodes
  1867. my %node = ();
  1868. my $nextnode = 1;
  1869. foreach my $a (@list[0..$last]) {
  1870. # Pick font size
  1871. my $f = GetEntry($flat, $a);
  1872. my $c = GetEntry($cumulative, $a);
  1873. my $fs = 8;
  1874. if ($local_total > 0) {
  1875. $fs = 8 + (50.0 * sqrt(abs($f * 1.0 / $local_total)));
  1876. }
  1877. $node{$a} = $nextnode++;
  1878. my $sym = $a;
  1879. $sym =~ s/\s+/\\n/g;
  1880. $sym =~ s/::/\\n/g;
  1881. # Extra cumulative info to print for non-leaves
  1882. my $extra = "";
  1883. if ($f != $c) {
  1884. $extra = sprintf("\\rof %s (%s)",
  1885. Unparse($c),
  1886. Percent($c, $local_total));
  1887. }
  1888. my $style = "";
  1889. if ($main::opt_heapcheck) {
  1890. if ($f > 0) {
  1891. # make leak-causing nodes more visible (add a background)
  1892. $style = ",style=filled,fillcolor=gray"
  1893. } elsif ($f < 0) {
  1894. # make anti-leak-causing nodes (which almost never occur)
  1895. # stand out as well (triple border)
  1896. $style = ",peripheries=3"
  1897. }
  1898. }
  1899. printf DOT ("N%d [label=\"%s\\n%s (%s)%s\\r" .
  1900. "\",shape=box,fontsize=%.1f%s];\n",
  1901. $node{$a},
  1902. $sym,
  1903. Unparse($f),
  1904. Percent($f, $local_total),
  1905. $extra,
  1906. $fs,
  1907. $style,
  1908. );
  1909. }
  1910. # Get edges and counts per edge
  1911. my %edge = ();
  1912. my $n;
  1913. my $fullname_to_shortname_map = {};
  1914. FillFullnameToShortnameMap($symbols, $fullname_to_shortname_map);
  1915. foreach my $k (keys(%{$raw})) {
  1916. # TODO: omit low %age edges
  1917. $n = $raw->{$k};
  1918. my @translated = TranslateStack($symbols, $fullname_to_shortname_map, $k);
  1919. for (my $i = 1; $i <= $#translated; $i++) {
  1920. my $src = $translated[$i];
  1921. my $dst = $translated[$i-1];
  1922. #next if ($src eq $dst); # Avoid self-edges?
  1923. if (exists($node{$src}) && exists($node{$dst})) {
  1924. my $edge_label = "$src\001$dst";
  1925. if (!exists($edge{$edge_label})) {
  1926. $edge{$edge_label} = 0;
  1927. }
  1928. $edge{$edge_label} += $n;
  1929. }
  1930. }
  1931. }
  1932. # Print edges (process in order of decreasing counts)
  1933. my %indegree = (); # Number of incoming edges added per node so far
  1934. my %outdegree = (); # Number of outgoing edges added per node so far
  1935. foreach my $e (sort { $edge{$b} <=> $edge{$a} } keys(%edge)) {
  1936. my @x = split(/\001/, $e);
  1937. $n = $edge{$e};
  1938. # Initialize degree of kept incoming and outgoing edges if necessary
  1939. my $src = $x[0];
  1940. my $dst = $x[1];
  1941. if (!exists($outdegree{$src})) { $outdegree{$src} = 0; }
  1942. if (!exists($indegree{$dst})) { $indegree{$dst} = 0; }
  1943. my $keep;
  1944. if ($indegree{$dst} == 0) {
  1945. # Keep edge if needed for reachability
  1946. $keep = 1;
  1947. } elsif (abs($n) <= $edgelimit) {
  1948. # Drop if we are below --edgefraction
  1949. $keep = 0;
  1950. } elsif ($outdegree{$src} >= $main::opt_maxdegree ||
  1951. $indegree{$dst} >= $main::opt_maxdegree) {
  1952. # Keep limited number of in/out edges per node
  1953. $keep = 0;
  1954. } else {
  1955. $keep = 1;
  1956. }
  1957. if ($keep) {
  1958. $outdegree{$src}++;
  1959. $indegree{$dst}++;
  1960. # Compute line width based on edge count
  1961. my $fraction = abs($local_total ? (3 * ($n / $local_total)) : 0);
  1962. if ($fraction > 1) { $fraction = 1; }
  1963. my $w = $fraction * 2;
  1964. if ($w < 1 && ($main::opt_web || $main::opt_svg)) {
  1965. # SVG output treats line widths < 1 poorly.
  1966. $w = 1;
  1967. }
  1968. # Dot sometimes segfaults if given edge weights that are too large, so
  1969. # we cap the weights at a large value
  1970. my $edgeweight = abs($n) ** 0.7;
  1971. if ($edgeweight > 100000) { $edgeweight = 100000; }
  1972. $edgeweight = int($edgeweight);
  1973. my $style = sprintf("setlinewidth(%f)", $w);
  1974. if ($x[1] =~ m/\(inline\)/) {
  1975. $style .= ",dashed";
  1976. }
  1977. # Use a slightly squashed function of the edge count as the weight
  1978. printf DOT ("N%s -> N%s [label=%s, weight=%d, style=\"%s\"];\n",
  1979. $node{$x[0]},
  1980. $node{$x[1]},
  1981. Unparse($n),
  1982. $edgeweight,
  1983. $style);
  1984. }
  1985. }
  1986. print DOT ("}\n");
  1987. close(DOT);
  1988. if ($main::opt_web || $main::opt_svg) {
  1989. # Rewrite SVG to be more usable inside web browser.
  1990. RewriteSvg(TempName($main::next_tmpfile, "svg"));
  1991. }
  1992. return 1;
  1993. }
  1994. sub RewriteSvg {
  1995. my $svgfile = shift;
  1996. open(SVG, $svgfile) || die "open temp svg: $!";
  1997. my @svg = <SVG>;
  1998. close(SVG);
  1999. unlink $svgfile;
  2000. my $svg = join('', @svg);
  2001. # Dot's SVG output is
  2002. #
  2003. # <svg width="___" height="___"
  2004. # viewBox="___" xmlns=...>
  2005. # <g id="graph0" transform="...">
  2006. # ...
  2007. # </g>
  2008. # </svg>
  2009. #
  2010. # Change it to
  2011. #
  2012. # <svg width="100%" height="100%"
  2013. # xmlns=...>
  2014. # $svg_javascript
  2015. # <g id="viewport" transform="translate(0,0)">
  2016. # <g id="graph0" transform="...">
  2017. # ...
  2018. # </g>
  2019. # </g>
  2020. # </svg>
  2021. # Fix width, height; drop viewBox.
  2022. $svg =~ s/(?s)<svg width="[^"]+" height="[^"]+"(.*?)viewBox="[^"]+"/<svg width="100%" height="100%"$1/;
  2023. # Insert script, viewport <g> above first <g>
  2024. my $svg_javascript = SvgJavascript();
  2025. my $viewport = "<g id=\"viewport\" transform=\"translate(0,0)\">\n";
  2026. $svg =~ s/<g id="graph\d"/$svg_javascript$viewport$&/;
  2027. # Insert final </g> above </svg>.
  2028. $svg =~ s/(.*)(<\/svg>)/$1<\/g>$2/;
  2029. $svg =~ s/<g id="graph\d"(.*?)/<g id="viewport"$1/;
  2030. if ($main::opt_svg) {
  2031. # --svg: write to standard output.
  2032. print $svg;
  2033. } else {
  2034. # Write back to temporary file.
  2035. open(SVG, ">$svgfile") || die "open $svgfile: $!";
  2036. print SVG $svg;
  2037. close(SVG);
  2038. }
  2039. }
  2040. sub SvgJavascript {
  2041. return <<'EOF';
  2042. <script type="text/ecmascript"><![CDATA[
  2043. // SVGPan
  2044. // http://www.cyberz.org/blog/2009/12/08/svgpan-a-javascript-svg-panzoomdrag-library/
  2045. // Local modification: if(true || ...) below to force panning, never moving.
  2046. /**
  2047. * SVGPan library 1.2
  2048. * ====================
  2049. *
  2050. * Given an unique existing element with id "viewport", including the
  2051. * the library into any SVG adds the following capabilities:
  2052. *
  2053. * - Mouse panning
  2054. * - Mouse zooming (using the wheel)
  2055. * - Object dargging
  2056. *
  2057. * Known issues:
  2058. *
  2059. * - Zooming (while panning) on Safari has still some issues
  2060. *
  2061. * Releases:
  2062. *
  2063. * 1.2, Sat Mar 20 08:42:50 GMT 2010, Zeng Xiaohui
  2064. * Fixed a bug with browser mouse handler interaction
  2065. *
  2066. * 1.1, Wed Feb 3 17:39:33 GMT 2010, Zeng Xiaohui
  2067. * Updated the zoom code to support the mouse wheel on Safari/Chrome
  2068. *
  2069. * 1.0, Andrea Leofreddi
  2070. * First release
  2071. *
  2072. * This code is licensed under the following BSD license:
  2073. *
  2074. * Copyright 2009-2010 Andrea Leofreddi <a.leofreddi@itcharm.com>. All rights reserved.
  2075. *
  2076. * Redistribution and use in source and binary forms, with or without modification, are
  2077. * permitted provided that the following conditions are met:
  2078. *
  2079. * 1. Redistributions of source code must retain the above copyright notice, this list of
  2080. * conditions and the following disclaimer.
  2081. *
  2082. * 2. Redistributions in binary form must reproduce the above copyright notice, this list
  2083. * of conditions and the following disclaimer in the documentation and/or other materials
  2084. * provided with the distribution.
  2085. *
  2086. * THIS SOFTWARE IS PROVIDED BY Andrea Leofreddi ``AS IS'' AND ANY EXPRESS OR IMPLIED
  2087. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2088. * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Andrea Leofreddi OR
  2089. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  2090. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  2091. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  2092. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2093. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  2094. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2095. *
  2096. * The views and conclusions contained in the software and documentation are those of the
  2097. * authors and should not be interpreted as representing official policies, either expressed
  2098. * or implied, of Andrea Leofreddi.
  2099. */
  2100. var root = document.documentElement;
  2101. var state = 'none', stateTarget, stateOrigin, stateTf;
  2102. setupHandlers(root);
  2103. /**
  2104. * Register handlers
  2105. */
  2106. function setupHandlers(root){
  2107. setAttributes(root, {
  2108. "onmouseup" : "add(evt)",
  2109. "onmousedown" : "handleMouseDown(evt)",
  2110. "onmousemove" : "handleMouseMove(evt)",
  2111. "onmouseup" : "handleMouseUp(evt)",
  2112. //"onmouseout" : "handleMouseUp(evt)", // Decomment this to stop the pan functionality when dragging out of the SVG element
  2113. });
  2114. if(navigator.userAgent.toLowerCase().indexOf('webkit') >= 0)
  2115. window.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
  2116. else
  2117. window.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
  2118. var g = svgDoc.getElementById("svg");
  2119. g.width = "100%";
  2120. g.height = "100%";
  2121. }
  2122. /**
  2123. * Instance an SVGPoint object with given event coordinates.
  2124. */
  2125. function getEventPoint(evt) {
  2126. var p = root.createSVGPoint();
  2127. p.x = evt.clientX;
  2128. p.y = evt.clientY;
  2129. return p;
  2130. }
  2131. /**
  2132. * Sets the current transform matrix of an element.
  2133. */
  2134. function setCTM(element, matrix) {
  2135. var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
  2136. element.setAttribute("transform", s);
  2137. }
  2138. /**
  2139. * Dumps a matrix to a string (useful for debug).
  2140. */
  2141. function dumpMatrix(matrix) {
  2142. var s = "[ " + matrix.a + ", " + matrix.c + ", " + matrix.e + "\n " + matrix.b + ", " + matrix.d + ", " + matrix.f + "\n 0, 0, 1 ]";
  2143. return s;
  2144. }
  2145. /**
  2146. * Sets attributes of an element.
  2147. */
  2148. function setAttributes(element, attributes){
  2149. for (i in attributes)
  2150. element.setAttributeNS(null, i, attributes[i]);
  2151. }
  2152. /**
  2153. * Handle mouse move event.
  2154. */
  2155. function handleMouseWheel(evt) {
  2156. if(evt.preventDefault)
  2157. evt.preventDefault();
  2158. evt.returnValue = false;
  2159. var svgDoc = evt.target.ownerDocument;
  2160. var delta;
  2161. if(evt.wheelDelta)
  2162. delta = evt.wheelDelta / 3600; // Chrome/Safari
  2163. else
  2164. delta = evt.detail / -90; // Mozilla
  2165. var z = 1 + delta; // Zoom factor: 0.9/1.1
  2166. var g = svgDoc.getElementById("viewport");
  2167. var p = getEventPoint(evt);
  2168. p = p.matrixTransform(g.getCTM().inverse());
  2169. // Compute new scale matrix in current mouse position
  2170. var k = root.createSVGMatrix().translate(p.x, p.y).scale(z).translate(-p.x, -p.y);
  2171. setCTM(g, g.getCTM().multiply(k));
  2172. stateTf = stateTf.multiply(k.inverse());
  2173. }
  2174. /**
  2175. * Handle mouse move event.
  2176. */
  2177. function handleMouseMove(evt) {
  2178. if(evt.preventDefault)
  2179. evt.preventDefault();
  2180. evt.returnValue = false;
  2181. var svgDoc = evt.target.ownerDocument;
  2182. var g = svgDoc.getElementById("viewport");
  2183. if(state == 'pan') {
  2184. // Pan mode
  2185. var p = getEventPoint(evt).matrixTransform(stateTf);
  2186. setCTM(g, stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y));
  2187. } else if(state == 'move') {
  2188. // Move mode
  2189. var p = getEventPoint(evt).matrixTransform(g.getCTM().inverse());
  2190. setCTM(stateTarget, root.createSVGMatrix().translate(p.x - stateOrigin.x, p.y - stateOrigin.y).multiply(g.getCTM().inverse()).multiply(stateTarget.getCTM()));
  2191. stateOrigin = p;
  2192. }
  2193. }
  2194. /**
  2195. * Handle click event.
  2196. */
  2197. function handleMouseDown(evt) {
  2198. if(evt.preventDefault)
  2199. evt.preventDefault();
  2200. evt.returnValue = false;
  2201. var svgDoc = evt.target.ownerDocument;
  2202. var g = svgDoc.getElementById("viewport");
  2203. if(true || evt.target.tagName == "svg") {
  2204. // Pan mode
  2205. state = 'pan';
  2206. stateTf = g.getCTM().inverse();
  2207. stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
  2208. } else {
  2209. // Move mode
  2210. state = 'move';
  2211. stateTarget = evt.target;
  2212. stateTf = g.getCTM().inverse();
  2213. stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
  2214. }
  2215. }
  2216. /**
  2217. * Handle mouse button release event.
  2218. */
  2219. function handleMouseUp(evt) {
  2220. if(evt.preventDefault)
  2221. evt.preventDefault();
  2222. evt.returnValue = false;
  2223. var svgDoc = evt.target.ownerDocument;
  2224. if(state == 'pan' || state == 'move') {
  2225. // Quit pan mode
  2226. state = '';
  2227. }
  2228. }
  2229. ]]></script>
  2230. EOF
  2231. }
  2232. # Provides a map from fullname to shortname for cases where the
  2233. # shortname is ambiguous. The symlist has both the fullname and
  2234. # shortname for all symbols, which is usually fine, but sometimes --
  2235. # such as overloaded functions -- two different fullnames can map to
  2236. # the same shortname. In that case, we use the address of the
  2237. # function to disambiguate the two. This function fills in a map that
  2238. # maps fullnames to modified shortnames in such cases. If a fullname
  2239. # is not present in the map, the 'normal' shortname provided by the
  2240. # symlist is the appropriate one to use.
  2241. sub FillFullnameToShortnameMap {
  2242. my $symbols = shift;
  2243. my $fullname_to_shortname_map = shift;
  2244. my $shortnames_seen_once = {};
  2245. my $shortnames_seen_more_than_once = {};
  2246. foreach my $symlist (values(%{$symbols})) {
  2247. # TODO(csilvers): deal with inlined symbols too.
  2248. my $shortname = $symlist->[0];
  2249. my $fullname = $symlist->[2];
  2250. if ($fullname !~ /<[0-9a-fA-F]+>$/) { # fullname doesn't end in an address
  2251. next; # the only collisions we care about are when addresses differ
  2252. }
  2253. if (defined($shortnames_seen_once->{$shortname}) &&
  2254. $shortnames_seen_once->{$shortname} ne $fullname) {
  2255. $shortnames_seen_more_than_once->{$shortname} = 1;
  2256. } else {
  2257. $shortnames_seen_once->{$shortname} = $fullname;
  2258. }
  2259. }
  2260. foreach my $symlist (values(%{$symbols})) {
  2261. my $shortname = $symlist->[0];
  2262. my $fullname = $symlist->[2];
  2263. # TODO(csilvers): take in a list of addresses we care about, and only
  2264. # store in the map if $symlist->[1] is in that list. Saves space.
  2265. next if defined($fullname_to_shortname_map->{$fullname});
  2266. if (defined($shortnames_seen_more_than_once->{$shortname})) {
  2267. if ($fullname =~ /<0*([^>]*)>$/) { # fullname has address at end of it
  2268. $fullname_to_shortname_map->{$fullname} = "$shortname\@$1";
  2269. }
  2270. }
  2271. }
  2272. }
  2273. # Return a small number that identifies the argument.
  2274. # Multiple calls with the same argument will return the same number.
  2275. # Calls with different arguments will return different numbers.
  2276. sub ShortIdFor {
  2277. my $key = shift;
  2278. my $id = $main::uniqueid{$key};
  2279. if (!defined($id)) {
  2280. $id = keys(%main::uniqueid) + 1;
  2281. $main::uniqueid{$key} = $id;
  2282. }
  2283. return $id;
  2284. }
  2285. # Translate a stack of addresses into a stack of symbols
  2286. sub TranslateStack {
  2287. my $symbols = shift;
  2288. my $fullname_to_shortname_map = shift;
  2289. my $k = shift;
  2290. my @addrs = split(/\n/, $k);
  2291. my @result = ();
  2292. for (my $i = 0; $i <= $#addrs; $i++) {
  2293. my $a = $addrs[$i];
  2294. # Skip large addresses since they sometimes show up as fake entries on RH9
  2295. if (length($a) > 8 && $a gt "7fffffffffffffff") {
  2296. next;
  2297. }
  2298. if ($main::opt_disasm || $main::opt_list) {
  2299. # We want just the address for the key
  2300. push(@result, $a);
  2301. next;
  2302. }
  2303. my $symlist = $symbols->{$a};
  2304. if (!defined($symlist)) {
  2305. $symlist = [$a, "", $a];
  2306. }
  2307. # We can have a sequence of symbols for a particular entry
  2308. # (more than one symbol in the case of inlining). Callers
  2309. # come before callees in symlist, so walk backwards since
  2310. # the translated stack should contain callees before callers.
  2311. for (my $j = $#{$symlist}; $j >= 2; $j -= 3) {
  2312. my $func = $symlist->[$j-2];
  2313. my $fileline = $symlist->[$j-1];
  2314. my $fullfunc = $symlist->[$j];
  2315. if (defined($fullname_to_shortname_map->{$fullfunc})) {
  2316. $func = $fullname_to_shortname_map->{$fullfunc};
  2317. }
  2318. if ($j > 2) {
  2319. $func = "$func (inline)";
  2320. }
  2321. # Do not merge nodes corresponding to Callback::Run since that
  2322. # causes confusing cycles in dot display. Instead, we synthesize
  2323. # a unique name for this frame per caller.
  2324. if ($func =~ m/Callback.*::Run$/) {
  2325. my $caller = ($i > 0) ? $addrs[$i-1] : 0;
  2326. $func = "Run#" . ShortIdFor($caller);
  2327. }
  2328. if ($main::opt_addresses) {
  2329. push(@result, "$a $func $fileline");
  2330. } elsif ($main::opt_lines) {
  2331. if ($func eq '??' && $fileline eq '??:0') {
  2332. push(@result, "$a");
  2333. } else {
  2334. push(@result, "$func $fileline");
  2335. }
  2336. } elsif ($main::opt_functions) {
  2337. if ($func eq '??') {
  2338. push(@result, "$a");
  2339. } else {
  2340. push(@result, $func);
  2341. }
  2342. } elsif ($main::opt_files) {
  2343. if ($fileline eq '??:0' || $fileline eq '') {
  2344. push(@result, "$a");
  2345. } else {
  2346. my $f = $fileline;
  2347. $f =~ s/:\d+$//;
  2348. push(@result, $f);
  2349. }
  2350. } else {
  2351. push(@result, $a);
  2352. last; # Do not print inlined info
  2353. }
  2354. }
  2355. }
  2356. # print join(",", @addrs), " => ", join(",", @result), "\n";
  2357. return @result;
  2358. }
  2359. # Generate percent string for a number and a total
  2360. sub Percent {
  2361. my $num = shift;
  2362. my $tot = shift;
  2363. if ($tot != 0) {
  2364. return sprintf("%.1f%%", $num * 100.0 / $tot);
  2365. } else {
  2366. return ($num == 0) ? "nan" : (($num > 0) ? "+inf" : "-inf");
  2367. }
  2368. }
  2369. # Generate pretty-printed form of number
  2370. sub Unparse {
  2371. my $num = shift;
  2372. if ($main::profile_type eq 'heap' || $main::profile_type eq 'growth') {
  2373. if ($main::opt_inuse_objects || $main::opt_alloc_objects) {
  2374. return sprintf("%d", $num);
  2375. } else {
  2376. if ($main::opt_show_bytes) {
  2377. return sprintf("%d", $num);
  2378. } else {
  2379. return sprintf("%.1f", $num / 1048576.0);
  2380. }
  2381. }
  2382. } elsif ($main::profile_type eq 'contention' && !$main::opt_contentions) {
  2383. return sprintf("%.3f", $num / 1e9); # Convert nanoseconds to seconds
  2384. } else {
  2385. return sprintf("%d", $num);
  2386. }
  2387. }
  2388. # Alternate pretty-printed form: 0 maps to "."
  2389. sub UnparseAlt {
  2390. my $num = shift;
  2391. if ($num == 0) {
  2392. return ".";
  2393. } else {
  2394. return Unparse($num);
  2395. }
  2396. }
  2397. # Alternate pretty-printed form: 0 maps to ""
  2398. sub HtmlPrintNumber {
  2399. my $num = shift;
  2400. if ($num == 0) {
  2401. return "";
  2402. } else {
  2403. return Unparse($num);
  2404. }
  2405. }
  2406. # Return output units
  2407. sub Units {
  2408. if ($main::profile_type eq 'heap' || $main::profile_type eq 'growth') {
  2409. if ($main::opt_inuse_objects || $main::opt_alloc_objects) {
  2410. return "objects";
  2411. } else {
  2412. if ($main::opt_show_bytes) {
  2413. return "B";
  2414. } else {
  2415. return "MB";
  2416. }
  2417. }
  2418. } elsif ($main::profile_type eq 'contention' && !$main::opt_contentions) {
  2419. return "seconds";
  2420. } else {
  2421. return "samples";
  2422. }
  2423. }
  2424. ##### Profile manipulation code #####
  2425. # Generate flattened profile:
  2426. # If count is charged to stack [a,b,c,d], in generated profile,
  2427. # it will be charged to [a]
  2428. sub FlatProfile {
  2429. my $profile = shift;
  2430. my $result = {};
  2431. foreach my $k (keys(%{$profile})) {
  2432. my $count = $profile->{$k};
  2433. my @addrs = split(/\n/, $k);
  2434. if ($#addrs >= 0) {
  2435. AddEntry($result, $addrs[0], $count);
  2436. }
  2437. }
  2438. return $result;
  2439. }
  2440. # Generate cumulative profile:
  2441. # If count is charged to stack [a,b,c,d], in generated profile,
  2442. # it will be charged to [a], [b], [c], [d]
  2443. sub CumulativeProfile {
  2444. my $profile = shift;
  2445. my $result = {};
  2446. foreach my $k (keys(%{$profile})) {
  2447. my $count = $profile->{$k};
  2448. my @addrs = split(/\n/, $k);
  2449. foreach my $a (@addrs) {
  2450. AddEntry($result, $a, $count);
  2451. }
  2452. }
  2453. return $result;
  2454. }
  2455. # If the second-youngest PC on the stack is always the same, returns
  2456. # that pc. Otherwise, returns undef.
  2457. sub IsSecondPcAlwaysTheSame {
  2458. my $profile = shift;
  2459. my $second_pc = undef;
  2460. foreach my $k (keys(%{$profile})) {
  2461. my @addrs = split(/\n/, $k);
  2462. if ($#addrs < 1) {
  2463. return undef;
  2464. }
  2465. if (not defined $second_pc) {
  2466. $second_pc = $addrs[1];
  2467. } else {
  2468. if ($second_pc ne $addrs[1]) {
  2469. return undef;
  2470. }
  2471. }
  2472. }
  2473. return $second_pc;
  2474. }
  2475. sub ExtractSymbolLocation {
  2476. my $symbols = shift;
  2477. my $address = shift;
  2478. # 'addr2line' outputs "??:0" for unknown locations; we do the
  2479. # same to be consistent.
  2480. my $location = "??:0:unknown";
  2481. if (exists $symbols->{$address}) {
  2482. my $file = $symbols->{$address}->[1];
  2483. if ($file eq "?") {
  2484. $file = "??:0"
  2485. }
  2486. $location = $file . ":" . $symbols->{$address}->[0];
  2487. }
  2488. return $location;
  2489. }
  2490. # Extracts a graph of calls.
  2491. sub ExtractCalls {
  2492. my $symbols = shift;
  2493. my $profile = shift;
  2494. my $calls = {};
  2495. while( my ($stack_trace, $count) = each %$profile ) {
  2496. my @address = split(/\n/, $stack_trace);
  2497. my $destination = ExtractSymbolLocation($symbols, $address[0]);
  2498. AddEntry($calls, $destination, $count);
  2499. for (my $i = 1; $i <= $#address; $i++) {
  2500. my $source = ExtractSymbolLocation($symbols, $address[$i]);
  2501. my $call = "$source -> $destination";
  2502. AddEntry($calls, $call, $count);
  2503. $destination = $source;
  2504. }
  2505. }
  2506. return $calls;
  2507. }
  2508. sub RemoveUninterestingFrames {
  2509. my $symbols = shift;
  2510. my $profile = shift;
  2511. # List of function names to skip
  2512. my %skip = ();
  2513. my $skip_regexp = 'NOMATCH';
  2514. if ($main::profile_type eq 'heap' || $main::profile_type eq 'growth') {
  2515. foreach my $name ('calloc',
  2516. 'cfree',
  2517. 'malloc',
  2518. 'free',
  2519. 'memalign',
  2520. 'posix_memalign',
  2521. 'aligned_alloc',
  2522. 'pvalloc',
  2523. 'valloc',
  2524. 'realloc',
  2525. 'mallocx', # jemalloc
  2526. 'rallocx', # jemalloc
  2527. 'xallocx', # jemalloc
  2528. 'dallocx', # jemalloc
  2529. 'sdallocx', # jemalloc
  2530. 'tc_calloc',
  2531. 'tc_cfree',
  2532. 'tc_malloc',
  2533. 'tc_free',
  2534. 'tc_memalign',
  2535. 'tc_posix_memalign',
  2536. 'tc_pvalloc',
  2537. 'tc_valloc',
  2538. 'tc_realloc',
  2539. 'tc_new',
  2540. 'tc_delete',
  2541. 'tc_newarray',
  2542. 'tc_deletearray',
  2543. 'tc_new_nothrow',
  2544. 'tc_newarray_nothrow',
  2545. 'do_malloc',
  2546. '::do_malloc', # new name -- got moved to an unnamed ns
  2547. '::do_malloc_or_cpp_alloc',
  2548. 'DoSampledAllocation',
  2549. 'simple_alloc::allocate',
  2550. '__malloc_alloc_template::allocate',
  2551. '__builtin_delete',
  2552. '__builtin_new',
  2553. '__builtin_vec_delete',
  2554. '__builtin_vec_new',
  2555. 'operator new',
  2556. 'operator new[]',
  2557. # The entry to our memory-allocation routines on OS X
  2558. 'malloc_zone_malloc',
  2559. 'malloc_zone_calloc',
  2560. 'malloc_zone_valloc',
  2561. 'malloc_zone_realloc',
  2562. 'malloc_zone_memalign',
  2563. 'malloc_zone_free',
  2564. # These mark the beginning/end of our custom sections
  2565. '__start_google_malloc',
  2566. '__stop_google_malloc',
  2567. '__start_malloc_hook',
  2568. '__stop_malloc_hook') {
  2569. $skip{$name} = 1;
  2570. $skip{"_" . $name} = 1; # Mach (OS X) adds a _ prefix to everything
  2571. }
  2572. # TODO: Remove TCMalloc once everything has been
  2573. # moved into the tcmalloc:: namespace and we have flushed
  2574. # old code out of the system.
  2575. $skip_regexp = "TCMalloc|^tcmalloc::";
  2576. } elsif ($main::profile_type eq 'contention') {
  2577. foreach my $vname ('base::RecordLockProfileData',
  2578. 'base::SubmitMutexProfileData',
  2579. 'base::SubmitSpinLockProfileData',
  2580. 'Mutex::Unlock',
  2581. 'Mutex::UnlockSlow',
  2582. 'Mutex::ReaderUnlock',
  2583. 'MutexLock::~MutexLock',
  2584. 'SpinLock::Unlock',
  2585. 'SpinLock::SlowUnlock',
  2586. 'SpinLockHolder::~SpinLockHolder') {
  2587. $skip{$vname} = 1;
  2588. }
  2589. } elsif ($main::profile_type eq 'cpu') {
  2590. # Drop signal handlers used for CPU profile collection
  2591. # TODO(dpeng): this should not be necessary; it's taken
  2592. # care of by the general 2nd-pc mechanism below.
  2593. foreach my $name ('ProfileData::Add', # historical
  2594. 'ProfileData::prof_handler', # historical
  2595. 'CpuProfiler::prof_handler',
  2596. '__FRAME_END__',
  2597. '__pthread_sighandler',
  2598. '__restore') {
  2599. $skip{$name} = 1;
  2600. }
  2601. } else {
  2602. # Nothing skipped for unknown types
  2603. }
  2604. if ($main::profile_type eq 'cpu') {
  2605. # If all the second-youngest program counters are the same,
  2606. # this STRONGLY suggests that it is an artifact of measurement,
  2607. # i.e., stack frames pushed by the CPU profiler signal handler.
  2608. # Hence, we delete them.
  2609. # (The topmost PC is read from the signal structure, not from
  2610. # the stack, so it does not get involved.)
  2611. while (my $second_pc = IsSecondPcAlwaysTheSame($profile)) {
  2612. my $result = {};
  2613. my $func = '';
  2614. if (exists($symbols->{$second_pc})) {
  2615. $second_pc = $symbols->{$second_pc}->[0];
  2616. }
  2617. print STDERR "Removing $second_pc from all stack traces.\n";
  2618. foreach my $k (keys(%{$profile})) {
  2619. my $count = $profile->{$k};
  2620. my @addrs = split(/\n/, $k);
  2621. splice @addrs, 1, 1;
  2622. my $reduced_path = join("\n", @addrs);
  2623. AddEntry($result, $reduced_path, $count);
  2624. }
  2625. $profile = $result;
  2626. }
  2627. }
  2628. my $result = {};
  2629. foreach my $k (keys(%{$profile})) {
  2630. my $count = $profile->{$k};
  2631. my @addrs = split(/\n/, $k);
  2632. my @path = ();
  2633. foreach my $a (@addrs) {
  2634. if (exists($symbols->{$a})) {
  2635. my $func = $symbols->{$a}->[0];
  2636. if ($skip{$func} || ($func =~ m/$skip_regexp/)) {
  2637. # Throw away the portion of the backtrace seen so far, under the
  2638. # assumption that previous frames were for functions internal to the
  2639. # allocator.
  2640. @path = ();
  2641. next;
  2642. }
  2643. }
  2644. push(@path, $a);
  2645. }
  2646. my $reduced_path = join("\n", @path);
  2647. AddEntry($result, $reduced_path, $count);
  2648. }
  2649. return $result;
  2650. }
  2651. # Reduce profile to granularity given by user
  2652. sub ReduceProfile {
  2653. my $symbols = shift;
  2654. my $profile = shift;
  2655. my $result = {};
  2656. my $fullname_to_shortname_map = {};
  2657. FillFullnameToShortnameMap($symbols, $fullname_to_shortname_map);
  2658. foreach my $k (keys(%{$profile})) {
  2659. my $count = $profile->{$k};
  2660. my @translated = TranslateStack($symbols, $fullname_to_shortname_map, $k);
  2661. my @path = ();
  2662. my %seen = ();
  2663. $seen{''} = 1; # So that empty keys are skipped
  2664. foreach my $e (@translated) {
  2665. # To avoid double-counting due to recursion, skip a stack-trace
  2666. # entry if it has already been seen
  2667. if (!$seen{$e}) {
  2668. $seen{$e} = 1;
  2669. push(@path, $e);
  2670. }
  2671. }
  2672. my $reduced_path = join("\n", @path);
  2673. AddEntry($result, $reduced_path, $count);
  2674. }
  2675. return $result;
  2676. }
  2677. # Does the specified symbol array match the regexp?
  2678. sub SymbolMatches {
  2679. my $sym = shift;
  2680. my $re = shift;
  2681. if (defined($sym)) {
  2682. for (my $i = 0; $i < $#{$sym}; $i += 3) {
  2683. if ($sym->[$i] =~ m/$re/ || $sym->[$i+1] =~ m/$re/) {
  2684. return 1;
  2685. }
  2686. }
  2687. }
  2688. return 0;
  2689. }
  2690. # Focus only on paths involving specified regexps
  2691. sub FocusProfile {
  2692. my $symbols = shift;
  2693. my $profile = shift;
  2694. my $focus = shift;
  2695. my $result = {};
  2696. foreach my $k (keys(%{$profile})) {
  2697. my $count = $profile->{$k};
  2698. my @addrs = split(/\n/, $k);
  2699. foreach my $a (@addrs) {
  2700. # Reply if it matches either the address/shortname/fileline
  2701. if (($a =~ m/$focus/) || SymbolMatches($symbols->{$a}, $focus)) {
  2702. AddEntry($result, $k, $count);
  2703. last;
  2704. }
  2705. }
  2706. }
  2707. return $result;
  2708. }
  2709. # Focus only on paths not involving specified regexps
  2710. sub IgnoreProfile {
  2711. my $symbols = shift;
  2712. my $profile = shift;
  2713. my $ignore = shift;
  2714. my $result = {};
  2715. foreach my $k (keys(%{$profile})) {
  2716. my $count = $profile->{$k};
  2717. my @addrs = split(/\n/, $k);
  2718. my $matched = 0;
  2719. foreach my $a (@addrs) {
  2720. # Reply if it matches either the address/shortname/fileline
  2721. if (($a =~ m/$ignore/) || SymbolMatches($symbols->{$a}, $ignore)) {
  2722. $matched = 1;
  2723. last;
  2724. }
  2725. }
  2726. if (!$matched) {
  2727. AddEntry($result, $k, $count);
  2728. }
  2729. }
  2730. return $result;
  2731. }
  2732. # Get total count in profile
  2733. sub TotalProfile {
  2734. my $profile = shift;
  2735. my $result = 0;
  2736. foreach my $k (keys(%{$profile})) {
  2737. $result += $profile->{$k};
  2738. }
  2739. return $result;
  2740. }
  2741. # Add A to B
  2742. sub AddProfile {
  2743. my $A = shift;
  2744. my $B = shift;
  2745. my $R = {};
  2746. # add all keys in A
  2747. foreach my $k (keys(%{$A})) {
  2748. my $v = $A->{$k};
  2749. AddEntry($R, $k, $v);
  2750. }
  2751. # add all keys in B
  2752. foreach my $k (keys(%{$B})) {
  2753. my $v = $B->{$k};
  2754. AddEntry($R, $k, $v);
  2755. }
  2756. return $R;
  2757. }
  2758. # Merges symbol maps
  2759. sub MergeSymbols {
  2760. my $A = shift;
  2761. my $B = shift;
  2762. my $R = {};
  2763. foreach my $k (keys(%{$A})) {
  2764. $R->{$k} = $A->{$k};
  2765. }
  2766. if (defined($B)) {
  2767. foreach my $k (keys(%{$B})) {
  2768. $R->{$k} = $B->{$k};
  2769. }
  2770. }
  2771. return $R;
  2772. }
  2773. # Add A to B
  2774. sub AddPcs {
  2775. my $A = shift;
  2776. my $B = shift;
  2777. my $R = {};
  2778. # add all keys in A
  2779. foreach my $k (keys(%{$A})) {
  2780. $R->{$k} = 1
  2781. }
  2782. # add all keys in B
  2783. foreach my $k (keys(%{$B})) {
  2784. $R->{$k} = 1
  2785. }
  2786. return $R;
  2787. }
  2788. # Subtract B from A
  2789. sub SubtractProfile {
  2790. my $A = shift;
  2791. my $B = shift;
  2792. my $R = {};
  2793. foreach my $k (keys(%{$A})) {
  2794. my $v = $A->{$k} - GetEntry($B, $k);
  2795. if ($v < 0 && $main::opt_drop_negative) {
  2796. $v = 0;
  2797. }
  2798. AddEntry($R, $k, $v);
  2799. }
  2800. if (!$main::opt_drop_negative) {
  2801. # Take care of when subtracted profile has more entries
  2802. foreach my $k (keys(%{$B})) {
  2803. if (!exists($A->{$k})) {
  2804. AddEntry($R, $k, 0 - $B->{$k});
  2805. }
  2806. }
  2807. }
  2808. return $R;
  2809. }
  2810. # Get entry from profile; zero if not present
  2811. sub GetEntry {
  2812. my $profile = shift;
  2813. my $k = shift;
  2814. if (exists($profile->{$k})) {
  2815. return $profile->{$k};
  2816. } else {
  2817. return 0;
  2818. }
  2819. }
  2820. # Add entry to specified profile
  2821. sub AddEntry {
  2822. my $profile = shift;
  2823. my $k = shift;
  2824. my $n = shift;
  2825. if (!exists($profile->{$k})) {
  2826. $profile->{$k} = 0;
  2827. }
  2828. $profile->{$k} += $n;
  2829. }
  2830. # Add a stack of entries to specified profile, and add them to the $pcs
  2831. # list.
  2832. sub AddEntries {
  2833. my $profile = shift;
  2834. my $pcs = shift;
  2835. my $stack = shift;
  2836. my $count = shift;
  2837. my @k = ();
  2838. foreach my $e (split(/\s+/, $stack)) {
  2839. my $pc = HexExtend($e);
  2840. $pcs->{$pc} = 1;
  2841. push @k, $pc;
  2842. }
  2843. AddEntry($profile, (join "\n", @k), $count);
  2844. }
  2845. ##### Code to profile a server dynamically #####
  2846. sub CheckSymbolPage {
  2847. my $url = SymbolPageURL();
  2848. my $command = ShellEscape(@URL_FETCHER, $url);
  2849. open(SYMBOL, "$command |") or error($command);
  2850. my $line = <SYMBOL>;
  2851. $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
  2852. close(SYMBOL);
  2853. unless (defined($line)) {
  2854. error("$url doesn't exist\n");
  2855. }
  2856. if ($line =~ /^num_symbols:\s+(\d+)$/) {
  2857. if ($1 == 0) {
  2858. error("Stripped binary. No symbols available.\n");
  2859. }
  2860. } else {
  2861. error("Failed to get the number of symbols from $url\n");
  2862. }
  2863. }
  2864. sub IsProfileURL {
  2865. my $profile_name = shift;
  2866. if (-f $profile_name) {
  2867. printf STDERR "Using local file $profile_name.\n";
  2868. return 0;
  2869. }
  2870. return 1;
  2871. }
  2872. sub ParseProfileURL {
  2873. my $profile_name = shift;
  2874. if (!defined($profile_name) || $profile_name eq "") {
  2875. return ();
  2876. }
  2877. # Split profile URL - matches all non-empty strings, so no test.
  2878. $profile_name =~ m,^(https?://)?([^/]+)(.*?)(/|$PROFILES)?$,;
  2879. my $proto = $1 || "http://";
  2880. my $hostport = $2;
  2881. my $prefix = $3;
  2882. my $profile = $4 || "/";
  2883. my $host = $hostport;
  2884. $host =~ s/:.*//;
  2885. my $baseurl = "$proto$hostport$prefix";
  2886. return ($host, $baseurl, $profile);
  2887. }
  2888. # We fetch symbols from the first profile argument.
  2889. sub SymbolPageURL {
  2890. my ($host, $baseURL, $path) = ParseProfileURL($main::pfile_args[0]);
  2891. return "$baseURL$SYMBOL_PAGE";
  2892. }
  2893. sub FetchProgramName() {
  2894. my ($host, $baseURL, $path) = ParseProfileURL($main::pfile_args[0]);
  2895. my $url = "$baseURL$PROGRAM_NAME_PAGE";
  2896. my $command_line = ShellEscape(@URL_FETCHER, $url);
  2897. open(CMDLINE, "$command_line |") or error($command_line);
  2898. my $cmdline = <CMDLINE>;
  2899. $cmdline =~ s/\r//g; # turn windows-looking lines into unix-looking lines
  2900. close(CMDLINE);
  2901. error("Failed to get program name from $url\n") unless defined($cmdline);
  2902. $cmdline =~ s/\x00.+//; # Remove argv[1] and latters.
  2903. $cmdline =~ s!\n!!g; # Remove LFs.
  2904. return $cmdline;
  2905. }
  2906. # Gee, curl's -L (--location) option isn't reliable at least
  2907. # with its 7.12.3 version. Curl will forget to post data if
  2908. # there is a redirection. This function is a workaround for
  2909. # curl. Redirection happens on borg hosts.
  2910. sub ResolveRedirectionForCurl {
  2911. my $url = shift;
  2912. my $command_line = ShellEscape(@URL_FETCHER, "--head", $url);
  2913. open(CMDLINE, "$command_line |") or error($command_line);
  2914. while (<CMDLINE>) {
  2915. s/\r//g; # turn windows-looking lines into unix-looking lines
  2916. if (/^Location: (.*)/) {
  2917. $url = $1;
  2918. }
  2919. }
  2920. close(CMDLINE);
  2921. return $url;
  2922. }
  2923. # Add a timeout flat to URL_FETCHER. Returns a new list.
  2924. sub AddFetchTimeout {
  2925. my $timeout = shift;
  2926. my @fetcher = shift;
  2927. if (defined($timeout)) {
  2928. if (join(" ", @fetcher) =~ m/\bcurl -s/) {
  2929. push(@fetcher, "--max-time", sprintf("%d", $timeout));
  2930. } elsif (join(" ", @fetcher) =~ m/\brpcget\b/) {
  2931. push(@fetcher, sprintf("--deadline=%d", $timeout));
  2932. }
  2933. }
  2934. return @fetcher;
  2935. }
  2936. # Reads a symbol map from the file handle name given as $1, returning
  2937. # the resulting symbol map. Also processes variables relating to symbols.
  2938. # Currently, the only variable processed is 'binary=<value>' which updates
  2939. # $main::prog to have the correct program name.
  2940. sub ReadSymbols {
  2941. my $in = shift;
  2942. my $map = {};
  2943. while (<$in>) {
  2944. s/\r//g; # turn windows-looking lines into unix-looking lines
  2945. # Removes all the leading zeroes from the symbols, see comment below.
  2946. if (m/^0x0*([0-9a-f]+)\s+(.+)/) {
  2947. $map->{$1} = $2;
  2948. } elsif (m/^---/) {
  2949. last;
  2950. } elsif (m/^([a-z][^=]*)=(.*)$/ ) {
  2951. my ($variable, $value) = ($1, $2);
  2952. for ($variable, $value) {
  2953. s/^\s+//;
  2954. s/\s+$//;
  2955. }
  2956. if ($variable eq "binary") {
  2957. if ($main::prog ne $UNKNOWN_BINARY && $main::prog ne $value) {
  2958. printf STDERR ("Warning: Mismatched binary name '%s', using '%s'.\n",
  2959. $main::prog, $value);
  2960. }
  2961. $main::prog = $value;
  2962. } else {
  2963. printf STDERR ("Ignoring unknown variable in symbols list: " .
  2964. "'%s' = '%s'\n", $variable, $value);
  2965. }
  2966. }
  2967. }
  2968. return $map;
  2969. }
  2970. # Fetches and processes symbols to prepare them for use in the profile output
  2971. # code. If the optional 'symbol_map' arg is not given, fetches symbols from
  2972. # $SYMBOL_PAGE for all PC values found in profile. Otherwise, the raw symbols
  2973. # are assumed to have already been fetched into 'symbol_map' and are simply
  2974. # extracted and processed.
  2975. sub FetchSymbols {
  2976. my $pcset = shift;
  2977. my $symbol_map = shift;
  2978. my %seen = ();
  2979. my @pcs = grep { !$seen{$_}++ } keys(%$pcset); # uniq
  2980. if (!defined($symbol_map)) {
  2981. my $post_data = join("+", sort((map {"0x" . "$_"} @pcs)));
  2982. open(POSTFILE, ">$main::tmpfile_sym");
  2983. print POSTFILE $post_data;
  2984. close(POSTFILE);
  2985. my $url = SymbolPageURL();
  2986. my $command_line;
  2987. if (join(" ", @URL_FETCHER) =~ m/\bcurl -s/) {
  2988. $url = ResolveRedirectionForCurl($url);
  2989. $command_line = ShellEscape(@URL_FETCHER, "-d", "\@$main::tmpfile_sym",
  2990. $url);
  2991. } else {
  2992. $command_line = (ShellEscape(@URL_FETCHER, "--post", $url)
  2993. . " < " . ShellEscape($main::tmpfile_sym));
  2994. }
  2995. # We use c++filt in case $SYMBOL_PAGE gives us mangled symbols.
  2996. my $escaped_cppfilt = ShellEscape($obj_tool_map{"c++filt"});
  2997. open(SYMBOL, "$command_line | $escaped_cppfilt |") or error($command_line);
  2998. $symbol_map = ReadSymbols(*SYMBOL{IO});
  2999. close(SYMBOL);
  3000. }
  3001. my $symbols = {};
  3002. foreach my $pc (@pcs) {
  3003. my $fullname;
  3004. # For 64 bits binaries, symbols are extracted with 8 leading zeroes.
  3005. # Then /symbol reads the long symbols in as uint64, and outputs
  3006. # the result with a "0x%08llx" format which get rid of the zeroes.
  3007. # By removing all the leading zeroes in both $pc and the symbols from
  3008. # /symbol, the symbols match and are retrievable from the map.
  3009. my $shortpc = $pc;
  3010. $shortpc =~ s/^0*//;
  3011. # Each line may have a list of names, which includes the function
  3012. # and also other functions it has inlined. They are separated (in
  3013. # PrintSymbolizedProfile), by --, which is illegal in function names.
  3014. my $fullnames;
  3015. if (defined($symbol_map->{$shortpc})) {
  3016. $fullnames = $symbol_map->{$shortpc};
  3017. } else {
  3018. $fullnames = "0x" . $pc; # Just use addresses
  3019. }
  3020. my $sym = [];
  3021. $symbols->{$pc} = $sym;
  3022. foreach my $fullname (split("--", $fullnames)) {
  3023. my $name = ShortFunctionName($fullname);
  3024. push(@{$sym}, $name, "?", $fullname);
  3025. }
  3026. }
  3027. return $symbols;
  3028. }
  3029. sub BaseName {
  3030. my $file_name = shift;
  3031. $file_name =~ s!^.*/!!; # Remove directory name
  3032. return $file_name;
  3033. }
  3034. sub MakeProfileBaseName {
  3035. my ($binary_name, $profile_name) = @_;
  3036. my ($host, $baseURL, $path) = ParseProfileURL($profile_name);
  3037. my $binary_shortname = BaseName($binary_name);
  3038. return sprintf("%s.%s.%s",
  3039. $binary_shortname, $main::op_time, $host);
  3040. }
  3041. sub FetchDynamicProfile {
  3042. my $binary_name = shift;
  3043. my $profile_name = shift;
  3044. my $fetch_name_only = shift;
  3045. my $encourage_patience = shift;
  3046. if (!IsProfileURL($profile_name)) {
  3047. return $profile_name;
  3048. } else {
  3049. my ($host, $baseURL, $path) = ParseProfileURL($profile_name);
  3050. if ($path eq "" || $path eq "/") {
  3051. # Missing type specifier defaults to cpu-profile
  3052. $path = $PROFILE_PAGE;
  3053. }
  3054. my $profile_file = MakeProfileBaseName($binary_name, $profile_name);
  3055. my $url = "$baseURL$path";
  3056. my $fetch_timeout = undef;
  3057. if ($path =~ m/$PROFILE_PAGE|$PMUPROFILE_PAGE/) {
  3058. if ($path =~ m/[?]/) {
  3059. $url .= "&";
  3060. } else {
  3061. $url .= "?";
  3062. }
  3063. $url .= sprintf("seconds=%d", $main::opt_seconds);
  3064. $fetch_timeout = $main::opt_seconds * 1.01 + 60;
  3065. } else {
  3066. # For non-CPU profiles, we add a type-extension to
  3067. # the target profile file name.
  3068. my $suffix = $path;
  3069. $suffix =~ s,/,.,g;
  3070. $profile_file .= $suffix;
  3071. }
  3072. my $profile_dir = $ENV{"JEPROF_TMPDIR"} || ($ENV{HOME} . "/jeprof");
  3073. if (! -d $profile_dir) {
  3074. mkdir($profile_dir)
  3075. || die("Unable to create profile directory $profile_dir: $!\n");
  3076. }
  3077. my $tmp_profile = "$profile_dir/.tmp.$profile_file";
  3078. my $real_profile = "$profile_dir/$profile_file";
  3079. if ($fetch_name_only > 0) {
  3080. return $real_profile;
  3081. }
  3082. my @fetcher = AddFetchTimeout($fetch_timeout, @URL_FETCHER);
  3083. my $cmd = ShellEscape(@fetcher, $url) . " > " . ShellEscape($tmp_profile);
  3084. if ($path =~ m/$PROFILE_PAGE|$PMUPROFILE_PAGE|$CENSUSPROFILE_PAGE/){
  3085. print STDERR "Gathering CPU profile from $url for $main::opt_seconds seconds to\n ${real_profile}\n";
  3086. if ($encourage_patience) {
  3087. print STDERR "Be patient...\n";
  3088. }
  3089. } else {
  3090. print STDERR "Fetching $path profile from $url to\n ${real_profile}\n";
  3091. }
  3092. (system($cmd) == 0) || error("Failed to get profile: $cmd: $!\n");
  3093. (system("mv", $tmp_profile, $real_profile) == 0) || error("Unable to rename profile\n");
  3094. print STDERR "Wrote profile to $real_profile\n";
  3095. $main::collected_profile = $real_profile;
  3096. return $main::collected_profile;
  3097. }
  3098. }
  3099. # Collect profiles in parallel
  3100. sub FetchDynamicProfiles {
  3101. my $items = scalar(@main::pfile_args);
  3102. my $levels = log($items) / log(2);
  3103. if ($items == 1) {
  3104. $main::profile_files[0] = FetchDynamicProfile($main::prog, $main::pfile_args[0], 0, 1);
  3105. } else {
  3106. # math rounding issues
  3107. if ((2 ** $levels) < $items) {
  3108. $levels++;
  3109. }
  3110. my $count = scalar(@main::pfile_args);
  3111. for (my $i = 0; $i < $count; $i++) {
  3112. $main::profile_files[$i] = FetchDynamicProfile($main::prog, $main::pfile_args[$i], 1, 0);
  3113. }
  3114. print STDERR "Fetching $count profiles, Be patient...\n";
  3115. FetchDynamicProfilesRecurse($levels, 0, 0);
  3116. $main::collected_profile = join(" \\\n ", @main::profile_files);
  3117. }
  3118. }
  3119. # Recursively fork a process to get enough processes
  3120. # collecting profiles
  3121. sub FetchDynamicProfilesRecurse {
  3122. my $maxlevel = shift;
  3123. my $level = shift;
  3124. my $position = shift;
  3125. if (my $pid = fork()) {
  3126. $position = 0 | ($position << 1);
  3127. TryCollectProfile($maxlevel, $level, $position);
  3128. wait;
  3129. } else {
  3130. $position = 1 | ($position << 1);
  3131. TryCollectProfile($maxlevel, $level, $position);
  3132. cleanup();
  3133. exit(0);
  3134. }
  3135. }
  3136. # Collect a single profile
  3137. sub TryCollectProfile {
  3138. my $maxlevel = shift;
  3139. my $level = shift;
  3140. my $position = shift;
  3141. if ($level >= ($maxlevel - 1)) {
  3142. if ($position < scalar(@main::pfile_args)) {
  3143. FetchDynamicProfile($main::prog, $main::pfile_args[$position], 0, 0);
  3144. }
  3145. } else {
  3146. FetchDynamicProfilesRecurse($maxlevel, $level+1, $position);
  3147. }
  3148. }
  3149. ##### Parsing code #####
  3150. # Provide a small streaming-read module to handle very large
  3151. # cpu-profile files. Stream in chunks along a sliding window.
  3152. # Provides an interface to get one 'slot', correctly handling
  3153. # endian-ness differences. A slot is one 32-bit or 64-bit word
  3154. # (depending on the input profile). We tell endianness and bit-size
  3155. # for the profile by looking at the first 8 bytes: in cpu profiles,
  3156. # the second slot is always 3 (we'll accept anything that's not 0).
  3157. BEGIN {
  3158. package CpuProfileStream;
  3159. sub new {
  3160. my ($class, $file, $fname) = @_;
  3161. my $self = { file => $file,
  3162. base => 0,
  3163. stride => 512 * 1024, # must be a multiple of bitsize/8
  3164. slots => [],
  3165. unpack_code => "", # N for big-endian, V for little
  3166. perl_is_64bit => 1, # matters if profile is 64-bit
  3167. };
  3168. bless $self, $class;
  3169. # Let unittests adjust the stride
  3170. if ($main::opt_test_stride > 0) {
  3171. $self->{stride} = $main::opt_test_stride;
  3172. }
  3173. # Read the first two slots to figure out bitsize and endianness.
  3174. my $slots = $self->{slots};
  3175. my $str;
  3176. read($self->{file}, $str, 8);
  3177. # Set the global $address_length based on what we see here.
  3178. # 8 is 32-bit (8 hexadecimal chars); 16 is 64-bit (16 hexadecimal chars).
  3179. $address_length = ($str eq (chr(0)x8)) ? 16 : 8;
  3180. if ($address_length == 8) {
  3181. if (substr($str, 6, 2) eq chr(0)x2) {
  3182. $self->{unpack_code} = 'V'; # Little-endian.
  3183. } elsif (substr($str, 4, 2) eq chr(0)x2) {
  3184. $self->{unpack_code} = 'N'; # Big-endian
  3185. } else {
  3186. ::error("$fname: header size >= 2**16\n");
  3187. }
  3188. @$slots = unpack($self->{unpack_code} . "*", $str);
  3189. } else {
  3190. # If we're a 64-bit profile, check if we're a 64-bit-capable
  3191. # perl. Otherwise, each slot will be represented as a float
  3192. # instead of an int64, losing precision and making all the
  3193. # 64-bit addresses wrong. We won't complain yet, but will
  3194. # later if we ever see a value that doesn't fit in 32 bits.
  3195. my $has_q = 0;
  3196. eval { $has_q = pack("Q", "1") ? 1 : 1; };
  3197. if (!$has_q) {
  3198. $self->{perl_is_64bit} = 0;
  3199. }
  3200. read($self->{file}, $str, 8);
  3201. if (substr($str, 4, 4) eq chr(0)x4) {
  3202. # We'd love to use 'Q', but it's a) not universal, b) not endian-proof.
  3203. $self->{unpack_code} = 'V'; # Little-endian.
  3204. } elsif (substr($str, 0, 4) eq chr(0)x4) {
  3205. $self->{unpack_code} = 'N'; # Big-endian
  3206. } else {
  3207. ::error("$fname: header size >= 2**32\n");
  3208. }
  3209. my @pair = unpack($self->{unpack_code} . "*", $str);
  3210. # Since we know one of the pair is 0, it's fine to just add them.
  3211. @$slots = (0, $pair[0] + $pair[1]);
  3212. }
  3213. return $self;
  3214. }
  3215. # Load more data when we access slots->get(X) which is not yet in memory.
  3216. sub overflow {
  3217. my ($self) = @_;
  3218. my $slots = $self->{slots};
  3219. $self->{base} += $#$slots + 1; # skip over data we're replacing
  3220. my $str;
  3221. read($self->{file}, $str, $self->{stride});
  3222. if ($address_length == 8) { # the 32-bit case
  3223. # This is the easy case: unpack provides 32-bit unpacking primitives.
  3224. @$slots = unpack($self->{unpack_code} . "*", $str);
  3225. } else {
  3226. # We need to unpack 32 bits at a time and combine.
  3227. my @b32_values = unpack($self->{unpack_code} . "*", $str);
  3228. my @b64_values = ();
  3229. for (my $i = 0; $i < $#b32_values; $i += 2) {
  3230. # TODO(csilvers): if this is a 32-bit perl, the math below
  3231. # could end up in a too-large int, which perl will promote
  3232. # to a double, losing necessary precision. Deal with that.
  3233. # Right now, we just die.
  3234. my ($lo, $hi) = ($b32_values[$i], $b32_values[$i+1]);
  3235. if ($self->{unpack_code} eq 'N') { # big-endian
  3236. ($lo, $hi) = ($hi, $lo);
  3237. }
  3238. my $value = $lo + $hi * (2**32);
  3239. if (!$self->{perl_is_64bit} && # check value is exactly represented
  3240. (($value % (2**32)) != $lo || int($value / (2**32)) != $hi)) {
  3241. ::error("Need a 64-bit perl to process this 64-bit profile.\n");
  3242. }
  3243. push(@b64_values, $value);
  3244. }
  3245. @$slots = @b64_values;
  3246. }
  3247. }
  3248. # Access the i-th long in the file (logically), or -1 at EOF.
  3249. sub get {
  3250. my ($self, $idx) = @_;
  3251. my $slots = $self->{slots};
  3252. while ($#$slots >= 0) {
  3253. if ($idx < $self->{base}) {
  3254. # The only time we expect a reference to $slots[$i - something]
  3255. # after referencing $slots[$i] is reading the very first header.
  3256. # Since $stride > |header|, that shouldn't cause any lookback
  3257. # errors. And everything after the header is sequential.
  3258. print STDERR "Unexpected look-back reading CPU profile";
  3259. return -1; # shrug, don't know what better to return
  3260. } elsif ($idx > $self->{base} + $#$slots) {
  3261. $self->overflow();
  3262. } else {
  3263. return $slots->[$idx - $self->{base}];
  3264. }
  3265. }
  3266. # If we get here, $slots is [], which means we've reached EOF
  3267. return -1; # unique since slots is supposed to hold unsigned numbers
  3268. }
  3269. }
  3270. # Reads the top, 'header' section of a profile, and returns the last
  3271. # line of the header, commonly called a 'header line'. The header
  3272. # section of a profile consists of zero or more 'command' lines that
  3273. # are instructions to jeprof, which jeprof executes when reading the
  3274. # header. All 'command' lines start with a %. After the command
  3275. # lines is the 'header line', which is a profile-specific line that
  3276. # indicates what type of profile it is, and perhaps other global
  3277. # information about the profile. For instance, here's a header line
  3278. # for a heap profile:
  3279. # heap profile: 53: 38236 [ 5525: 1284029] @ heapprofile
  3280. # For historical reasons, the CPU profile does not contain a text-
  3281. # readable header line. If the profile looks like a CPU profile,
  3282. # this function returns "". If no header line could be found, this
  3283. # function returns undef.
  3284. #
  3285. # The following commands are recognized:
  3286. # %warn -- emit the rest of this line to stderr, prefixed by 'WARNING:'
  3287. #
  3288. # The input file should be in binmode.
  3289. sub ReadProfileHeader {
  3290. local *PROFILE = shift;
  3291. my $firstchar = "";
  3292. my $line = "";
  3293. read(PROFILE, $firstchar, 1);
  3294. seek(PROFILE, -1, 1); # unread the firstchar
  3295. if ($firstchar !~ /[[:print:]]/) { # is not a text character
  3296. return "";
  3297. }
  3298. while (defined($line = <PROFILE>)) {
  3299. $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
  3300. if ($line =~ /^%warn\s+(.*)/) { # 'warn' command
  3301. # Note this matches both '%warn blah\n' and '%warn\n'.
  3302. print STDERR "WARNING: $1\n"; # print the rest of the line
  3303. } elsif ($line =~ /^%/) {
  3304. print STDERR "Ignoring unknown command from profile header: $line";
  3305. } else {
  3306. # End of commands, must be the header line.
  3307. return $line;
  3308. }
  3309. }
  3310. return undef; # got to EOF without seeing a header line
  3311. }
  3312. sub IsSymbolizedProfileFile {
  3313. my $file_name = shift;
  3314. if (!(-e $file_name) || !(-r $file_name)) {
  3315. return 0;
  3316. }
  3317. # Check if the file contains a symbol-section marker.
  3318. open(TFILE, "<$file_name");
  3319. binmode TFILE;
  3320. my $firstline = ReadProfileHeader(*TFILE);
  3321. close(TFILE);
  3322. if (!$firstline) {
  3323. return 0;
  3324. }
  3325. $SYMBOL_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  3326. my $symbol_marker = $&;
  3327. return $firstline =~ /^--- *$symbol_marker/;
  3328. }
  3329. # Parse profile generated by common/profiler.cc and return a reference
  3330. # to a map:
  3331. # $result->{version} Version number of profile file
  3332. # $result->{period} Sampling period (in microseconds)
  3333. # $result->{profile} Profile object
  3334. # $result->{threads} Map of thread IDs to profile objects
  3335. # $result->{map} Memory map info from profile
  3336. # $result->{pcs} Hash of all PC values seen, key is hex address
  3337. sub ReadProfile {
  3338. my $prog = shift;
  3339. my $fname = shift;
  3340. my $result; # return value
  3341. $CONTENTION_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  3342. my $contention_marker = $&;
  3343. $GROWTH_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  3344. my $growth_marker = $&;
  3345. $SYMBOL_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  3346. my $symbol_marker = $&;
  3347. $PROFILE_PAGE =~ m,[^/]+$,; # matches everything after the last slash
  3348. my $profile_marker = $&;
  3349. # Look at first line to see if it is a heap or a CPU profile.
  3350. # CPU profile may start with no header at all, and just binary data
  3351. # (starting with \0\0\0\0) -- in that case, don't try to read the
  3352. # whole firstline, since it may be gigabytes(!) of data.
  3353. open(PROFILE, "<$fname") || error("$fname: $!\n");
  3354. binmode PROFILE; # New perls do UTF-8 processing
  3355. my $header = ReadProfileHeader(*PROFILE);
  3356. if (!defined($header)) { # means "at EOF"
  3357. error("Profile is empty.\n");
  3358. }
  3359. my $symbols;
  3360. if ($header =~ m/^--- *$symbol_marker/o) {
  3361. # Verify that the user asked for a symbolized profile
  3362. if (!$main::use_symbolized_profile) {
  3363. # we have both a binary and symbolized profiles, abort
  3364. error("FATAL ERROR: Symbolized profile\n $fname\ncannot be used with " .
  3365. "a binary arg. Try again without passing\n $prog\n");
  3366. }
  3367. # Read the symbol section of the symbolized profile file.
  3368. $symbols = ReadSymbols(*PROFILE{IO});
  3369. # Read the next line to get the header for the remaining profile.
  3370. $header = ReadProfileHeader(*PROFILE) || "";
  3371. }
  3372. $main::profile_type = '';
  3373. if ($header =~ m/^heap profile:.*$growth_marker/o) {
  3374. $main::profile_type = 'growth';
  3375. $result = ReadHeapProfile($prog, *PROFILE, $header);
  3376. } elsif ($header =~ m/^heap profile:/) {
  3377. $main::profile_type = 'heap';
  3378. $result = ReadHeapProfile($prog, *PROFILE, $header);
  3379. } elsif ($header =~ m/^heap/) {
  3380. $main::profile_type = 'heap';
  3381. $result = ReadThreadedHeapProfile($prog, $fname, $header);
  3382. } elsif ($header =~ m/^--- *$contention_marker/o) {
  3383. $main::profile_type = 'contention';
  3384. $result = ReadSynchProfile($prog, *PROFILE);
  3385. } elsif ($header =~ m/^--- *Stacks:/) {
  3386. print STDERR
  3387. "Old format contention profile: mistakenly reports " .
  3388. "condition variable signals as lock contentions.\n";
  3389. $main::profile_type = 'contention';
  3390. $result = ReadSynchProfile($prog, *PROFILE);
  3391. } elsif ($header =~ m/^--- *$profile_marker/) {
  3392. # the binary cpu profile data starts immediately after this line
  3393. $main::profile_type = 'cpu';
  3394. $result = ReadCPUProfile($prog, $fname, *PROFILE);
  3395. } else {
  3396. if (defined($symbols)) {
  3397. # a symbolized profile contains a format we don't recognize, bail out
  3398. error("$fname: Cannot recognize profile section after symbols.\n");
  3399. }
  3400. # no ascii header present -- must be a CPU profile
  3401. $main::profile_type = 'cpu';
  3402. $result = ReadCPUProfile($prog, $fname, *PROFILE);
  3403. }
  3404. close(PROFILE);
  3405. # if we got symbols along with the profile, return those as well
  3406. if (defined($symbols)) {
  3407. $result->{symbols} = $symbols;
  3408. }
  3409. return $result;
  3410. }
  3411. # Subtract one from caller pc so we map back to call instr.
  3412. # However, don't do this if we're reading a symbolized profile
  3413. # file, in which case the subtract-one was done when the file
  3414. # was written.
  3415. #
  3416. # We apply the same logic to all readers, though ReadCPUProfile uses an
  3417. # independent implementation.
  3418. sub FixCallerAddresses {
  3419. my $stack = shift;
  3420. if ($main::use_symbolized_profile) {
  3421. return $stack;
  3422. } else {
  3423. $stack =~ /(\s)/;
  3424. my $delimiter = $1;
  3425. my @addrs = split(' ', $stack);
  3426. my @fixedaddrs;
  3427. $#fixedaddrs = $#addrs;
  3428. if ($#addrs >= 0) {
  3429. $fixedaddrs[0] = $addrs[0];
  3430. }
  3431. for (my $i = 1; $i <= $#addrs; $i++) {
  3432. $fixedaddrs[$i] = AddressSub($addrs[$i], "0x1");
  3433. }
  3434. return join $delimiter, @fixedaddrs;
  3435. }
  3436. }
  3437. # CPU profile reader
  3438. sub ReadCPUProfile {
  3439. my $prog = shift;
  3440. my $fname = shift; # just used for logging
  3441. local *PROFILE = shift;
  3442. my $version;
  3443. my $period;
  3444. my $i;
  3445. my $profile = {};
  3446. my $pcs = {};
  3447. # Parse string into array of slots.
  3448. my $slots = CpuProfileStream->new(*PROFILE, $fname);
  3449. # Read header. The current header version is a 5-element structure
  3450. # containing:
  3451. # 0: header count (always 0)
  3452. # 1: header "words" (after this one: 3)
  3453. # 2: format version (0)
  3454. # 3: sampling period (usec)
  3455. # 4: unused padding (always 0)
  3456. if ($slots->get(0) != 0 ) {
  3457. error("$fname: not a profile file, or old format profile file\n");
  3458. }
  3459. $i = 2 + $slots->get(1);
  3460. $version = $slots->get(2);
  3461. $period = $slots->get(3);
  3462. # Do some sanity checking on these header values.
  3463. if ($version > (2**32) || $period > (2**32) || $i > (2**32) || $i < 5) {
  3464. error("$fname: not a profile file, or corrupted profile file\n");
  3465. }
  3466. # Parse profile
  3467. while ($slots->get($i) != -1) {
  3468. my $n = $slots->get($i++);
  3469. my $d = $slots->get($i++);
  3470. if ($d > (2**16)) { # TODO(csilvers): what's a reasonable max-stack-depth?
  3471. my $addr = sprintf("0%o", $i * ($address_length == 8 ? 4 : 8));
  3472. print STDERR "At index $i (address $addr):\n";
  3473. error("$fname: stack trace depth >= 2**32\n");
  3474. }
  3475. if ($slots->get($i) == 0) {
  3476. # End of profile data marker
  3477. $i += $d;
  3478. last;
  3479. }
  3480. # Make key out of the stack entries
  3481. my @k = ();
  3482. for (my $j = 0; $j < $d; $j++) {
  3483. my $pc = $slots->get($i+$j);
  3484. # Subtract one from caller pc so we map back to call instr.
  3485. # However, don't do this if we're reading a symbolized profile
  3486. # file, in which case the subtract-one was done when the file
  3487. # was written.
  3488. if ($j > 0 && !$main::use_symbolized_profile) {
  3489. $pc--;
  3490. }
  3491. $pc = sprintf("%0*x", $address_length, $pc);
  3492. $pcs->{$pc} = 1;
  3493. push @k, $pc;
  3494. }
  3495. AddEntry($profile, (join "\n", @k), $n);
  3496. $i += $d;
  3497. }
  3498. # Parse map
  3499. my $map = '';
  3500. seek(PROFILE, $i * 4, 0);
  3501. read(PROFILE, $map, (stat PROFILE)[7]);
  3502. my $r = {};
  3503. $r->{version} = $version;
  3504. $r->{period} = $period;
  3505. $r->{profile} = $profile;
  3506. $r->{libs} = ParseLibraries($prog, $map, $pcs);
  3507. $r->{pcs} = $pcs;
  3508. return $r;
  3509. }
  3510. sub HeapProfileIndex {
  3511. my $index = 1;
  3512. if ($main::opt_inuse_space) {
  3513. $index = 1;
  3514. } elsif ($main::opt_inuse_objects) {
  3515. $index = 0;
  3516. } elsif ($main::opt_alloc_space) {
  3517. $index = 3;
  3518. } elsif ($main::opt_alloc_objects) {
  3519. $index = 2;
  3520. }
  3521. return $index;
  3522. }
  3523. sub ReadMappedLibraries {
  3524. my $fh = shift;
  3525. my $map = "";
  3526. # Read the /proc/self/maps data
  3527. while (<$fh>) {
  3528. s/\r//g; # turn windows-looking lines into unix-looking lines
  3529. $map .= $_;
  3530. }
  3531. return $map;
  3532. }
  3533. sub ReadMemoryMap {
  3534. my $fh = shift;
  3535. my $map = "";
  3536. # Read /proc/self/maps data as formatted by DumpAddressMap()
  3537. my $buildvar = "";
  3538. while (<PROFILE>) {
  3539. s/\r//g; # turn windows-looking lines into unix-looking lines
  3540. # Parse "build=<dir>" specification if supplied
  3541. if (m/^\s*build=(.*)\n/) {
  3542. $buildvar = $1;
  3543. }
  3544. # Expand "$build" variable if available
  3545. $_ =~ s/\$build\b/$buildvar/g;
  3546. $map .= $_;
  3547. }
  3548. return $map;
  3549. }
  3550. sub AdjustSamples {
  3551. my ($sample_adjustment, $sampling_algorithm, $n1, $s1, $n2, $s2) = @_;
  3552. if ($sample_adjustment) {
  3553. if ($sampling_algorithm == 2) {
  3554. # Remote-heap version 2
  3555. # The sampling frequency is the rate of a Poisson process.
  3556. # This means that the probability of sampling an allocation of
  3557. # size X with sampling rate Y is 1 - exp(-X/Y)
  3558. if ($n1 != 0) {
  3559. my $ratio = (($s1*1.0)/$n1)/($sample_adjustment);
  3560. my $scale_factor = 1/(1 - exp(-$ratio));
  3561. $n1 *= $scale_factor;
  3562. $s1 *= $scale_factor;
  3563. }
  3564. if ($n2 != 0) {
  3565. my $ratio = (($s2*1.0)/$n2)/($sample_adjustment);
  3566. my $scale_factor = 1/(1 - exp(-$ratio));
  3567. $n2 *= $scale_factor;
  3568. $s2 *= $scale_factor;
  3569. }
  3570. } else {
  3571. # Remote-heap version 1
  3572. my $ratio;
  3573. $ratio = (($s1*1.0)/$n1)/($sample_adjustment);
  3574. if ($ratio < 1) {
  3575. $n1 /= $ratio;
  3576. $s1 /= $ratio;
  3577. }
  3578. $ratio = (($s2*1.0)/$n2)/($sample_adjustment);
  3579. if ($ratio < 1) {
  3580. $n2 /= $ratio;
  3581. $s2 /= $ratio;
  3582. }
  3583. }
  3584. }
  3585. return ($n1, $s1, $n2, $s2);
  3586. }
  3587. sub ReadHeapProfile {
  3588. my $prog = shift;
  3589. local *PROFILE = shift;
  3590. my $header = shift;
  3591. my $index = HeapProfileIndex();
  3592. # Find the type of this profile. The header line looks like:
  3593. # heap profile: 1246: 8800744 [ 1246: 8800744] @ <heap-url>/266053
  3594. # There are two pairs <count: size>, the first inuse objects/space, and the
  3595. # second allocated objects/space. This is followed optionally by a profile
  3596. # type, and if that is present, optionally by a sampling frequency.
  3597. # For remote heap profiles (v1):
  3598. # The interpretation of the sampling frequency is that the profiler, for
  3599. # each sample, calculates a uniformly distributed random integer less than
  3600. # the given value, and records the next sample after that many bytes have
  3601. # been allocated. Therefore, the expected sample interval is half of the
  3602. # given frequency. By default, if not specified, the expected sample
  3603. # interval is 128KB. Only remote-heap-page profiles are adjusted for
  3604. # sample size.
  3605. # For remote heap profiles (v2):
  3606. # The sampling frequency is the rate of a Poisson process. This means that
  3607. # the probability of sampling an allocation of size X with sampling rate Y
  3608. # is 1 - exp(-X/Y)
  3609. # For version 2, a typical header line might look like this:
  3610. # heap profile: 1922: 127792360 [ 1922: 127792360] @ <heap-url>_v2/524288
  3611. # the trailing number (524288) is the sampling rate. (Version 1 showed
  3612. # double the 'rate' here)
  3613. my $sampling_algorithm = 0;
  3614. my $sample_adjustment = 0;
  3615. chomp($header);
  3616. my $type = "unknown";
  3617. if ($header =~ m"^heap profile:\s*(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\](\s*@\s*([^/]*)(/(\d+))?)?") {
  3618. if (defined($6) && ($6 ne '')) {
  3619. $type = $6;
  3620. my $sample_period = $8;
  3621. # $type is "heapprofile" for profiles generated by the
  3622. # heap-profiler, and either "heap" or "heap_v2" for profiles
  3623. # generated by sampling directly within tcmalloc. It can also
  3624. # be "growth" for heap-growth profiles. The first is typically
  3625. # found for profiles generated locally, and the others for
  3626. # remote profiles.
  3627. if (($type eq "heapprofile") || ($type !~ /heap/) ) {
  3628. # No need to adjust for the sampling rate with heap-profiler-derived data
  3629. $sampling_algorithm = 0;
  3630. } elsif ($type =~ /_v2/) {
  3631. $sampling_algorithm = 2; # version 2 sampling
  3632. if (defined($sample_period) && ($sample_period ne '')) {
  3633. $sample_adjustment = int($sample_period);
  3634. }
  3635. } else {
  3636. $sampling_algorithm = 1; # version 1 sampling
  3637. if (defined($sample_period) && ($sample_period ne '')) {
  3638. $sample_adjustment = int($sample_period)/2;
  3639. }
  3640. }
  3641. } else {
  3642. # We detect whether or not this is a remote-heap profile by checking
  3643. # that the total-allocated stats ($n2,$s2) are exactly the
  3644. # same as the in-use stats ($n1,$s1). It is remotely conceivable
  3645. # that a non-remote-heap profile may pass this check, but it is hard
  3646. # to imagine how that could happen.
  3647. # In this case it's so old it's guaranteed to be remote-heap version 1.
  3648. my ($n1, $s1, $n2, $s2) = ($1, $2, $3, $4);
  3649. if (($n1 == $n2) && ($s1 == $s2)) {
  3650. # This is likely to be a remote-heap based sample profile
  3651. $sampling_algorithm = 1;
  3652. }
  3653. }
  3654. }
  3655. if ($sampling_algorithm > 0) {
  3656. # For remote-heap generated profiles, adjust the counts and sizes to
  3657. # account for the sample rate (we sample once every 128KB by default).
  3658. if ($sample_adjustment == 0) {
  3659. # Turn on profile adjustment.
  3660. $sample_adjustment = 128*1024;
  3661. print STDERR "Adjusting heap profiles for 1-in-128KB sampling rate\n";
  3662. } else {
  3663. printf STDERR ("Adjusting heap profiles for 1-in-%d sampling rate\n",
  3664. $sample_adjustment);
  3665. }
  3666. if ($sampling_algorithm > 1) {
  3667. # We don't bother printing anything for the original version (version 1)
  3668. printf STDERR "Heap version $sampling_algorithm\n";
  3669. }
  3670. }
  3671. my $profile = {};
  3672. my $pcs = {};
  3673. my $map = "";
  3674. while (<PROFILE>) {
  3675. s/\r//g; # turn windows-looking lines into unix-looking lines
  3676. if (/^MAPPED_LIBRARIES:/) {
  3677. $map .= ReadMappedLibraries(*PROFILE);
  3678. last;
  3679. }
  3680. if (/^--- Memory map:/) {
  3681. $map .= ReadMemoryMap(*PROFILE);
  3682. last;
  3683. }
  3684. # Read entry of the form:
  3685. # <count1>: <bytes1> [<count2>: <bytes2>] @ a1 a2 a3 ... an
  3686. s/^\s*//;
  3687. s/\s*$//;
  3688. if (m/^\s*(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\]\s+@\s+(.*)$/) {
  3689. my $stack = $5;
  3690. my ($n1, $s1, $n2, $s2) = ($1, $2, $3, $4);
  3691. my @counts = AdjustSamples($sample_adjustment, $sampling_algorithm,
  3692. $n1, $s1, $n2, $s2);
  3693. AddEntries($profile, $pcs, FixCallerAddresses($stack), $counts[$index]);
  3694. }
  3695. }
  3696. my $r = {};
  3697. $r->{version} = "heap";
  3698. $r->{period} = 1;
  3699. $r->{profile} = $profile;
  3700. $r->{libs} = ParseLibraries($prog, $map, $pcs);
  3701. $r->{pcs} = $pcs;
  3702. return $r;
  3703. }
  3704. sub ReadThreadedHeapProfile {
  3705. my ($prog, $fname, $header) = @_;
  3706. my $index = HeapProfileIndex();
  3707. my $sampling_algorithm = 0;
  3708. my $sample_adjustment = 0;
  3709. chomp($header);
  3710. my $type = "unknown";
  3711. # Assuming a very specific type of header for now.
  3712. if ($header =~ m"^heap_v2/(\d+)") {
  3713. $type = "_v2";
  3714. $sampling_algorithm = 2;
  3715. $sample_adjustment = int($1);
  3716. }
  3717. if ($type ne "_v2" || !defined($sample_adjustment)) {
  3718. die "Threaded heap profiles require v2 sampling with a sample rate\n";
  3719. }
  3720. my $profile = {};
  3721. my $thread_profiles = {};
  3722. my $pcs = {};
  3723. my $map = "";
  3724. my $stack = "";
  3725. while (<PROFILE>) {
  3726. s/\r//g;
  3727. if (/^MAPPED_LIBRARIES:/) {
  3728. $map .= ReadMappedLibraries(*PROFILE);
  3729. last;
  3730. }
  3731. if (/^--- Memory map:/) {
  3732. $map .= ReadMemoryMap(*PROFILE);
  3733. last;
  3734. }
  3735. # Read entry of the form:
  3736. # @ a1 a2 ... an
  3737. # t*: <count1>: <bytes1> [<count2>: <bytes2>]
  3738. # t1: <count1>: <bytes1> [<count2>: <bytes2>]
  3739. # ...
  3740. # tn: <count1>: <bytes1> [<count2>: <bytes2>]
  3741. s/^\s*//;
  3742. s/\s*$//;
  3743. if (m/^@\s+(.*)$/) {
  3744. $stack = $1;
  3745. } elsif (m/^\s*(t(\*|\d+)):\s+(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\]$/) {
  3746. if ($stack eq "") {
  3747. # Still in the header, so this is just a per-thread summary.
  3748. next;
  3749. }
  3750. my $thread = $2;
  3751. my ($n1, $s1, $n2, $s2) = ($3, $4, $5, $6);
  3752. my @counts = AdjustSamples($sample_adjustment, $sampling_algorithm,
  3753. $n1, $s1, $n2, $s2);
  3754. if ($thread eq "*") {
  3755. AddEntries($profile, $pcs, FixCallerAddresses($stack), $counts[$index]);
  3756. } else {
  3757. if (!exists($thread_profiles->{$thread})) {
  3758. $thread_profiles->{$thread} = {};
  3759. }
  3760. AddEntries($thread_profiles->{$thread}, $pcs,
  3761. FixCallerAddresses($stack), $counts[$index]);
  3762. }
  3763. }
  3764. }
  3765. my $r = {};
  3766. $r->{version} = "heap";
  3767. $r->{period} = 1;
  3768. $r->{profile} = $profile;
  3769. $r->{threads} = $thread_profiles;
  3770. $r->{libs} = ParseLibraries($prog, $map, $pcs);
  3771. $r->{pcs} = $pcs;
  3772. return $r;
  3773. }
  3774. sub ReadSynchProfile {
  3775. my $prog = shift;
  3776. local *PROFILE = shift;
  3777. my $header = shift;
  3778. my $map = '';
  3779. my $profile = {};
  3780. my $pcs = {};
  3781. my $sampling_period = 1;
  3782. my $cyclespernanosec = 2.8; # Default assumption for old binaries
  3783. my $seen_clockrate = 0;
  3784. my $line;
  3785. my $index = 0;
  3786. if ($main::opt_total_delay) {
  3787. $index = 0;
  3788. } elsif ($main::opt_contentions) {
  3789. $index = 1;
  3790. } elsif ($main::opt_mean_delay) {
  3791. $index = 2;
  3792. }
  3793. while ( $line = <PROFILE> ) {
  3794. $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
  3795. if ( $line =~ /^\s*(\d+)\s+(\d+) \@\s*(.*?)\s*$/ ) {
  3796. my ($cycles, $count, $stack) = ($1, $2, $3);
  3797. # Convert cycles to nanoseconds
  3798. $cycles /= $cyclespernanosec;
  3799. # Adjust for sampling done by application
  3800. $cycles *= $sampling_period;
  3801. $count *= $sampling_period;
  3802. my @values = ($cycles, $count, $cycles / $count);
  3803. AddEntries($profile, $pcs, FixCallerAddresses($stack), $values[$index]);
  3804. } elsif ( $line =~ /^(slow release).*thread \d+ \@\s*(.*?)\s*$/ ||
  3805. $line =~ /^\s*(\d+) \@\s*(.*?)\s*$/ ) {
  3806. my ($cycles, $stack) = ($1, $2);
  3807. if ($cycles !~ /^\d+$/) {
  3808. next;
  3809. }
  3810. # Convert cycles to nanoseconds
  3811. $cycles /= $cyclespernanosec;
  3812. # Adjust for sampling done by application
  3813. $cycles *= $sampling_period;
  3814. AddEntries($profile, $pcs, FixCallerAddresses($stack), $cycles);
  3815. } elsif ( $line =~ m/^([a-z][^=]*)=(.*)$/ ) {
  3816. my ($variable, $value) = ($1,$2);
  3817. for ($variable, $value) {
  3818. s/^\s+//;
  3819. s/\s+$//;
  3820. }
  3821. if ($variable eq "cycles/second") {
  3822. $cyclespernanosec = $value / 1e9;
  3823. $seen_clockrate = 1;
  3824. } elsif ($variable eq "sampling period") {
  3825. $sampling_period = $value;
  3826. } elsif ($variable eq "ms since reset") {
  3827. # Currently nothing is done with this value in jeprof
  3828. # So we just silently ignore it for now
  3829. } elsif ($variable eq "discarded samples") {
  3830. # Currently nothing is done with this value in jeprof
  3831. # So we just silently ignore it for now
  3832. } else {
  3833. printf STDERR ("Ignoring unnknown variable in /contention output: " .
  3834. "'%s' = '%s'\n",$variable,$value);
  3835. }
  3836. } else {
  3837. # Memory map entry
  3838. $map .= $line;
  3839. }
  3840. }
  3841. if (!$seen_clockrate) {
  3842. printf STDERR ("No cycles/second entry in profile; Guessing %.1f GHz\n",
  3843. $cyclespernanosec);
  3844. }
  3845. my $r = {};
  3846. $r->{version} = 0;
  3847. $r->{period} = $sampling_period;
  3848. $r->{profile} = $profile;
  3849. $r->{libs} = ParseLibraries($prog, $map, $pcs);
  3850. $r->{pcs} = $pcs;
  3851. return $r;
  3852. }
  3853. # Given a hex value in the form "0x1abcd" or "1abcd", return either
  3854. # "0001abcd" or "000000000001abcd", depending on the current (global)
  3855. # address length.
  3856. sub HexExtend {
  3857. my $addr = shift;
  3858. $addr =~ s/^(0x)?0*//;
  3859. my $zeros_needed = $address_length - length($addr);
  3860. if ($zeros_needed < 0) {
  3861. printf STDERR "Warning: address $addr is longer than address length $address_length\n";
  3862. return $addr;
  3863. }
  3864. return ("0" x $zeros_needed) . $addr;
  3865. }
  3866. ##### Symbol extraction #####
  3867. # Aggressively search the lib_prefix values for the given library
  3868. # If all else fails, just return the name of the library unmodified.
  3869. # If the lib_prefix is "/my/path,/other/path" and $file is "/lib/dir/mylib.so"
  3870. # it will search the following locations in this order, until it finds a file:
  3871. # /my/path/lib/dir/mylib.so
  3872. # /other/path/lib/dir/mylib.so
  3873. # /my/path/dir/mylib.so
  3874. # /other/path/dir/mylib.so
  3875. # /my/path/mylib.so
  3876. # /other/path/mylib.so
  3877. # /lib/dir/mylib.so (returned as last resort)
  3878. sub FindLibrary {
  3879. my $file = shift;
  3880. my $suffix = $file;
  3881. # Search for the library as described above
  3882. do {
  3883. foreach my $prefix (@prefix_list) {
  3884. my $fullpath = $prefix . $suffix;
  3885. if (-e $fullpath) {
  3886. return $fullpath;
  3887. }
  3888. }
  3889. } while ($suffix =~ s|^/[^/]+/|/|);
  3890. return $file;
  3891. }
  3892. # Return path to library with debugging symbols.
  3893. # For libc libraries, the copy in /usr/lib/debug contains debugging symbols
  3894. sub DebuggingLibrary {
  3895. my $file = shift;
  3896. if ($file =~ m|^/|) {
  3897. if (-f "/usr/lib/debug$file") {
  3898. return "/usr/lib/debug$file";
  3899. } elsif (-f "/usr/lib/debug$file.debug") {
  3900. return "/usr/lib/debug$file.debug";
  3901. }
  3902. }
  3903. return undef;
  3904. }
  3905. # Parse text section header of a library using objdump
  3906. sub ParseTextSectionHeaderFromObjdump {
  3907. my $lib = shift;
  3908. my $size = undef;
  3909. my $vma;
  3910. my $file_offset;
  3911. # Get objdump output from the library file to figure out how to
  3912. # map between mapped addresses and addresses in the library.
  3913. my $cmd = ShellEscape($obj_tool_map{"objdump"}, "-h", $lib);
  3914. open(OBJDUMP, "$cmd |") || error("$cmd: $!\n");
  3915. while (<OBJDUMP>) {
  3916. s/\r//g; # turn windows-looking lines into unix-looking lines
  3917. # Idx Name Size VMA LMA File off Algn
  3918. # 10 .text 00104b2c 420156f0 420156f0 000156f0 2**4
  3919. # For 64-bit objects, VMA and LMA will be 16 hex digits, size and file
  3920. # offset may still be 8. But AddressSub below will still handle that.
  3921. my @x = split;
  3922. if (($#x >= 6) && ($x[1] eq '.text')) {
  3923. $size = $x[2];
  3924. $vma = $x[3];
  3925. $file_offset = $x[5];
  3926. last;
  3927. }
  3928. }
  3929. close(OBJDUMP);
  3930. if (!defined($size)) {
  3931. return undef;
  3932. }
  3933. my $r = {};
  3934. $r->{size} = $size;
  3935. $r->{vma} = $vma;
  3936. $r->{file_offset} = $file_offset;
  3937. return $r;
  3938. }
  3939. # Parse text section header of a library using otool (on OS X)
  3940. sub ParseTextSectionHeaderFromOtool {
  3941. my $lib = shift;
  3942. my $size = undef;
  3943. my $vma = undef;
  3944. my $file_offset = undef;
  3945. # Get otool output from the library file to figure out how to
  3946. # map between mapped addresses and addresses in the library.
  3947. my $command = ShellEscape($obj_tool_map{"otool"}, "-l", $lib);
  3948. open(OTOOL, "$command |") || error("$command: $!\n");
  3949. my $cmd = "";
  3950. my $sectname = "";
  3951. my $segname = "";
  3952. foreach my $line (<OTOOL>) {
  3953. $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
  3954. # Load command <#>
  3955. # cmd LC_SEGMENT
  3956. # [...]
  3957. # Section
  3958. # sectname __text
  3959. # segname __TEXT
  3960. # addr 0x000009f8
  3961. # size 0x00018b9e
  3962. # offset 2552
  3963. # align 2^2 (4)
  3964. # We will need to strip off the leading 0x from the hex addresses,
  3965. # and convert the offset into hex.
  3966. if ($line =~ /Load command/) {
  3967. $cmd = "";
  3968. $sectname = "";
  3969. $segname = "";
  3970. } elsif ($line =~ /Section/) {
  3971. $sectname = "";
  3972. $segname = "";
  3973. } elsif ($line =~ /cmd (\w+)/) {
  3974. $cmd = $1;
  3975. } elsif ($line =~ /sectname (\w+)/) {
  3976. $sectname = $1;
  3977. } elsif ($line =~ /segname (\w+)/) {
  3978. $segname = $1;
  3979. } elsif (!(($cmd eq "LC_SEGMENT" || $cmd eq "LC_SEGMENT_64") &&
  3980. $sectname eq "__text" &&
  3981. $segname eq "__TEXT")) {
  3982. next;
  3983. } elsif ($line =~ /\baddr 0x([0-9a-fA-F]+)/) {
  3984. $vma = $1;
  3985. } elsif ($line =~ /\bsize 0x([0-9a-fA-F]+)/) {
  3986. $size = $1;
  3987. } elsif ($line =~ /\boffset ([0-9]+)/) {
  3988. $file_offset = sprintf("%016x", $1);
  3989. }
  3990. if (defined($vma) && defined($size) && defined($file_offset)) {
  3991. last;
  3992. }
  3993. }
  3994. close(OTOOL);
  3995. if (!defined($vma) || !defined($size) || !defined($file_offset)) {
  3996. return undef;
  3997. }
  3998. my $r = {};
  3999. $r->{size} = $size;
  4000. $r->{vma} = $vma;
  4001. $r->{file_offset} = $file_offset;
  4002. return $r;
  4003. }
  4004. sub ParseTextSectionHeader {
  4005. # obj_tool_map("otool") is only defined if we're in a Mach-O environment
  4006. if (defined($obj_tool_map{"otool"})) {
  4007. my $r = ParseTextSectionHeaderFromOtool(@_);
  4008. if (defined($r)){
  4009. return $r;
  4010. }
  4011. }
  4012. # If otool doesn't work, or we don't have it, fall back to objdump
  4013. return ParseTextSectionHeaderFromObjdump(@_);
  4014. }
  4015. # Split /proc/pid/maps dump into a list of libraries
  4016. sub ParseLibraries {
  4017. return if $main::use_symbol_page; # We don't need libraries info.
  4018. my $prog = shift;
  4019. my $map = shift;
  4020. my $pcs = shift;
  4021. my $result = [];
  4022. my $h = "[a-f0-9]+";
  4023. my $zero_offset = HexExtend("0");
  4024. my $buildvar = "";
  4025. foreach my $l (split("\n", $map)) {
  4026. if ($l =~ m/^\s*build=(.*)$/) {
  4027. $buildvar = $1;
  4028. }
  4029. my $start;
  4030. my $finish;
  4031. my $offset;
  4032. my $lib;
  4033. if ($l =~ /^($h)-($h)\s+..x.\s+($h)\s+\S+:\S+\s+\d+\s+(\S+\.(so|dll|dylib|bundle)((\.\d+)+\w*(\.\d+){0,3})?)$/i) {
  4034. # Full line from /proc/self/maps. Example:
  4035. # 40000000-40015000 r-xp 00000000 03:01 12845071 /lib/ld-2.3.2.so
  4036. $start = HexExtend($1);
  4037. $finish = HexExtend($2);
  4038. $offset = HexExtend($3);
  4039. $lib = $4;
  4040. $lib =~ s|\\|/|g; # turn windows-style paths into unix-style paths
  4041. } elsif ($l =~ /^\s*($h)-($h):\s*(\S+\.so(\.\d+)*)/) {
  4042. # Cooked line from DumpAddressMap. Example:
  4043. # 40000000-40015000: /lib/ld-2.3.2.so
  4044. $start = HexExtend($1);
  4045. $finish = HexExtend($2);
  4046. $offset = $zero_offset;
  4047. $lib = $3;
  4048. }
  4049. # FreeBSD 10.0 virtual memory map /proc/curproc/map as defined in
  4050. # function procfs_doprocmap (sys/fs/procfs/procfs_map.c)
  4051. #
  4052. # Example:
  4053. # 0x800600000 0x80061a000 26 0 0xfffff800035a0000 r-x 75 33 0x1004 COW NC vnode /libexec/ld-elf.s
  4054. # o.1 NCH -1
  4055. elsif ($l =~ /^(0x$h)\s(0x$h)\s\d+\s\d+\s0x$h\sr-x\s\d+\s\d+\s0x\d+\s(COW|NCO)\s(NC|NNC)\svnode\s(\S+\.so(\.\d+)*)/) {
  4056. $start = HexExtend($1);
  4057. $finish = HexExtend($2);
  4058. $offset = $zero_offset;
  4059. $lib = FindLibrary($5);
  4060. } else {
  4061. next;
  4062. }
  4063. # Expand "$build" variable if available
  4064. $lib =~ s/\$build\b/$buildvar/g;
  4065. $lib = FindLibrary($lib);
  4066. # Check for pre-relocated libraries, which use pre-relocated symbol tables
  4067. # and thus require adjusting the offset that we'll use to translate
  4068. # VM addresses into symbol table addresses.
  4069. # Only do this if we're not going to fetch the symbol table from a
  4070. # debugging copy of the library.
  4071. if (!DebuggingLibrary($lib)) {
  4072. my $text = ParseTextSectionHeader($lib);
  4073. if (defined($text)) {
  4074. my $vma_offset = AddressSub($text->{vma}, $text->{file_offset});
  4075. $offset = AddressAdd($offset, $vma_offset);
  4076. }
  4077. }
  4078. if($main::opt_debug) { printf STDERR "$start:$finish ($offset) $lib\n"; }
  4079. push(@{$result}, [$lib, $start, $finish, $offset]);
  4080. }
  4081. # Append special entry for additional library (not relocated)
  4082. if ($main::opt_lib ne "") {
  4083. my $text = ParseTextSectionHeader($main::opt_lib);
  4084. if (defined($text)) {
  4085. my $start = $text->{vma};
  4086. my $finish = AddressAdd($start, $text->{size});
  4087. push(@{$result}, [$main::opt_lib, $start, $finish, $start]);
  4088. }
  4089. }
  4090. # Append special entry for the main program. This covers
  4091. # 0..max_pc_value_seen, so that we assume pc values not found in one
  4092. # of the library ranges will be treated as coming from the main
  4093. # program binary.
  4094. my $min_pc = HexExtend("0");
  4095. my $max_pc = $min_pc; # find the maximal PC value in any sample
  4096. foreach my $pc (keys(%{$pcs})) {
  4097. if (HexExtend($pc) gt $max_pc) { $max_pc = HexExtend($pc); }
  4098. }
  4099. push(@{$result}, [$prog, $min_pc, $max_pc, $zero_offset]);
  4100. return $result;
  4101. }
  4102. # Add two hex addresses of length $address_length.
  4103. # Run jeprof --test for unit test if this is changed.
  4104. sub AddressAdd {
  4105. my $addr1 = shift;
  4106. my $addr2 = shift;
  4107. my $sum;
  4108. if ($address_length == 8) {
  4109. # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
  4110. $sum = (hex($addr1)+hex($addr2)) % (0x10000000 * 16);
  4111. return sprintf("%08x", $sum);
  4112. } else {
  4113. # Do the addition in 7-nibble chunks to trivialize carry handling.
  4114. if ($main::opt_debug and $main::opt_test) {
  4115. print STDERR "AddressAdd $addr1 + $addr2 = ";
  4116. }
  4117. my $a1 = substr($addr1,-7);
  4118. $addr1 = substr($addr1,0,-7);
  4119. my $a2 = substr($addr2,-7);
  4120. $addr2 = substr($addr2,0,-7);
  4121. $sum = hex($a1) + hex($a2);
  4122. my $c = 0;
  4123. if ($sum > 0xfffffff) {
  4124. $c = 1;
  4125. $sum -= 0x10000000;
  4126. }
  4127. my $r = sprintf("%07x", $sum);
  4128. $a1 = substr($addr1,-7);
  4129. $addr1 = substr($addr1,0,-7);
  4130. $a2 = substr($addr2,-7);
  4131. $addr2 = substr($addr2,0,-7);
  4132. $sum = hex($a1) + hex($a2) + $c;
  4133. $c = 0;
  4134. if ($sum > 0xfffffff) {
  4135. $c = 1;
  4136. $sum -= 0x10000000;
  4137. }
  4138. $r = sprintf("%07x", $sum) . $r;
  4139. $sum = hex($addr1) + hex($addr2) + $c;
  4140. if ($sum > 0xff) { $sum -= 0x100; }
  4141. $r = sprintf("%02x", $sum) . $r;
  4142. if ($main::opt_debug and $main::opt_test) { print STDERR "$r\n"; }
  4143. return $r;
  4144. }
  4145. }
  4146. # Subtract two hex addresses of length $address_length.
  4147. # Run jeprof --test for unit test if this is changed.
  4148. sub AddressSub {
  4149. my $addr1 = shift;
  4150. my $addr2 = shift;
  4151. my $diff;
  4152. if ($address_length == 8) {
  4153. # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
  4154. $diff = (hex($addr1)-hex($addr2)) % (0x10000000 * 16);
  4155. return sprintf("%08x", $diff);
  4156. } else {
  4157. # Do the addition in 7-nibble chunks to trivialize borrow handling.
  4158. # if ($main::opt_debug) { print STDERR "AddressSub $addr1 - $addr2 = "; }
  4159. my $a1 = hex(substr($addr1,-7));
  4160. $addr1 = substr($addr1,0,-7);
  4161. my $a2 = hex(substr($addr2,-7));
  4162. $addr2 = substr($addr2,0,-7);
  4163. my $b = 0;
  4164. if ($a2 > $a1) {
  4165. $b = 1;
  4166. $a1 += 0x10000000;
  4167. }
  4168. $diff = $a1 - $a2;
  4169. my $r = sprintf("%07x", $diff);
  4170. $a1 = hex(substr($addr1,-7));
  4171. $addr1 = substr($addr1,0,-7);
  4172. $a2 = hex(substr($addr2,-7)) + $b;
  4173. $addr2 = substr($addr2,0,-7);
  4174. $b = 0;
  4175. if ($a2 > $a1) {
  4176. $b = 1;
  4177. $a1 += 0x10000000;
  4178. }
  4179. $diff = $a1 - $a2;
  4180. $r = sprintf("%07x", $diff) . $r;
  4181. $a1 = hex($addr1);
  4182. $a2 = hex($addr2) + $b;
  4183. if ($a2 > $a1) { $a1 += 0x100; }
  4184. $diff = $a1 - $a2;
  4185. $r = sprintf("%02x", $diff) . $r;
  4186. # if ($main::opt_debug) { print STDERR "$r\n"; }
  4187. return $r;
  4188. }
  4189. }
  4190. # Increment a hex addresses of length $address_length.
  4191. # Run jeprof --test for unit test if this is changed.
  4192. sub AddressInc {
  4193. my $addr = shift;
  4194. my $sum;
  4195. if ($address_length == 8) {
  4196. # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
  4197. $sum = (hex($addr)+1) % (0x10000000 * 16);
  4198. return sprintf("%08x", $sum);
  4199. } else {
  4200. # Do the addition in 7-nibble chunks to trivialize carry handling.
  4201. # We are always doing this to step through the addresses in a function,
  4202. # and will almost never overflow the first chunk, so we check for this
  4203. # case and exit early.
  4204. # if ($main::opt_debug) { print STDERR "AddressInc $addr1 = "; }
  4205. my $a1 = substr($addr,-7);
  4206. $addr = substr($addr,0,-7);
  4207. $sum = hex($a1) + 1;
  4208. my $r = sprintf("%07x", $sum);
  4209. if ($sum <= 0xfffffff) {
  4210. $r = $addr . $r;
  4211. # if ($main::opt_debug) { print STDERR "$r\n"; }
  4212. return HexExtend($r);
  4213. } else {
  4214. $r = "0000000";
  4215. }
  4216. $a1 = substr($addr,-7);
  4217. $addr = substr($addr,0,-7);
  4218. $sum = hex($a1) + 1;
  4219. $r = sprintf("%07x", $sum) . $r;
  4220. if ($sum <= 0xfffffff) {
  4221. $r = $addr . $r;
  4222. # if ($main::opt_debug) { print STDERR "$r\n"; }
  4223. return HexExtend($r);
  4224. } else {
  4225. $r = "00000000000000";
  4226. }
  4227. $sum = hex($addr) + 1;
  4228. if ($sum > 0xff) { $sum -= 0x100; }
  4229. $r = sprintf("%02x", $sum) . $r;
  4230. # if ($main::opt_debug) { print STDERR "$r\n"; }
  4231. return $r;
  4232. }
  4233. }
  4234. # Extract symbols for all PC values found in profile
  4235. sub ExtractSymbols {
  4236. my $libs = shift;
  4237. my $pcset = shift;
  4238. my $symbols = {};
  4239. # Map each PC value to the containing library. To make this faster,
  4240. # we sort libraries by their starting pc value (highest first), and
  4241. # advance through the libraries as we advance the pc. Sometimes the
  4242. # addresses of libraries may overlap with the addresses of the main
  4243. # binary, so to make sure the libraries 'win', we iterate over the
  4244. # libraries in reverse order (which assumes the binary doesn't start
  4245. # in the middle of a library, which seems a fair assumption).
  4246. my @pcs = (sort { $a cmp $b } keys(%{$pcset})); # pcset is 0-extended strings
  4247. foreach my $lib (sort {$b->[1] cmp $a->[1]} @{$libs}) {
  4248. my $libname = $lib->[0];
  4249. my $start = $lib->[1];
  4250. my $finish = $lib->[2];
  4251. my $offset = $lib->[3];
  4252. # Use debug library if it exists
  4253. my $debug_libname = DebuggingLibrary($libname);
  4254. if ($debug_libname) {
  4255. $libname = $debug_libname;
  4256. }
  4257. # Get list of pcs that belong in this library.
  4258. my $contained = [];
  4259. my ($start_pc_index, $finish_pc_index);
  4260. # Find smallest finish_pc_index such that $finish < $pc[$finish_pc_index].
  4261. for ($finish_pc_index = $#pcs + 1; $finish_pc_index > 0;
  4262. $finish_pc_index--) {
  4263. last if $pcs[$finish_pc_index - 1] le $finish;
  4264. }
  4265. # Find smallest start_pc_index such that $start <= $pc[$start_pc_index].
  4266. for ($start_pc_index = $finish_pc_index; $start_pc_index > 0;
  4267. $start_pc_index--) {
  4268. last if $pcs[$start_pc_index - 1] lt $start;
  4269. }
  4270. # This keeps PC values higher than $pc[$finish_pc_index] in @pcs,
  4271. # in case there are overlaps in libraries and the main binary.
  4272. @{$contained} = splice(@pcs, $start_pc_index,
  4273. $finish_pc_index - $start_pc_index);
  4274. # Map to symbols
  4275. MapToSymbols($libname, AddressSub($start, $offset), $contained, $symbols);
  4276. }
  4277. return $symbols;
  4278. }
  4279. # Map list of PC values to symbols for a given image
  4280. sub MapToSymbols {
  4281. my $image = shift;
  4282. my $offset = shift;
  4283. my $pclist = shift;
  4284. my $symbols = shift;
  4285. my $debug = 0;
  4286. # Ignore empty binaries
  4287. if ($#{$pclist} < 0) { return; }
  4288. # Figure out the addr2line command to use
  4289. my $addr2line = $obj_tool_map{"addr2line"};
  4290. my $cmd = ShellEscape($addr2line, "-f", "-C", "-e", $image);
  4291. if (exists $obj_tool_map{"addr2line_pdb"}) {
  4292. $addr2line = $obj_tool_map{"addr2line_pdb"};
  4293. $cmd = ShellEscape($addr2line, "--demangle", "-f", "-C", "-e", $image);
  4294. }
  4295. # If "addr2line" isn't installed on the system at all, just use
  4296. # nm to get what info we can (function names, but not line numbers).
  4297. if (system(ShellEscape($addr2line, "--help") . " >$dev_null 2>&1") != 0) {
  4298. MapSymbolsWithNM($image, $offset, $pclist, $symbols);
  4299. return;
  4300. }
  4301. # "addr2line -i" can produce a variable number of lines per input
  4302. # address, with no separator that allows us to tell when data for
  4303. # the next address starts. So we find the address for a special
  4304. # symbol (_fini) and interleave this address between all real
  4305. # addresses passed to addr2line. The name of this special symbol
  4306. # can then be used as a separator.
  4307. $sep_address = undef; # May be filled in by MapSymbolsWithNM()
  4308. my $nm_symbols = {};
  4309. MapSymbolsWithNM($image, $offset, $pclist, $nm_symbols);
  4310. if (defined($sep_address)) {
  4311. # Only add " -i" to addr2line if the binary supports it.
  4312. # addr2line --help returns 0, but not if it sees an unknown flag first.
  4313. if (system("$cmd -i --help >$dev_null 2>&1") == 0) {
  4314. $cmd .= " -i";
  4315. } else {
  4316. $sep_address = undef; # no need for sep_address if we don't support -i
  4317. }
  4318. }
  4319. # Make file with all PC values with intervening 'sep_address' so
  4320. # that we can reliably detect the end of inlined function list
  4321. open(ADDRESSES, ">$main::tmpfile_sym") || error("$main::tmpfile_sym: $!\n");
  4322. if ($debug) { print("---- $image ---\n"); }
  4323. for (my $i = 0; $i <= $#{$pclist}; $i++) {
  4324. # addr2line always reads hex addresses, and does not need '0x' prefix.
  4325. if ($debug) { printf STDERR ("%s\n", $pclist->[$i]); }
  4326. printf ADDRESSES ("%s\n", AddressSub($pclist->[$i], $offset));
  4327. if (defined($sep_address)) {
  4328. printf ADDRESSES ("%s\n", $sep_address);
  4329. }
  4330. }
  4331. close(ADDRESSES);
  4332. if ($debug) {
  4333. print("----\n");
  4334. system("cat", $main::tmpfile_sym);
  4335. print("----\n");
  4336. system("$cmd < " . ShellEscape($main::tmpfile_sym));
  4337. print("----\n");
  4338. }
  4339. open(SYMBOLS, "$cmd <" . ShellEscape($main::tmpfile_sym) . " |")
  4340. || error("$cmd: $!\n");
  4341. my $count = 0; # Index in pclist
  4342. while (<SYMBOLS>) {
  4343. # Read fullfunction and filelineinfo from next pair of lines
  4344. s/\r?\n$//g;
  4345. my $fullfunction = $_;
  4346. $_ = <SYMBOLS>;
  4347. s/\r?\n$//g;
  4348. my $filelinenum = $_;
  4349. if (defined($sep_address) && $fullfunction eq $sep_symbol) {
  4350. # Terminating marker for data for this address
  4351. $count++;
  4352. next;
  4353. }
  4354. $filelinenum =~ s|\\|/|g; # turn windows-style paths into unix-style paths
  4355. my $pcstr = $pclist->[$count];
  4356. my $function = ShortFunctionName($fullfunction);
  4357. my $nms = $nm_symbols->{$pcstr};
  4358. if (defined($nms)) {
  4359. if ($fullfunction eq '??') {
  4360. # nm found a symbol for us.
  4361. $function = $nms->[0];
  4362. $fullfunction = $nms->[2];
  4363. } else {
  4364. # MapSymbolsWithNM tags each routine with its starting address,
  4365. # useful in case the image has multiple occurrences of this
  4366. # routine. (It uses a syntax that resembles template paramters,
  4367. # that are automatically stripped out by ShortFunctionName().)
  4368. # addr2line does not provide the same information. So we check
  4369. # if nm disambiguated our symbol, and if so take the annotated
  4370. # (nm) version of the routine-name. TODO(csilvers): this won't
  4371. # catch overloaded, inlined symbols, which nm doesn't see.
  4372. # Better would be to do a check similar to nm's, in this fn.
  4373. if ($nms->[2] =~ m/^\Q$function\E/) { # sanity check it's the right fn
  4374. $function = $nms->[0];
  4375. $fullfunction = $nms->[2];
  4376. }
  4377. }
  4378. }
  4379. # Prepend to accumulated symbols for pcstr
  4380. # (so that caller comes before callee)
  4381. my $sym = $symbols->{$pcstr};
  4382. if (!defined($sym)) {
  4383. $sym = [];
  4384. $symbols->{$pcstr} = $sym;
  4385. }
  4386. unshift(@{$sym}, $function, $filelinenum, $fullfunction);
  4387. if ($debug) { printf STDERR ("%s => [%s]\n", $pcstr, join(" ", @{$sym})); }
  4388. if (!defined($sep_address)) {
  4389. # Inlining is off, so this entry ends immediately
  4390. $count++;
  4391. }
  4392. }
  4393. close(SYMBOLS);
  4394. }
  4395. # Use nm to map the list of referenced PCs to symbols. Return true iff we
  4396. # are able to read procedure information via nm.
  4397. sub MapSymbolsWithNM {
  4398. my $image = shift;
  4399. my $offset = shift;
  4400. my $pclist = shift;
  4401. my $symbols = shift;
  4402. # Get nm output sorted by increasing address
  4403. my $symbol_table = GetProcedureBoundaries($image, ".");
  4404. if (!%{$symbol_table}) {
  4405. return 0;
  4406. }
  4407. # Start addresses are already the right length (8 or 16 hex digits).
  4408. my @names = sort { $symbol_table->{$a}->[0] cmp $symbol_table->{$b}->[0] }
  4409. keys(%{$symbol_table});
  4410. if ($#names < 0) {
  4411. # No symbols: just use addresses
  4412. foreach my $pc (@{$pclist}) {
  4413. my $pcstr = "0x" . $pc;
  4414. $symbols->{$pc} = [$pcstr, "?", $pcstr];
  4415. }
  4416. return 0;
  4417. }
  4418. # Sort addresses so we can do a join against nm output
  4419. my $index = 0;
  4420. my $fullname = $names[0];
  4421. my $name = ShortFunctionName($fullname);
  4422. foreach my $pc (sort { $a cmp $b } @{$pclist}) {
  4423. # Adjust for mapped offset
  4424. my $mpc = AddressSub($pc, $offset);
  4425. while (($index < $#names) && ($mpc ge $symbol_table->{$fullname}->[1])){
  4426. $index++;
  4427. $fullname = $names[$index];
  4428. $name = ShortFunctionName($fullname);
  4429. }
  4430. if ($mpc lt $symbol_table->{$fullname}->[1]) {
  4431. $symbols->{$pc} = [$name, "?", $fullname];
  4432. } else {
  4433. my $pcstr = "0x" . $pc;
  4434. $symbols->{$pc} = [$pcstr, "?", $pcstr];
  4435. }
  4436. }
  4437. return 1;
  4438. }
  4439. sub ShortFunctionName {
  4440. my $function = shift;
  4441. while ($function =~ s/\([^()]*\)(\s*const)?//g) { } # Argument types
  4442. while ($function =~ s/<[^<>]*>//g) { } # Remove template arguments
  4443. $function =~ s/^.*\s+(\w+::)/$1/; # Remove leading type
  4444. return $function;
  4445. }
  4446. # Trim overly long symbols found in disassembler output
  4447. sub CleanDisassembly {
  4448. my $d = shift;
  4449. while ($d =~ s/\([^()%]*\)(\s*const)?//g) { } # Argument types, not (%rax)
  4450. while ($d =~ s/(\w+)<[^<>]*>/$1/g) { } # Remove template arguments
  4451. return $d;
  4452. }
  4453. # Clean file name for display
  4454. sub CleanFileName {
  4455. my ($f) = @_;
  4456. $f =~ s|^/proc/self/cwd/||;
  4457. $f =~ s|^\./||;
  4458. return $f;
  4459. }
  4460. # Make address relative to section and clean up for display
  4461. sub UnparseAddress {
  4462. my ($offset, $address) = @_;
  4463. $address = AddressSub($address, $offset);
  4464. $address =~ s/^0x//;
  4465. $address =~ s/^0*//;
  4466. return $address;
  4467. }
  4468. ##### Miscellaneous #####
  4469. # Find the right versions of the above object tools to use. The
  4470. # argument is the program file being analyzed, and should be an ELF
  4471. # 32-bit or ELF 64-bit executable file. The location of the tools
  4472. # is determined by considering the following options in this order:
  4473. # 1) --tools option, if set
  4474. # 2) JEPROF_TOOLS environment variable, if set
  4475. # 3) the environment
  4476. sub ConfigureObjTools {
  4477. my $prog_file = shift;
  4478. # Check for the existence of $prog_file because /usr/bin/file does not
  4479. # predictably return error status in prod.
  4480. (-e $prog_file) || error("$prog_file does not exist.\n");
  4481. my $file_type = undef;
  4482. if (-e "/usr/bin/file") {
  4483. # Follow symlinks (at least for systems where "file" supports that).
  4484. my $escaped_prog_file = ShellEscape($prog_file);
  4485. $file_type = `/usr/bin/file -L $escaped_prog_file 2>$dev_null ||
  4486. /usr/bin/file $escaped_prog_file`;
  4487. } elsif ($^O == "MSWin32") {
  4488. $file_type = "MS Windows";
  4489. } else {
  4490. print STDERR "WARNING: Can't determine the file type of $prog_file";
  4491. }
  4492. if ($file_type =~ /64-bit/) {
  4493. # Change $address_length to 16 if the program file is ELF 64-bit.
  4494. # We can't detect this from many (most?) heap or lock contention
  4495. # profiles, since the actual addresses referenced are generally in low
  4496. # memory even for 64-bit programs.
  4497. $address_length = 16;
  4498. }
  4499. if ($file_type =~ /MS Windows/) {
  4500. # For windows, we provide a version of nm and addr2line as part of
  4501. # the opensource release, which is capable of parsing
  4502. # Windows-style PDB executables. It should live in the path, or
  4503. # in the same directory as jeprof.
  4504. $obj_tool_map{"nm_pdb"} = "nm-pdb";
  4505. $obj_tool_map{"addr2line_pdb"} = "addr2line-pdb";
  4506. }
  4507. if ($file_type =~ /Mach-O/) {
  4508. # OS X uses otool to examine Mach-O files, rather than objdump.
  4509. $obj_tool_map{"otool"} = "otool";
  4510. $obj_tool_map{"addr2line"} = "false"; # no addr2line
  4511. $obj_tool_map{"objdump"} = "false"; # no objdump
  4512. }
  4513. # Go fill in %obj_tool_map with the pathnames to use:
  4514. foreach my $tool (keys %obj_tool_map) {
  4515. $obj_tool_map{$tool} = ConfigureTool($obj_tool_map{$tool});
  4516. }
  4517. }
  4518. # Returns the path of a caller-specified object tool. If --tools or
  4519. # JEPROF_TOOLS are specified, then returns the full path to the tool
  4520. # with that prefix. Otherwise, returns the path unmodified (which
  4521. # means we will look for it on PATH).
  4522. sub ConfigureTool {
  4523. my $tool = shift;
  4524. my $path;
  4525. # --tools (or $JEPROF_TOOLS) is a comma separated list, where each
  4526. # item is either a) a pathname prefix, or b) a map of the form
  4527. # <tool>:<path>. First we look for an entry of type (b) for our
  4528. # tool. If one is found, we use it. Otherwise, we consider all the
  4529. # pathname prefixes in turn, until one yields an existing file. If
  4530. # none does, we use a default path.
  4531. my $tools = $main::opt_tools || $ENV{"JEPROF_TOOLS"} || "";
  4532. if ($tools =~ m/(,|^)\Q$tool\E:([^,]*)/) {
  4533. $path = $2;
  4534. # TODO(csilvers): sanity-check that $path exists? Hard if it's relative.
  4535. } elsif ($tools ne '') {
  4536. foreach my $prefix (split(',', $tools)) {
  4537. next if ($prefix =~ /:/); # ignore "tool:fullpath" entries in the list
  4538. if (-x $prefix . $tool) {
  4539. $path = $prefix . $tool;
  4540. last;
  4541. }
  4542. }
  4543. if (!$path) {
  4544. error("No '$tool' found with prefix specified by " .
  4545. "--tools (or \$JEPROF_TOOLS) '$tools'\n");
  4546. }
  4547. } else {
  4548. # ... otherwise use the version that exists in the same directory as
  4549. # jeprof. If there's nothing there, use $PATH.
  4550. $0 =~ m,[^/]*$,; # this is everything after the last slash
  4551. my $dirname = $`; # this is everything up to and including the last slash
  4552. if (-x "$dirname$tool") {
  4553. $path = "$dirname$tool";
  4554. } else {
  4555. $path = $tool;
  4556. }
  4557. }
  4558. if ($main::opt_debug) { print STDERR "Using '$path' for '$tool'.\n"; }
  4559. return $path;
  4560. }
  4561. sub ShellEscape {
  4562. my @escaped_words = ();
  4563. foreach my $word (@_) {
  4564. my $escaped_word = $word;
  4565. if ($word =~ m![^a-zA-Z0-9/.,_=-]!) { # check for anything not in whitelist
  4566. $escaped_word =~ s/'/'\\''/;
  4567. $escaped_word = "'$escaped_word'";
  4568. }
  4569. push(@escaped_words, $escaped_word);
  4570. }
  4571. return join(" ", @escaped_words);
  4572. }
  4573. sub cleanup {
  4574. unlink($main::tmpfile_sym);
  4575. unlink(keys %main::tempnames);
  4576. # We leave any collected profiles in $HOME/jeprof in case the user wants
  4577. # to look at them later. We print a message informing them of this.
  4578. if ((scalar(@main::profile_files) > 0) &&
  4579. defined($main::collected_profile)) {
  4580. if (scalar(@main::profile_files) == 1) {
  4581. print STDERR "Dynamically gathered profile is in $main::collected_profile\n";
  4582. }
  4583. print STDERR "If you want to investigate this profile further, you can do:\n";
  4584. print STDERR "\n";
  4585. print STDERR " jeprof \\\n";
  4586. print STDERR " $main::prog \\\n";
  4587. print STDERR " $main::collected_profile\n";
  4588. print STDERR "\n";
  4589. }
  4590. }
  4591. sub sighandler {
  4592. cleanup();
  4593. exit(1);
  4594. }
  4595. sub error {
  4596. my $msg = shift;
  4597. print STDERR $msg;
  4598. cleanup();
  4599. exit(1);
  4600. }
  4601. # Run $nm_command and get all the resulting procedure boundaries whose
  4602. # names match "$regexp" and returns them in a hashtable mapping from
  4603. # procedure name to a two-element vector of [start address, end address]
  4604. sub GetProcedureBoundariesViaNm {
  4605. my $escaped_nm_command = shift; # shell-escaped
  4606. my $regexp = shift;
  4607. my $symbol_table = {};
  4608. open(NM, "$escaped_nm_command |") || error("$escaped_nm_command: $!\n");
  4609. my $last_start = "0";
  4610. my $routine = "";
  4611. while (<NM>) {
  4612. s/\r//g; # turn windows-looking lines into unix-looking lines
  4613. if (m/^\s*([0-9a-f]+) (.) (..*)/) {
  4614. my $start_val = $1;
  4615. my $type = $2;
  4616. my $this_routine = $3;
  4617. # It's possible for two symbols to share the same address, if
  4618. # one is a zero-length variable (like __start_google_malloc) or
  4619. # one symbol is a weak alias to another (like __libc_malloc).
  4620. # In such cases, we want to ignore all values except for the
  4621. # actual symbol, which in nm-speak has type "T". The logic
  4622. # below does this, though it's a bit tricky: what happens when
  4623. # we have a series of lines with the same address, is the first
  4624. # one gets queued up to be processed. However, it won't
  4625. # *actually* be processed until later, when we read a line with
  4626. # a different address. That means that as long as we're reading
  4627. # lines with the same address, we have a chance to replace that
  4628. # item in the queue, which we do whenever we see a 'T' entry --
  4629. # that is, a line with type 'T'. If we never see a 'T' entry,
  4630. # we'll just go ahead and process the first entry (which never
  4631. # got touched in the queue), and ignore the others.
  4632. if ($start_val eq $last_start && $type =~ /t/i) {
  4633. # We are the 'T' symbol at this address, replace previous symbol.
  4634. $routine = $this_routine;
  4635. next;
  4636. } elsif ($start_val eq $last_start) {
  4637. # We're not the 'T' symbol at this address, so ignore us.
  4638. next;
  4639. }
  4640. if ($this_routine eq $sep_symbol) {
  4641. $sep_address = HexExtend($start_val);
  4642. }
  4643. # Tag this routine with the starting address in case the image
  4644. # has multiple occurrences of this routine. We use a syntax
  4645. # that resembles template parameters that are automatically
  4646. # stripped out by ShortFunctionName()
  4647. $this_routine .= "<$start_val>";
  4648. if (defined($routine) && $routine =~ m/$regexp/) {
  4649. $symbol_table->{$routine} = [HexExtend($last_start),
  4650. HexExtend($start_val)];
  4651. }
  4652. $last_start = $start_val;
  4653. $routine = $this_routine;
  4654. } elsif (m/^Loaded image name: (.+)/) {
  4655. # The win32 nm workalike emits information about the binary it is using.
  4656. if ($main::opt_debug) { print STDERR "Using Image $1\n"; }
  4657. } elsif (m/^PDB file name: (.+)/) {
  4658. # The win32 nm workalike emits information about the pdb it is using.
  4659. if ($main::opt_debug) { print STDERR "Using PDB $1\n"; }
  4660. }
  4661. }
  4662. close(NM);
  4663. # Handle the last line in the nm output. Unfortunately, we don't know
  4664. # how big this last symbol is, because we don't know how big the file
  4665. # is. For now, we just give it a size of 0.
  4666. # TODO(csilvers): do better here.
  4667. if (defined($routine) && $routine =~ m/$regexp/) {
  4668. $symbol_table->{$routine} = [HexExtend($last_start),
  4669. HexExtend($last_start)];
  4670. }
  4671. return $symbol_table;
  4672. }
  4673. # Gets the procedure boundaries for all routines in "$image" whose names
  4674. # match "$regexp" and returns them in a hashtable mapping from procedure
  4675. # name to a two-element vector of [start address, end address].
  4676. # Will return an empty map if nm is not installed or not working properly.
  4677. sub GetProcedureBoundaries {
  4678. my $image = shift;
  4679. my $regexp = shift;
  4680. # If $image doesn't start with /, then put ./ in front of it. This works
  4681. # around an obnoxious bug in our probing of nm -f behavior.
  4682. # "nm -f $image" is supposed to fail on GNU nm, but if:
  4683. #
  4684. # a. $image starts with [BbSsPp] (for example, bin/foo/bar), AND
  4685. # b. you have a.out in your current directory (a not uncommon occurence)
  4686. #
  4687. # then "nm -f $image" succeeds because -f only looks at the first letter of
  4688. # the argument, which looks valid because it's [BbSsPp], and then since
  4689. # there's no image provided, it looks for a.out and finds it.
  4690. #
  4691. # This regex makes sure that $image starts with . or /, forcing the -f
  4692. # parsing to fail since . and / are not valid formats.
  4693. $image =~ s#^[^/]#./$&#;
  4694. # For libc libraries, the copy in /usr/lib/debug contains debugging symbols
  4695. my $debugging = DebuggingLibrary($image);
  4696. if ($debugging) {
  4697. $image = $debugging;
  4698. }
  4699. my $nm = $obj_tool_map{"nm"};
  4700. my $cppfilt = $obj_tool_map{"c++filt"};
  4701. # nm can fail for two reasons: 1) $image isn't a debug library; 2) nm
  4702. # binary doesn't support --demangle. In addition, for OS X we need
  4703. # to use the -f flag to get 'flat' nm output (otherwise we don't sort
  4704. # properly and get incorrect results). Unfortunately, GNU nm uses -f
  4705. # in an incompatible way. So first we test whether our nm supports
  4706. # --demangle and -f.
  4707. my $demangle_flag = "";
  4708. my $cppfilt_flag = "";
  4709. my $to_devnull = ">$dev_null 2>&1";
  4710. if (system(ShellEscape($nm, "--demangle", "image") . $to_devnull) == 0) {
  4711. # In this mode, we do "nm --demangle <foo>"
  4712. $demangle_flag = "--demangle";
  4713. $cppfilt_flag = "";
  4714. } elsif (system(ShellEscape($cppfilt, $image) . $to_devnull) == 0) {
  4715. # In this mode, we do "nm <foo> | c++filt"
  4716. $cppfilt_flag = " | " . ShellEscape($cppfilt);
  4717. };
  4718. my $flatten_flag = "";
  4719. if (system(ShellEscape($nm, "-f", $image) . $to_devnull) == 0) {
  4720. $flatten_flag = "-f";
  4721. }
  4722. # Finally, in the case $imagie isn't a debug library, we try again with
  4723. # -D to at least get *exported* symbols. If we can't use --demangle,
  4724. # we use c++filt instead, if it exists on this system.
  4725. my @nm_commands = (ShellEscape($nm, "-n", $flatten_flag, $demangle_flag,
  4726. $image) . " 2>$dev_null $cppfilt_flag",
  4727. ShellEscape($nm, "-D", "-n", $flatten_flag, $demangle_flag,
  4728. $image) . " 2>$dev_null $cppfilt_flag",
  4729. # 6nm is for Go binaries
  4730. ShellEscape("6nm", "$image") . " 2>$dev_null | sort",
  4731. );
  4732. # If the executable is an MS Windows PDB-format executable, we'll
  4733. # have set up obj_tool_map("nm_pdb"). In this case, we actually
  4734. # want to use both unix nm and windows-specific nm_pdb, since
  4735. # PDB-format executables can apparently include dwarf .o files.
  4736. if (exists $obj_tool_map{"nm_pdb"}) {
  4737. push(@nm_commands,
  4738. ShellEscape($obj_tool_map{"nm_pdb"}, "--demangle", $image)
  4739. . " 2>$dev_null");
  4740. }
  4741. foreach my $nm_command (@nm_commands) {
  4742. my $symbol_table = GetProcedureBoundariesViaNm($nm_command, $regexp);
  4743. return $symbol_table if (%{$symbol_table});
  4744. }
  4745. my $symbol_table = {};
  4746. return $symbol_table;
  4747. }
  4748. # The test vectors for AddressAdd/Sub/Inc are 8-16-nibble hex strings.
  4749. # To make them more readable, we add underscores at interesting places.
  4750. # This routine removes the underscores, producing the canonical representation
  4751. # used by jeprof to represent addresses, particularly in the tested routines.
  4752. sub CanonicalHex {
  4753. my $arg = shift;
  4754. return join '', (split '_',$arg);
  4755. }
  4756. # Unit test for AddressAdd:
  4757. sub AddressAddUnitTest {
  4758. my $test_data_8 = shift;
  4759. my $test_data_16 = shift;
  4760. my $error_count = 0;
  4761. my $fail_count = 0;
  4762. my $pass_count = 0;
  4763. # print STDERR "AddressAddUnitTest: ", 1+$#{$test_data_8}, " tests\n";
  4764. # First a few 8-nibble addresses. Note that this implementation uses
  4765. # plain old arithmetic, so a quick sanity check along with verifying what
  4766. # happens to overflow (we want it to wrap):
  4767. $address_length = 8;
  4768. foreach my $row (@{$test_data_8}) {
  4769. if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
  4770. my $sum = AddressAdd ($row->[0], $row->[1]);
  4771. if ($sum ne $row->[2]) {
  4772. printf STDERR "ERROR: %s != %s + %s = %s\n", $sum,
  4773. $row->[0], $row->[1], $row->[2];
  4774. ++$fail_count;
  4775. } else {
  4776. ++$pass_count;
  4777. }
  4778. }
  4779. printf STDERR "AddressAdd 32-bit tests: %d passes, %d failures\n",
  4780. $pass_count, $fail_count;
  4781. $error_count = $fail_count;
  4782. $fail_count = 0;
  4783. $pass_count = 0;
  4784. # Now 16-nibble addresses.
  4785. $address_length = 16;
  4786. foreach my $row (@{$test_data_16}) {
  4787. if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
  4788. my $sum = AddressAdd (CanonicalHex($row->[0]), CanonicalHex($row->[1]));
  4789. my $expected = join '', (split '_',$row->[2]);
  4790. if ($sum ne CanonicalHex($row->[2])) {
  4791. printf STDERR "ERROR: %s != %s + %s = %s\n", $sum,
  4792. $row->[0], $row->[1], $row->[2];
  4793. ++$fail_count;
  4794. } else {
  4795. ++$pass_count;
  4796. }
  4797. }
  4798. printf STDERR "AddressAdd 64-bit tests: %d passes, %d failures\n",
  4799. $pass_count, $fail_count;
  4800. $error_count += $fail_count;
  4801. return $error_count;
  4802. }
  4803. # Unit test for AddressSub:
  4804. sub AddressSubUnitTest {
  4805. my $test_data_8 = shift;
  4806. my $test_data_16 = shift;
  4807. my $error_count = 0;
  4808. my $fail_count = 0;
  4809. my $pass_count = 0;
  4810. # print STDERR "AddressSubUnitTest: ", 1+$#{$test_data_8}, " tests\n";
  4811. # First a few 8-nibble addresses. Note that this implementation uses
  4812. # plain old arithmetic, so a quick sanity check along with verifying what
  4813. # happens to overflow (we want it to wrap):
  4814. $address_length = 8;
  4815. foreach my $row (@{$test_data_8}) {
  4816. if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
  4817. my $sum = AddressSub ($row->[0], $row->[1]);
  4818. if ($sum ne $row->[3]) {
  4819. printf STDERR "ERROR: %s != %s - %s = %s\n", $sum,
  4820. $row->[0], $row->[1], $row->[3];
  4821. ++$fail_count;
  4822. } else {
  4823. ++$pass_count;
  4824. }
  4825. }
  4826. printf STDERR "AddressSub 32-bit tests: %d passes, %d failures\n",
  4827. $pass_count, $fail_count;
  4828. $error_count = $fail_count;
  4829. $fail_count = 0;
  4830. $pass_count = 0;
  4831. # Now 16-nibble addresses.
  4832. $address_length = 16;
  4833. foreach my $row (@{$test_data_16}) {
  4834. if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
  4835. my $sum = AddressSub (CanonicalHex($row->[0]), CanonicalHex($row->[1]));
  4836. if ($sum ne CanonicalHex($row->[3])) {
  4837. printf STDERR "ERROR: %s != %s - %s = %s\n", $sum,
  4838. $row->[0], $row->[1], $row->[3];
  4839. ++$fail_count;
  4840. } else {
  4841. ++$pass_count;
  4842. }
  4843. }
  4844. printf STDERR "AddressSub 64-bit tests: %d passes, %d failures\n",
  4845. $pass_count, $fail_count;
  4846. $error_count += $fail_count;
  4847. return $error_count;
  4848. }
  4849. # Unit test for AddressInc:
  4850. sub AddressIncUnitTest {
  4851. my $test_data_8 = shift;
  4852. my $test_data_16 = shift;
  4853. my $error_count = 0;
  4854. my $fail_count = 0;
  4855. my $pass_count = 0;
  4856. # print STDERR "AddressIncUnitTest: ", 1+$#{$test_data_8}, " tests\n";
  4857. # First a few 8-nibble addresses. Note that this implementation uses
  4858. # plain old arithmetic, so a quick sanity check along with verifying what
  4859. # happens to overflow (we want it to wrap):
  4860. $address_length = 8;
  4861. foreach my $row (@{$test_data_8}) {
  4862. if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
  4863. my $sum = AddressInc ($row->[0]);
  4864. if ($sum ne $row->[4]) {
  4865. printf STDERR "ERROR: %s != %s + 1 = %s\n", $sum,
  4866. $row->[0], $row->[4];
  4867. ++$fail_count;
  4868. } else {
  4869. ++$pass_count;
  4870. }
  4871. }
  4872. printf STDERR "AddressInc 32-bit tests: %d passes, %d failures\n",
  4873. $pass_count, $fail_count;
  4874. $error_count = $fail_count;
  4875. $fail_count = 0;
  4876. $pass_count = 0;
  4877. # Now 16-nibble addresses.
  4878. $address_length = 16;
  4879. foreach my $row (@{$test_data_16}) {
  4880. if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
  4881. my $sum = AddressInc (CanonicalHex($row->[0]));
  4882. if ($sum ne CanonicalHex($row->[4])) {
  4883. printf STDERR "ERROR: %s != %s + 1 = %s\n", $sum,
  4884. $row->[0], $row->[4];
  4885. ++$fail_count;
  4886. } else {
  4887. ++$pass_count;
  4888. }
  4889. }
  4890. printf STDERR "AddressInc 64-bit tests: %d passes, %d failures\n",
  4891. $pass_count, $fail_count;
  4892. $error_count += $fail_count;
  4893. return $error_count;
  4894. }
  4895. # Driver for unit tests.
  4896. # Currently just the address add/subtract/increment routines for 64-bit.
  4897. sub RunUnitTests {
  4898. my $error_count = 0;
  4899. # This is a list of tuples [a, b, a+b, a-b, a+1]
  4900. my $unit_test_data_8 = [
  4901. [qw(aaaaaaaa 50505050 fafafafa 5a5a5a5a aaaaaaab)],
  4902. [qw(50505050 aaaaaaaa fafafafa a5a5a5a6 50505051)],
  4903. [qw(ffffffff aaaaaaaa aaaaaaa9 55555555 00000000)],
  4904. [qw(00000001 ffffffff 00000000 00000002 00000002)],
  4905. [qw(00000001 fffffff0 fffffff1 00000011 00000002)],
  4906. ];
  4907. my $unit_test_data_16 = [
  4908. # The implementation handles data in 7-nibble chunks, so those are the
  4909. # interesting boundaries.
  4910. [qw(aaaaaaaa 50505050
  4911. 00_000000f_afafafa 00_0000005_a5a5a5a 00_000000a_aaaaaab)],
  4912. [qw(50505050 aaaaaaaa
  4913. 00_000000f_afafafa ff_ffffffa_5a5a5a6 00_0000005_0505051)],
  4914. [qw(ffffffff aaaaaaaa
  4915. 00_000001a_aaaaaa9 00_0000005_5555555 00_0000010_0000000)],
  4916. [qw(00000001 ffffffff
  4917. 00_0000010_0000000 ff_ffffff0_0000002 00_0000000_0000002)],
  4918. [qw(00000001 fffffff0
  4919. 00_000000f_ffffff1 ff_ffffff0_0000011 00_0000000_0000002)],
  4920. [qw(00_a00000a_aaaaaaa 50505050
  4921. 00_a00000f_afafafa 00_a000005_a5a5a5a 00_a00000a_aaaaaab)],
  4922. [qw(0f_fff0005_0505050 aaaaaaaa
  4923. 0f_fff000f_afafafa 0f_ffefffa_5a5a5a6 0f_fff0005_0505051)],
  4924. [qw(00_000000f_fffffff 01_800000a_aaaaaaa
  4925. 01_800001a_aaaaaa9 fe_8000005_5555555 00_0000010_0000000)],
  4926. [qw(00_0000000_0000001 ff_fffffff_fffffff
  4927. 00_0000000_0000000 00_0000000_0000002 00_0000000_0000002)],
  4928. [qw(00_0000000_0000001 ff_fffffff_ffffff0
  4929. ff_fffffff_ffffff1 00_0000000_0000011 00_0000000_0000002)],
  4930. ];
  4931. $error_count += AddressAddUnitTest($unit_test_data_8, $unit_test_data_16);
  4932. $error_count += AddressSubUnitTest($unit_test_data_8, $unit_test_data_16);
  4933. $error_count += AddressIncUnitTest($unit_test_data_8, $unit_test_data_16);
  4934. if ($error_count > 0) {
  4935. print STDERR $error_count, " errors: FAILED\n";
  4936. } else {
  4937. print STDERR "PASS\n";
  4938. }
  4939. exit ($error_count);
  4940. }