jeprof 178 KB

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