pprof 167 KB

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