pprof 146 KB

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