jdebug.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009
  1. /*##############################################################################
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ############################################################################## */
  12. #include "platform.h"
  13. #include "jdebug.hpp"
  14. #include "jstring.hpp"
  15. #include "jhash.hpp"
  16. #include "jmisc.hpp"
  17. #include "jexcept.hpp"
  18. #include "jmutex.hpp"
  19. #include "jtime.hpp"
  20. #include <stdio.h>
  21. #include <time.h>
  22. #include <atomic>
  23. #ifdef _WIN32
  24. #define DPSAPI_VERSION 1
  25. #include <psapi.h>
  26. #include <processthreadsapi.h>
  27. #include <sysinfoapi.h>
  28. #endif
  29. #ifdef __linux__
  30. #include <sys/time.h>
  31. #include <sys/resource.h>
  32. #include <unistd.h>
  33. #include <sys/vfs.h>
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <sys/klog.h>
  37. #include <dirent.h>
  38. #endif
  39. #ifdef __APPLE__
  40. #include <sys/param.h>
  41. #include <sys/mount.h>
  42. #include <sys/sysctl.h>
  43. #include <mach/task.h>
  44. #include <mach/mach_init.h>
  45. #include <mach/mach_host.h>
  46. #include <mach/vm_statistics.h>
  47. #endif
  48. #include "build-config.h"
  49. //===========================================================================
  50. #ifdef _DEBUG
  51. // #define _USE_MALLOC_HOOK // Only enable if you need it - slow!
  52. #else
  53. #undef _USE_MALLOC_HOOK // don't define for release - not threadsafe
  54. #endif
  55. #define _USE_RDTSC true
  56. #ifdef _USE_MALLOC_HOOK
  57. #define REPORT_LARGER_BLOCK_THAN (10*0x100000)
  58. static __int64 totalMem = 0;
  59. static __int64 hwmTotalMem = 0;
  60. #ifdef __linux__
  61. static unsigned memArea[32];
  62. #endif
  63. #endif
  64. /* LINUX SYS: log KEY
  65. ========================
  66. PU (%) is the percentage CPU in use (unchanged from previously).
  67. MU (%) is what percentage of total (all processes) memory is in use
  68. (ram + swap) or in 32 bit is the percentage of 3GB (address space)
  69. used (whichever larger).
  70. MAL is total memory in use (i.e malloced and not freed ) by this
  71. process (= MMP+SBK)
  72. MMP is the sum of memory mapped (large) blocks in use by this process
  73. (which will be returned to OS when freed).
  74. SBK is the sbrk'ed memory i.e. smaller blocks allocated from the
  75. arena. (note this memory is unlikely to be returned to OS while the
  76. process is still running).
  77. TOT (K) is an indication of the memory footprint of the process.
  78. This is the 'arena' size (which is how much reserved by sbrk) plus the
  79. mmap memory size (MMP).
  80. RAM (K) is how much real memory is in use by all processes - it is
  81. the same as what would be reported by the 'free' command after the
  82. caches/buffers have been subtracted.
  83. SWP (K) is the swap size in use for all processes.
  84. Extended stats
  85. DSK: disk statistics for each disk (e.g. [sda] and [sdb])
  86. r/s read i/o operations per sec (over last period)
  87. kr/s K bytes read per sec
  88. w/s write i/o operations per sec
  89. kw/s K bytes written per sec
  90. busy indication how busy the disk was during period (%)
  91. NIC: network (i.e. eth0) statistics
  92. rxp/s packets received per sec
  93. rxk/s K bytes received per sec
  94. txp/s packets transmitted per sec
  95. txk/s K bytes transmitted per sec
  96. CPU:
  97. usr % at user level
  98. sys % in kernel
  99. iow % waiting for i/o
  100. */
  101. inline void skipSp(const char *&s)
  102. {
  103. while (isspace(*s))
  104. s++;
  105. }
  106. inline offset_t readHexNum(const char *&s)
  107. {
  108. offset_t ret = 0;
  109. for (;;) {
  110. switch (*s) {
  111. case '0':
  112. case '1':
  113. case '2':
  114. case '3':
  115. case '4':
  116. case '5':
  117. case '6':
  118. case '7':
  119. case '8':
  120. case '9': ret = ret*16+(*s-'0');
  121. break;
  122. case 'A':
  123. case 'B':
  124. case 'C':
  125. case 'D':
  126. case 'E':
  127. case 'F': ret = ret*16+(*s-'A'+10);
  128. break;
  129. case 'a':
  130. case 'b':
  131. case 'c':
  132. case 'd':
  133. case 'e':
  134. case 'f': ret = ret*16+(*s-'a'+10);
  135. break;
  136. default:
  137. return ret;
  138. }
  139. s++;
  140. }
  141. return 0;
  142. }
  143. inline offset_t readDecNum(const char *&s)
  144. {
  145. offset_t ret = 0;
  146. for (;;) {
  147. switch (*s) {
  148. case '0':
  149. case '1':
  150. case '2':
  151. case '3':
  152. case '4':
  153. case '5':
  154. case '6':
  155. case '7':
  156. case '8':
  157. case '9': ret = ret*10+(*s-'0');
  158. break;
  159. default:
  160. return ret;
  161. }
  162. s++;
  163. }
  164. return 0;
  165. }
  166. #if defined(_WIN32)
  167. static __int64 numCyclesNTicks;
  168. static __int64 ticksPerSec;
  169. static __int64 numScaleTicks;
  170. static bool useRDTSC = _USE_RDTSC;
  171. static double cycleToNanoScale;
  172. static void calibrate_timing()
  173. {
  174. #ifndef _AMD64_
  175. if (useRDTSC)
  176. {
  177. unsigned long r;
  178. __asm {
  179. mov eax, 1 ;
  180. cpuid ;
  181. mov r, edx
  182. }
  183. if ((r&0x10)==0)
  184. useRDTSC = false;
  185. }
  186. #endif
  187. if (useRDTSC) {
  188. unsigned startu = usTick();
  189. cycle_t start = getTSC();
  190. unsigned s1 = msTick();
  191. unsigned s2;
  192. while (s1==(s2=msTick()));
  193. unsigned s3;
  194. while (s2==(s3=msTick()));
  195. unsigned elapsedu = usTick()-startu;
  196. if (elapsedu) {
  197. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  198. if (numPerUS>0)
  199. {
  200. cycleToNanoScale = 1000.0 / numPerUS;
  201. return;
  202. }
  203. }
  204. ERRLOG("calibrate_timing failed using RDTSC");
  205. useRDTSC = false;
  206. }
  207. static LARGE_INTEGER temp;
  208. QueryPerformanceFrequency(&temp);
  209. ticksPerSec = temp.QuadPart;
  210. numScaleTicks = ticksPerSec/100;
  211. LARGE_INTEGER t1;
  212. LARGE_INTEGER t2;
  213. QueryPerformanceCounter(&t1);
  214. t2.QuadPart=t1.QuadPart;
  215. while (t1.QuadPart==t2.QuadPart) QueryPerformanceCounter(&t1);
  216. cycle_t a1 = getTSC();
  217. t2.QuadPart = t1.QuadPart;
  218. while (t2.QuadPart-t1.QuadPart<numScaleTicks) QueryPerformanceCounter(&t2);
  219. cycle_t a2 = getTSC();
  220. numCyclesNTicks = (a2 - a1);
  221. cycleToNanoScale = ((double)numScaleTicks * 1000000000.0) / ((double)numCyclesNTicks * ticksPerSec);
  222. }
  223. __int64 cycle_to_nanosec(cycle_t cycles)
  224. {
  225. return (__int64)((double)cycles * cycleToNanoScale);
  226. }
  227. __int64 jlib_decl cycle_to_microsec(cycle_t cycles)
  228. {
  229. return (__int64)((double)cycles * cycleToNanoScale) / 1000;
  230. }
  231. __int64 jlib_decl cycle_to_millisec(cycle_t cycles)
  232. {
  233. return (__int64)((double)cycles * cycleToNanoScale) / 1000000;
  234. }
  235. cycle_t nanosec_to_cycle(__int64 ns)
  236. {
  237. return (__int64)((double)ns / cycleToNanoScale);
  238. }
  239. #if !(defined(INLINE_GET_CYCLES_NOW) && defined(HAS_GOOD_CYCLE_COUNTER))
  240. cycle_t jlib_decl get_cycles_now()
  241. {
  242. if (useRDTSC)
  243. return getTSC();
  244. LARGE_INTEGER temp;
  245. QueryPerformanceCounter(&temp);
  246. return temp.QuadPart;
  247. }
  248. #endif
  249. double getCycleToNanoScale()
  250. {
  251. return cycleToNanoScale;
  252. }
  253. #else
  254. #if defined(HAS_GOOD_CYCLE_COUNTER)
  255. static bool useRDTSC = _USE_RDTSC;
  256. #endif
  257. static double cycleToNanoScale;
  258. static double cycleToMicroScale;
  259. static double cycleToMilliScale;
  260. void calibrate_timing()
  261. {
  262. #if defined(_ARCH_X86_) || defined(_ARCH_X86_64_)
  263. if (useRDTSC) {
  264. unsigned long eax;
  265. unsigned long ebx;
  266. unsigned long ecx;
  267. unsigned long edx;
  268. #if defined(_ARCH_X86_64_)
  269. __asm__ ("cpuid\n\t" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "0" (1));
  270. #else
  271. // NB PIC code and ebx usage don't mix well
  272. asm volatile("pushl %%ebx \n\t"
  273. "cpuid \n\t"
  274. "movl %%ebx, %1 \n\t"
  275. "popl %%ebx \n\t"
  276. : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx)
  277. : "a"(1)
  278. : "cc");
  279. #endif
  280. if ((edx&0x10)==0)
  281. useRDTSC = false;
  282. }
  283. #endif
  284. #if defined(HAS_GOOD_CYCLE_COUNTER)
  285. if (useRDTSC) {
  286. unsigned startu = usTick();
  287. cycle_t start = getTSC();
  288. unsigned s1 = msTick();
  289. unsigned s2;
  290. while (s1==(s2=msTick()));
  291. unsigned s3;
  292. while (s2==(s3=msTick()));
  293. unsigned elapsedu = usTick()-startu;
  294. if (elapsedu) {
  295. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  296. if (numPerUS>0)
  297. {
  298. cycleToNanoScale = 1000.0 / numPerUS;
  299. cycleToMicroScale = 1.0 / numPerUS;
  300. cycleToMilliScale = 0.001 / numPerUS;
  301. return;
  302. }
  303. }
  304. ERRLOG("calibrate_timing failed using RDTSC");
  305. useRDTSC = false;
  306. }
  307. #endif
  308. cycleToNanoScale = 1.0;
  309. cycleToMicroScale = 1.0;
  310. cycleToMilliScale = 1.0;
  311. }
  312. #if !defined(INLINE_GET_CYCLES_NOW) || !defined(HAS_GOOD_CYCLE_COUNTER)
  313. #if defined(CLOCK_MONOTONIC) && !defined(__APPLE__)
  314. static bool use_gettimeofday=false;
  315. #endif
  316. cycle_t jlib_decl get_cycles_now()
  317. {
  318. #if defined(HAS_GOOD_CYCLE_COUNTER)
  319. if (useRDTSC)
  320. return getTSC();
  321. #endif
  322. #ifdef __APPLE__
  323. return mach_absolute_time();
  324. #elif defined(CLOCK_MONOTONIC)
  325. if (!use_gettimeofday) {
  326. timespec tm;
  327. if (clock_gettime(CLOCK_MONOTONIC, &tm)>=0)
  328. return ((cycle_t)tm.tv_sec)*1000000000L+(tm.tv_nsec);
  329. use_gettimeofday = true;
  330. fprintf(stderr,"clock_gettime CLOCK_MONOTONIC returns %d",errno); // don't use PROGLOG
  331. }
  332. #endif
  333. struct timeval tm;
  334. gettimeofday(&tm,NULL);
  335. return ((cycle_t)tm.tv_sec)*1000000000L+(cycle_t)tm.tv_usec*1000L;
  336. }
  337. #endif
  338. __int64 jlib_decl cycle_to_nanosec(cycle_t cycles)
  339. {
  340. #if defined(HAS_GOOD_CYCLE_COUNTER)
  341. if (useRDTSC)
  342. return (__int64)((double)cycles * cycleToNanoScale);
  343. #endif
  344. #ifdef __APPLE__
  345. return cycles * (uint64_t) timebase_info.numer / (uint64_t)timebase_info.denom;
  346. #endif
  347. return cycles;
  348. }
  349. __int64 jlib_decl cycle_to_microsec(cycle_t cycles)
  350. {
  351. #if defined(HAS_GOOD_CYCLE_COUNTER)
  352. if (useRDTSC)
  353. return (__int64)((double)cycles * cycleToMicroScale);
  354. #endif
  355. return cycles / 1000;
  356. }
  357. __int64 jlib_decl cycle_to_millisec(cycle_t cycles)
  358. {
  359. #if defined(HAS_GOOD_CYCLE_COUNTER)
  360. if (useRDTSC)
  361. return (__int64)((double)cycles * cycleToMilliScale);
  362. #endif
  363. return cycles / 1000000;
  364. }
  365. cycle_t nanosec_to_cycle(__int64 ns)
  366. {
  367. #if defined(HAS_GOOD_CYCLE_COUNTER)
  368. if (useRDTSC)
  369. return (__int64)((double)ns / cycleToNanoScale);
  370. #endif
  371. return ns;
  372. }
  373. double getCycleToNanoScale()
  374. {
  375. return cycleToNanoScale;
  376. }
  377. #endif
  378. void display_time(const char *title, cycle_t diff)
  379. {
  380. DBGLOG("Time taken for %s: %" I64F "d cycles (%" I64F "dM) = %" I64F "d msec", title, diff, diff/1000000, cycle_to_nanosec(diff)/1000000);
  381. }
  382. TimeSection::TimeSection(const char * _title) : title(_title)
  383. {
  384. start_time = get_cycles_now();
  385. }
  386. TimeSection::~TimeSection()
  387. {
  388. cycle_t end_time = get_cycles_now();
  389. if (title)
  390. display_time(title, end_time-start_time);
  391. }
  392. MTimeSection::MTimeSection(ITimeReporter *_master, const char * _scope) : scope(_scope), master(_master)
  393. {
  394. start_time = get_cycles_now();
  395. }
  396. MTimeSection::~MTimeSection()
  397. {
  398. cycle_t end_time = get_cycles_now();
  399. if (master)
  400. master->addTiming(scope, end_time-start_time);
  401. else if (scope)
  402. display_time(scope, end_time-start_time);
  403. }
  404. class TimeSectionInfo : public MappingBase
  405. {
  406. public:
  407. TimeSectionInfo(const char * _scope, __int64 _cycles) : scope(_scope), totalcycles(_cycles), maxcycles(_cycles), count(1) {};
  408. TimeSectionInfo(const char * _scope, __int64 _cycles, __int64 _maxcycles, unsigned _count)
  409. : scope(_scope), totalcycles(_cycles), maxcycles(_maxcycles), count(_count) {};
  410. virtual const void * getKey() const { return scope.get(); }
  411. __int64 getTime() const { return cycle_to_nanosec(totalcycles); }
  412. __int64 getMaxTime() const { return cycle_to_nanosec(maxcycles); }
  413. unsigned getCount() const { return count; }
  414. StringAttr scope;
  415. __int64 totalcycles;
  416. __int64 maxcycles;
  417. unsigned count;
  418. };
  419. class DefaultTimeReporter : implements ITimeReporter, public CInterface
  420. {
  421. StringMapOf<TimeSectionInfo> *sections;
  422. CriticalSection c;
  423. TimeSectionInfo &findSection(unsigned idx)
  424. {
  425. CriticalBlock b(c);
  426. HashIterator iter(*sections);
  427. for(iter.first(); iter.isValid(); iter.next())
  428. {
  429. if (!idx--)
  430. return (TimeSectionInfo &) iter.query();
  431. }
  432. throw MakeStringException(2, "Invalid index to DefaultTimeReporter");
  433. }
  434. public:
  435. IMPLEMENT_IINTERFACE
  436. DefaultTimeReporter()
  437. {
  438. sections = new StringMapOf<TimeSectionInfo>(true);
  439. }
  440. ~DefaultTimeReporter()
  441. {
  442. // printTimings(); // Must explicitly call printTimings - no automatic print (too late here!)
  443. delete sections;
  444. }
  445. virtual void report(ITimeReportInfo &cb)
  446. {
  447. CriticalBlock b(c);
  448. HashIterator iter(*sections);
  449. for(iter.first(); iter.isValid(); iter.next())
  450. {
  451. TimeSectionInfo &ts = (TimeSectionInfo &)iter.query();
  452. cb.report(ts.scope, ts.getTime(), ts.getMaxTime(), ts.count);
  453. }
  454. }
  455. virtual void addTiming(const char * scope, cycle_t cycles)
  456. {
  457. CriticalBlock b(c);
  458. TimeSectionInfo *info = sections->find(scope);
  459. if (info)
  460. {
  461. info->totalcycles += cycles;
  462. if (cycles > info->maxcycles) info->maxcycles = cycles;
  463. info->count++;
  464. }
  465. else
  466. {
  467. TimeSectionInfo &newinfo = * new TimeSectionInfo(scope, cycles);
  468. sections->replaceOwn(newinfo);
  469. }
  470. }
  471. virtual void reset()
  472. {
  473. CriticalBlock b(c);
  474. delete sections;
  475. sections = new StringMapOf<TimeSectionInfo>(true);
  476. }
  477. virtual StringBuffer &getTimings(StringBuffer &str)
  478. {
  479. CriticalBlock b(c);
  480. HashIterator iter(*sections);
  481. for(iter.first(); iter.isValid(); iter.next())
  482. {
  483. TimeSectionInfo &ts = (TimeSectionInfo &)iter.query();
  484. str.append("Timing: ").append(ts.scope)
  485. .append(" total=")
  486. .append(ts.getTime()/1000000)
  487. .append("ms max=")
  488. .append(ts.getMaxTime()/1000)
  489. .append("us count=")
  490. .append(ts.getCount())
  491. .append(" ave=")
  492. .append((ts.getTime()/1000)/ts.getCount())
  493. .append("us\n");
  494. }
  495. if (numSections())
  496. {
  497. for (unsigned i = 0; i < numSections(); i++)
  498. {
  499. }
  500. }
  501. return str;
  502. }
  503. virtual void printTimings()
  504. {
  505. CriticalBlock b(c);
  506. if (numSections())
  507. {
  508. StringBuffer str;
  509. PrintLog(getTimings(str).str());
  510. }
  511. }
  512. virtual void mergeTiming(const char * scope, cycle_t totalcycles, cycle_t maxcycles, const unsigned count)
  513. {
  514. CriticalBlock b(c);
  515. TimeSectionInfo *info = sections->find(scope);
  516. if (!info)
  517. {
  518. info = new TimeSectionInfo(scope, totalcycles, maxcycles, count);
  519. sections->replaceOwn(*info);
  520. }
  521. else
  522. {
  523. info->totalcycles += totalcycles;
  524. if (maxcycles > info->maxcycles) info->maxcycles = maxcycles;
  525. info->count += count;
  526. }
  527. }
  528. virtual void mergeInto(ITimeReporter &other)
  529. {
  530. CriticalBlock b(c);
  531. HashIterator iter(*sections);
  532. for(iter.first(); iter.isValid(); iter.next())
  533. {
  534. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  535. other.mergeTiming(ts.scope, ts.totalcycles, ts.maxcycles, ts.count);
  536. }
  537. }
  538. virtual void merge(ITimeReporter &other)
  539. {
  540. CriticalBlock b(c);
  541. other.mergeInto(*this);
  542. }
  543. protected:
  544. unsigned numSections()
  545. {
  546. return sections->count();
  547. }
  548. };
  549. static ITimeReporter * activeTimer = NULL;
  550. ITimeReporter * queryActiveTimer()
  551. {
  552. return activeTimer;
  553. }
  554. ITimeReporter *createStdTimeReporter() { return new DefaultTimeReporter(); }
  555. cycle_t oneSecInCycles;
  556. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  557. {
  558. // perform v. early in process startup, ideally this would grab process exclusively for the 2 100ths of a sec it performs calc.
  559. calibrate_timing();
  560. oneSecInCycles = nanosec_to_cycle(1000000000);
  561. return 1;
  562. }
  563. MODULE_INIT(INIT_PRIORITY_JDEBUG2)
  564. {
  565. activeTimer = new DefaultTimeReporter();
  566. return true;
  567. }
  568. MODULE_EXIT()
  569. {
  570. ::Release(activeTimer);
  571. activeTimer = NULL;
  572. }
  573. //===========================================================================
  574. #ifdef _WIN32
  575. typedef enum _PROCESSINFOCLASS {
  576. ProcessBasicInformation,
  577. ProcessQuotaLimits,
  578. ProcessIoCounters,
  579. ProcessVmCounters,
  580. ProcessTimes,
  581. ProcessBasePriority,
  582. ProcessRaisePriority,
  583. ProcessDebugPort,
  584. ProcessExceptionPort,
  585. ProcessAccessToken,
  586. ProcessLdtInformation,
  587. ProcessLdtSize,
  588. ProcessDefaultHardErrorMode,
  589. ProcessIoPortHandlers, // Note: this is kernel mode only
  590. ProcessPooledUsageAndLimits,
  591. ProcessWorkingSetWatch,
  592. ProcessUserModeIOPL,
  593. ProcessEnableAlignmentFaultFixup,
  594. ProcessPriorityClass,
  595. ProcessWx86Information,
  596. ProcessHandleCount,
  597. ProcessAffinityMask,
  598. ProcessPriorityBoost,
  599. ProcessDeviceMap,
  600. ProcessSessionInformation,
  601. ProcessForegroundInformation,
  602. ProcessWow64Information,
  603. MaxProcessInfoClass
  604. } PROCESSINFOCLASS;
  605. typedef LONG NTSTATUS;
  606. struct __IO_COUNTERS { // defined in SDK
  607. ULONGLONG ReadOperationCount;
  608. ULONGLONG WriteOperationCount;
  609. ULONGLONG OtherOperationCount;
  610. ULONGLONG ReadTransferCount;
  611. ULONGLONG WriteTransferCount;
  612. ULONGLONG OtherTransferCount;
  613. };
  614. struct VM_COUNTERS {
  615. unsigned long PeakVirtualSize;
  616. unsigned long VirtualSize;
  617. unsigned long PageFaultCount;
  618. unsigned long PeakWorkingSetSize;
  619. unsigned long WorkingSetSize;
  620. unsigned long QuotaPeakPagedPoolUsage;
  621. unsigned long QuotaPagedPoolUsage;
  622. unsigned long QuotaPeakNonPagedPoolUsage;
  623. unsigned long QuotaNonPagedPoolUsage;
  624. unsigned long PagefileUsage;
  625. unsigned long PeakPagefileUsage;
  626. };
  627. struct POOLED_USAGE_AND_LIMITS {
  628. unsigned long PeakPagedPoolUsage;
  629. unsigned long PagedPoolUsage;
  630. unsigned long PagedPoolLimit;
  631. unsigned long PeakNonPagedPoolUsage;
  632. unsigned long NonPagedPoolUsage;
  633. unsigned long NonPagedPoolLimit;
  634. unsigned long PeakPagefileUsage;
  635. unsigned long PagefileUsage;
  636. unsigned long PagefileLimit;
  637. };
  638. struct KERNEL_USER_TIMES {
  639. __int64 CreateTime;
  640. __int64 ExitTime;
  641. __int64 KernelTime;
  642. __int64 UserTime;
  643. //__int64 EllapsedTime;
  644. };
  645. //
  646. //NTSYSCALLAPI
  647. //NTSTATUS
  648. //NTAPI
  649. //NtQueryInformationProcess(
  650. // IN HANDLE ProcessHandle,
  651. // IN PROCESSINFOCLASS ProcessInformationClass,
  652. // OUT PVOID ProcessInformation,
  653. // IN ULONG ProcessInformationLength,
  654. // OUT PULONG ReturnLength OPTIONAL
  655. // );
  656. typedef LONG(WINAPI *PROCNTQIP)(HANDLE, UINT, PVOID, ULONG, PULONG);
  657. static struct CNtKernelInformation
  658. {
  659. CNtKernelInformation()
  660. {
  661. NtQueryInformationProcess = (PROCNTQIP)GetProcAddress(
  662. GetModuleHandle("ntdll"),
  663. "NtQueryInformationProcess"
  664. );
  665. GetSystemInfo(&SysBaseInfo);
  666. }
  667. PROCNTQIP NtQueryInformationProcess;
  668. SYSTEM_INFO SysBaseInfo;
  669. } NtKernelFunctions;
  670. #endif
  671. //===========================================================================
  672. #ifdef _WIN32
  673. static __uint64 ticksToNs = I64C(100); // FILETIME is in 100ns increments
  674. #else
  675. static __uint64 ticksToNs = I64C(1000000000) / sysconf(_SC_CLK_TCK);
  676. #endif
  677. #ifdef _WIN32
  678. inline unsigned __int64 extractFILETIME(const FILETIME & value)
  679. {
  680. return ((__uint64)value.dwHighDateTime << (sizeof(value.dwLowDateTime) * 8) | value.dwLowDateTime);
  681. }
  682. #endif
  683. CpuInfo::CpuInfo(bool processTime, bool systemTime) : CpuInfo()
  684. {
  685. if (processTime)
  686. getProcessTimes();
  687. else if (systemTime)
  688. getSystemTimes();
  689. }
  690. void CpuInfo::clear()
  691. {
  692. user = 0;
  693. system = 0;
  694. idle = 0;
  695. iowait = 0;
  696. }
  697. CpuInfo CpuInfo::operator - (const CpuInfo & rhs) const
  698. {
  699. CpuInfo result;
  700. result.user = user - rhs.user;
  701. result.system = system - rhs.system;
  702. result.idle = idle - rhs.idle;
  703. result.iowait = iowait - rhs.iowait;
  704. result.ctx = ctx - rhs.ctx;
  705. return result;
  706. }
  707. bool CpuInfo::getProcessTimes()
  708. {
  709. #ifdef _WIN32
  710. FILETIME kernelTime, userTime;
  711. GetProcessTimes(GetCurrentProcess(), nullptr, nullptr, &kernelTime, &userTime);
  712. user = extractFILETIME(userTime);
  713. system = extractFILETIME(kernelTime);
  714. return true;
  715. #else
  716. VStringBuffer fname("/proc/%u/stat", getpid());
  717. //NOTE: This file needs to be reopened each time - seeking to the start and rereading does not refresh it
  718. clear();
  719. FILE* cpufp = fopen(fname.str(), "r");
  720. if (!cpufp) {
  721. return false;
  722. }
  723. char ln[2560];
  724. if (fgets(ln, sizeof(ln), cpufp))
  725. {
  726. long int majorFaults = 0;
  727. long unsigned userTime = 0;
  728. long unsigned systemTime = 0;
  729. long unsigned childUserTime = 0;
  730. long unsigned childSystemTime = 0;
  731. int matched = sscanf(ln, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %lu %*u %lu %lu %lu %lu", &majorFaults, &userTime, &systemTime, &childUserTime, &childSystemTime);
  732. if (matched >= 3)
  733. {
  734. user = userTime + childUserTime;
  735. system = systemTime + childSystemTime;
  736. }
  737. }
  738. fclose(cpufp);
  739. return true;
  740. #endif
  741. }
  742. bool CpuInfo::getSystemTimes()
  743. {
  744. #ifdef _WIN32
  745. FILETIME idleTime, kernelTime, userTime;
  746. GetSystemTimes(&idleTime, &kernelTime, &userTime);
  747. // note - kernel time seems to include idle time
  748. idle = extractFILETIME(idleTime);
  749. user = extractFILETIME(userTime);
  750. system = extractFILETIME(kernelTime) - idle;
  751. return true;
  752. #else
  753. //NOTE: This file needs to be reopened each time - seeking to the start and rereading does not refresh it
  754. FILE* cpufp = fopen("/proc/stat", "r");
  755. if (!cpufp) {
  756. clear();
  757. return false;
  758. }
  759. char ln[256];
  760. while (fgets(ln, sizeof(ln), cpufp))
  761. {
  762. if (strncmp(ln, "cpu ", 4) == 0)
  763. {
  764. int items;
  765. __uint64 nice, irq, softirq;
  766. items = sscanf(ln,
  767. "cpu %llu %llu %llu %llu %llu %llu %llu",
  768. &user, &nice,
  769. &system,
  770. &idle,
  771. &iowait,
  772. &irq, &softirq);
  773. user += nice;
  774. if (items == 4)
  775. iowait = 0;
  776. if (items == 7)
  777. system += irq + softirq;
  778. }
  779. else if (strncmp(ln, "ctxt ", 5) == 0)
  780. {
  781. (void)sscanf(ln, "ctxt %llu", &ctx);
  782. }
  783. }
  784. fclose(cpufp);
  785. return true;
  786. #endif
  787. }
  788. unsigned CpuInfo::getPercentCpu() const
  789. {
  790. __uint64 total = getTotal();
  791. if (total == 0)
  792. return 0;
  793. unsigned percent = (unsigned)(((total - idle) * 100) / idle);
  794. if (percent > 100)
  795. percent = 100;
  796. return percent;
  797. }
  798. __uint64 CpuInfo::getSystemNs() const
  799. {
  800. return system * ticksToNs;
  801. }
  802. __uint64 CpuInfo::getUserNs() const
  803. {
  804. return user * ticksToNs;
  805. }
  806. __uint64 CpuInfo::getTotalNs() const
  807. {
  808. return getTotal() * ticksToNs;
  809. }
  810. unsigned CpuInfo::getIdlePercent() const
  811. {
  812. return (unsigned)((idle * 100) / getTotal());
  813. }
  814. unsigned CpuInfo::getIoWaitPercent() const
  815. {
  816. return (unsigned)((iowait * 100) / getTotal());
  817. }
  818. unsigned CpuInfo::getSystemPercent() const
  819. {
  820. return (unsigned)((system * 100) / getTotal());
  821. }
  822. unsigned CpuInfo::getUserPercent() const
  823. {
  824. return (unsigned)((user * 100) / getTotal());
  825. }
  826. //===========================================================================
  827. void BlockIoStats::clear()
  828. {
  829. rd_ios = 0;
  830. rd_merges = 0;
  831. rd_sectors = 0;
  832. rd_ticks = 0;
  833. wr_ios = 0;
  834. wr_merges = 0;
  835. wr_sectors = 0;
  836. wr_ticks = 0;
  837. ticks = 0;
  838. aveq = 0;
  839. }
  840. BlockIoStats & BlockIoStats::operator += (const BlockIoStats & other)
  841. {
  842. rd_ios += other.rd_ios;
  843. rd_merges += other.rd_merges;
  844. rd_sectors += other.rd_sectors;
  845. rd_ticks += other.rd_ticks;
  846. wr_ios += other.wr_ios;
  847. wr_merges += other.wr_merges;
  848. wr_sectors += other.wr_sectors;
  849. wr_ticks += other.wr_ticks;
  850. ticks += other.ticks;
  851. aveq += other.aveq;
  852. return *this;
  853. }
  854. BlockIoStats BlockIoStats::operator - (const BlockIoStats & other) const
  855. {
  856. BlockIoStats result;
  857. result.rd_ios = rd_ios - other.rd_ios;
  858. result.rd_merges = rd_merges - other.rd_merges;
  859. result.rd_sectors = rd_sectors - other.rd_sectors;
  860. result.rd_ticks = rd_ticks - other.rd_ticks;
  861. result.wr_ios = wr_ios - other.wr_ios;
  862. result.wr_merges = wr_merges - other.wr_merges;
  863. result.wr_sectors = wr_sectors - other.wr_sectors;
  864. result.wr_ticks = wr_ticks - other.wr_ticks;
  865. result.ticks = ticks - other.ticks;
  866. result.aveq = aveq - other.aveq;
  867. return result;
  868. }
  869. //===========================================================================
  870. // Performance Monitor
  871. #ifdef _WIN32
  872. memsize_t getMapInfo(const char *type)
  873. {
  874. return 0; // TODO/UNKNOWN
  875. }
  876. memsize_t getVMInfo(const char *type)
  877. {
  878. return 0; // TODO/UNKNOWN
  879. }
  880. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  881. {
  882. // MORE: Might be a better way to get CPU speed (actual) than the one stored in Registry
  883. LONG lRet;
  884. HKEY hKey;
  885. DWORD keyValue;
  886. DWORD valueLen = sizeof(keyValue);
  887. if ((lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0L, KEY_READ , &hKey)) != ERROR_SUCCESS)
  888. {
  889. DBGLOG("RegOpenKeyEx(HKEY_LOCAL_MACHINE, ...) failed to open CentralProcessor\\0 - SysErrorCode=%d", lRet);
  890. }
  891. else if ((lRet = RegQueryValueEx(hKey, TEXT("~MHz"), NULL, NULL, (LPBYTE) &keyValue, &valueLen)) != ERROR_SUCCESS)
  892. {
  893. DBGLOG("RegQueryValueEx() failed to get CPU speed - errorCode=%d", lRet);
  894. RegCloseKey(hKey);
  895. }
  896. else
  897. {
  898. CPUSpeed = keyValue;
  899. RegCloseKey(hKey);
  900. }
  901. SYSTEM_INFO sysInfo;
  902. GetSystemInfo(&sysInfo);
  903. numCPUs = sysInfo.dwNumberOfProcessors;
  904. }
  905. static unsigned evalAffinityCpus()
  906. {
  907. unsigned numCpus = 0;
  908. DWORD ProcessAffinityMask, SystemAffinityMask;
  909. if (GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&ProcessAffinityMask, (PDWORD_PTR)&SystemAffinityMask))
  910. {
  911. unsigned i = 0;
  912. while (ProcessAffinityMask)
  913. {
  914. if (ProcessAffinityMask & 1)
  915. ++numCpus;
  916. ProcessAffinityMask >>=1;
  917. }
  918. }
  919. else // fall back to legacy num system cpus
  920. {
  921. Owned<IException> e = makeOsException(GetLastError(), "Failed to get affinity");
  922. EXCLOG(e, NULL);
  923. unsigned cpuSpeed;
  924. getCpuInfo(numCpus, cpuSpeed);
  925. return numCpus;
  926. }
  927. return numCpus;
  928. }
  929. #else // linux
  930. memsize_t getMapInfo(const char *type)
  931. {
  932. // NOTE: 'total' heap value includes Roxiemem allocation, if present
  933. enum mapList { HEAP, STACK, SBRK, ANON };
  934. enum mapList mapType;
  935. if ( streq(type, "heap") )
  936. mapType = HEAP;
  937. else if ( streq(type, "stack") )
  938. mapType = STACK;
  939. else if ( streq(type, "sbrk") )
  940. mapType = SBRK;
  941. else if ( streq(type, "anon") )
  942. mapType = ANON;
  943. else
  944. return 0;
  945. memsize_t ret = 0;
  946. VStringBuffer procMaps("/proc/%d/maps", GetCurrentProcessId());
  947. FILE *diskfp = fopen(procMaps.str(), "r");
  948. if (!diskfp)
  949. return false;
  950. char ln[256];
  951. /*
  952. * exmaple /proc/<pid>/maps format:
  953. * addr_start -addr_end perms offset dev inode pathname
  954. * 01c3a000-01c5b000 rw-p 00000000 00:00 0 [heap]
  955. * 7f3f25217000-7f3f25a40000 rw-p 00000000 00:00 0 [stack:2362]
  956. * 7f4020a40000-7f4020a59000 rw-p 00000000 00:00 0
  957. * 7f4020a59000-7f4020a5a000 ---p 00000000 00:00 0
  958. * 7f4029bd4000-7f4029bf6000 r-xp 00000000 08:01 17576135 /lib/x86_64-linux-gnu/ld-2.15.so
  959. */
  960. while (fgets(ln, sizeof(ln), diskfp))
  961. {
  962. bool skipline = true;
  963. if ( mapType == HEAP || mapType == ANON ) // 'general' heap includes anon mmapped + sbrk
  964. {
  965. // skip file maps (beginning with /) and all other regions (except [heap if selected)
  966. if ( (mapType == HEAP && strstr(ln, "[heap")) || (!strstr(ln, " /") && !strstr(ln, " [")) )
  967. {
  968. // include only (r)ead + (w)rite and (p)rivate (not shared), skipping e(x)ecutable
  969. // and ---p guard regions
  970. if ( strstr(ln, " rw-p") )
  971. skipline = false;
  972. }
  973. }
  974. else if ( mapType == STACK )
  975. {
  976. if ( strstr(ln, "[stack") )
  977. skipline = false;
  978. }
  979. else if ( mapType == SBRK )
  980. {
  981. if ( strstr(ln, "[heap") )
  982. skipline = false;
  983. }
  984. if ( !skipline )
  985. {
  986. unsigned __int64 addrLow, addrHigh;
  987. if (2 == sscanf(ln, "%16" I64F "x-%16" I64F "x", &addrLow, &addrHigh))
  988. ret += (memsize_t)(addrHigh-addrLow);
  989. }
  990. }
  991. fclose(diskfp);
  992. return ret;
  993. }
  994. static bool matchExtract(const char * prefix, const char * line, memsize_t & value)
  995. {
  996. size32_t len = strlen(prefix);
  997. if (strncmp(prefix, line, len)==0)
  998. {
  999. char * tail = NULL;
  1000. value = strtol(line+len, &tail, 10);
  1001. while (isspace(*tail))
  1002. tail++;
  1003. if (strncmp(tail, "kB", 2) == 0)
  1004. value *= 0x400;
  1005. else if (strncmp(tail, "mB", 2) == 0)
  1006. value *= 0x100000;
  1007. else if (strncmp(tail, "gB", 2) == 0)
  1008. value *= 0x40000000;
  1009. return true;
  1010. }
  1011. return false;
  1012. }
  1013. memsize_t getVMInfo(const char *type)
  1014. {
  1015. memsize_t ret = 0;
  1016. VStringBuffer name("%s:", type);
  1017. VStringBuffer procMaps("/proc/self/status");
  1018. FILE *diskfp = fopen(procMaps.str(), "r");
  1019. if (!diskfp)
  1020. return 0;
  1021. char ln[256];
  1022. while (fgets(ln, sizeof(ln), diskfp))
  1023. {
  1024. if (matchExtract(name.str(), ln, ret))
  1025. break;
  1026. }
  1027. fclose(diskfp);
  1028. return ret;
  1029. }
  1030. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  1031. {
  1032. numCPUs = 1;
  1033. CPUSpeed = 0;
  1034. #ifdef __APPLE__
  1035. # if defined(_SC_NPROCESSORS_CONF)
  1036. int ncpus = sysconf(_SC_NPROCESSORS_CONF);
  1037. if (ncpus > 0)
  1038. numCPUs = ncpus;
  1039. # endif
  1040. #else // linux
  1041. // NOTE: Could have perhaps used sysconf(_SC_NPROCESSORS_CONF) for numCPUs
  1042. FILE *cpufp = fopen("/proc/cpuinfo", "r");
  1043. if (cpufp == NULL)
  1044. return;
  1045. char * tail;
  1046. // MORE: It is a shame that the info in this file (/proc/cpuinfo) are formatted (ie tabs .. etc)
  1047. const char *cpuNumTag = "processor\t:";
  1048. const char *cpuSpeedTag = "cpu MHz\t\t:";
  1049. // NOTE: This provides current cpu freq, not max
  1050. numCPUs = 0;
  1051. char line[1001];
  1052. const char *bufptr;
  1053. while ((bufptr = fgets(line, 1000, cpufp)) != NULL)
  1054. {
  1055. if (strncmp(cpuNumTag, bufptr, strlen(cpuNumTag))==0)
  1056. numCPUs++;
  1057. else if (strncmp(cpuSpeedTag, bufptr, strlen(cpuSpeedTag))==0)
  1058. CPUSpeed = (unsigned)strtol(bufptr+strlen(cpuSpeedTag), &tail, 10);
  1059. }
  1060. fclose(cpufp);
  1061. if (numCPUs < 1)
  1062. numCPUs = 1;
  1063. // max cpu freq (KHz) may be in:
  1064. // /sys/devices/system/cpu/cpu[0-X]/cpufreq/cpuinfo_max_freq
  1065. cpufp = fopen("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r");
  1066. if (cpufp != NULL)
  1067. {
  1068. unsigned CPUSpeedMax = 0;
  1069. int srtn = fscanf(cpufp, "%u", &CPUSpeedMax);
  1070. if (srtn == 1)
  1071. {
  1072. CPUSpeedMax /= 1000;
  1073. if (CPUSpeedMax > CPUSpeed)
  1074. CPUSpeed = CPUSpeedMax;
  1075. }
  1076. fclose(cpufp);
  1077. }
  1078. #endif
  1079. }
  1080. static unsigned evalAffinityCpus()
  1081. {
  1082. #ifdef __APPLE__
  1083. // MORE - could do better
  1084. #else
  1085. cpu_set_t cpuset;
  1086. int err = pthread_getaffinity_np(GetCurrentThreadId(), sizeof(cpu_set_t), &cpuset);
  1087. if (0 == err)
  1088. {
  1089. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 6)
  1090. return CPU_COUNT(&cpuset);
  1091. #else
  1092. unsigned numCpus = 0;
  1093. unsigned setSize = CPU_SETSIZE;
  1094. while (setSize--)
  1095. {
  1096. if (CPU_ISSET(setSize, &cpuset))
  1097. ++numCpus;
  1098. }
  1099. return numCpus;
  1100. #endif /* GLIBC */
  1101. }
  1102. #endif
  1103. return 1;
  1104. }
  1105. // Note - values are returned in Kb
  1106. static void getMemUsage(unsigned &inuse,unsigned &active,unsigned &total,unsigned &swaptotal,unsigned &swapinuse)
  1107. {
  1108. #ifdef __APPLE__
  1109. active = 0;
  1110. inuse = 0;
  1111. total = 0;
  1112. swaptotal = 0;
  1113. swapinuse = 0;
  1114. vm_size_t pageSize;
  1115. if (KERN_SUCCESS != host_page_size(mach_host_self(), &pageSize))
  1116. return;
  1117. mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
  1118. vm_statistics64_data_t vmstat;
  1119. if (KERN_SUCCESS != host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vmstat, &count))
  1120. return;
  1121. uint64_t totalBytes = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count + vmstat.compressor_page_count) * pageSize;
  1122. uint64_t inuseBytes = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.compressor_page_count) * pageSize;
  1123. uint64_t activeBytes = (vmstat.wire_count + vmstat.active_count) * pageSize;
  1124. active = activeBytes / 1024;
  1125. inuse = inuseBytes / 1024;
  1126. total = totalBytes / 1024;
  1127. // swaptotal and swapinuse TBD
  1128. #else
  1129. unsigned free=0;
  1130. unsigned swapfree=0;
  1131. active = 0;
  1132. inuse = 0;
  1133. static int memfd = -1;
  1134. if (memfd==-1)
  1135. memfd = open("/proc/meminfo",O_RDONLY);
  1136. if (memfd==-1)
  1137. return;
  1138. char buf[2048];
  1139. size32_t l = pread(memfd, buf, sizeof(buf)-1, 0L);
  1140. if ((int)l<=0)
  1141. return;
  1142. buf[l] = 0;
  1143. const char *bufptr = buf;
  1144. char * tail;
  1145. unsigned i = 7; // supposed to match max number of items extract below
  1146. total = swaptotal = free = active = swapfree = 0;
  1147. unsigned swapcached = 0;
  1148. unsigned cached = 0;
  1149. while (bufptr&&i) {
  1150. if (*bufptr =='\n')
  1151. bufptr++;
  1152. i--;
  1153. if (strncmp("MemTotal:", bufptr, 9)==0)
  1154. total = (unsigned)strtol(bufptr+9, &tail, 10);
  1155. else if (strncmp("SwapTotal:", bufptr, 10)==0)
  1156. swaptotal = (unsigned)strtol(bufptr+10, &tail, 10);
  1157. else if (strncmp("MemFree:", bufptr, 8)==0)
  1158. free = (unsigned)strtol(bufptr+8, &tail, 10);
  1159. else if (strncmp("Active:", bufptr, 7)==0)
  1160. active = (unsigned)strtol(bufptr+7, &tail, 10);
  1161. else if (strncmp("SwapFree:", bufptr, 9)==0)
  1162. swapfree = (unsigned)strtol(bufptr+9, &tail, 10);
  1163. else if (strncmp("Cached:", bufptr, 7)==0)
  1164. cached = (unsigned)strtol(bufptr+7, &tail, 10);
  1165. else if (strncmp("SwapCached:", bufptr, 11)==0)
  1166. swapcached = (unsigned)strtol(bufptr+11, &tail, 10);
  1167. else
  1168. i++;
  1169. bufptr = strchr(bufptr, '\n');
  1170. }
  1171. inuse = total-free-cached;
  1172. swapinuse = swaptotal-swapfree-swapcached;
  1173. #endif
  1174. }
  1175. class CInt64fix
  1176. {
  1177. __int64 val;
  1178. public:
  1179. CInt64fix()
  1180. {
  1181. val = 0;
  1182. }
  1183. void set(int v)
  1184. {
  1185. __int64 ret = (unsigned)v;
  1186. while (val-ret>0x80000000LL)
  1187. ret += 0x100000000LL;
  1188. val = ret;
  1189. }
  1190. __int64 get()
  1191. {
  1192. return val;
  1193. }
  1194. };
  1195. void getMemStats(StringBuffer &out, unsigned &memused, unsigned &memtot)
  1196. {
  1197. #ifdef __linux__
  1198. __int64 total = getMapInfo("heap");
  1199. __int64 sbrkmem = getMapInfo("sbrk");
  1200. __int64 mmapmem = total - sbrkmem;
  1201. __int64 virttot = getVMInfo("VmData");
  1202. unsigned mu;
  1203. unsigned ma;
  1204. unsigned mt;
  1205. unsigned st;
  1206. unsigned su;
  1207. getMemUsage(mu,ma,mt,st,su);
  1208. unsigned muval = (unsigned)(((__int64)mu+(__int64)su)*100/((__int64)mt+(__int64)st));
  1209. if (sizeof(memsize_t)==4) {
  1210. unsigned muval2 = (virttot*100)/(3*(__int64)0x40000000);
  1211. if (muval2>muval)
  1212. muval = muval2;
  1213. }
  1214. if (muval>100)
  1215. muval = 100; // !
  1216. out.appendf("MU=%3u%% MAL=%" I64F "d MMP=%" I64F "d SBK=%" I64F "d TOT=%uK RAM=%uK SWP=%uK",
  1217. muval, total, mmapmem, sbrkmem, (unsigned)(virttot/1024), mu, su);
  1218. #ifdef _USE_MALLOC_HOOK
  1219. if (totalMem)
  1220. out.appendf(" TM=%" I64F "d",totalMem);
  1221. #endif
  1222. memused = mu+su;
  1223. memtot = mt+st;
  1224. #elif defined (__APPLE__)
  1225. __uint64 bytes;
  1226. size_t len = sizeof(bytes);
  1227. sysctlbyname("hw.memsize", &bytes, &len, NULL, 0);
  1228. // See http://miknight.blogspot.com/2005/11/resident-set-size-in-mac-os-x.html
  1229. struct task_basic_info t_info;
  1230. mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
  1231. task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
  1232. out.appendf("RES=%" I64F "uMiB VIRT=%" I64F "uMiB TOT=%" I64F "uMiB",
  1233. (__uint64) t_info.resident_size/(1024*1024),
  1234. (__uint64) t_info.virtual_size/(1024*1024),
  1235. bytes/(1024*1024));
  1236. memused = t_info.resident_size;
  1237. memtot = t_info.virtual_size;
  1238. #elif defined (__FreeBSD___)
  1239. UNIMPLEMENTED;
  1240. #endif
  1241. }
  1242. void getDiskUsage(char const * path, unsigned __int64 & total, unsigned __int64 & inUse)
  1243. {
  1244. #if defined(__linux__) || defined(__APPLE__)
  1245. struct statfs stfs;
  1246. if(statfs(path, &stfs) < 0)
  1247. {
  1248. //PrintLog("statfs error for filesystem '%s'", path);
  1249. total = inUse = 0;
  1250. }
  1251. else
  1252. {
  1253. struct stat st;
  1254. if(stat(path, &st) < 0)
  1255. {
  1256. //PrintLog("stat error for filesystem '%s'", path);
  1257. total = inUse = 0;
  1258. }
  1259. else
  1260. {
  1261. total = (unsigned __int64)stfs.f_blocks * st.st_blksize;
  1262. inUse = total - (unsigned __int64)stfs.f_bfree * st.st_blksize;
  1263. }
  1264. }
  1265. #else
  1266. total = inUse = 0;
  1267. #endif
  1268. }
  1269. #endif
  1270. static std::atomic<unsigned> cachedNumCpus;
  1271. unsigned getAffinityCpus()
  1272. {
  1273. if (cachedNumCpus.load(std::memory_order_acquire) == 0)
  1274. cachedNumCpus.store(evalAffinityCpus(), std::memory_order_release);
  1275. return cachedNumCpus.load(std::memory_order_acquire);
  1276. }
  1277. void clearAffinityCache()
  1278. {
  1279. cachedNumCpus.store(0, std::memory_order_release);
  1280. }
  1281. void getPeakMemUsage(memsize_t &peakVm,memsize_t &peakResident)
  1282. {
  1283. peakVm = 0;
  1284. peakResident = 0;
  1285. #ifdef _WIN32
  1286. PROCESS_MEMORY_COUNTERS pmc;
  1287. if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
  1288. {
  1289. peakVm = pmc.PeakWorkingSetSize;
  1290. peakResident = pmc.PeakWorkingSetSize;
  1291. }
  1292. #else
  1293. static int memfd = -1;
  1294. if (memfd==-1)
  1295. memfd = open("/proc/self/status",O_RDONLY);
  1296. if (memfd==-1)
  1297. return;
  1298. char buf[2048];
  1299. size32_t l = pread(memfd, buf, sizeof(buf)-1, 0L);
  1300. if ((int)l<=0)
  1301. return;
  1302. buf[l] = 0;
  1303. const char *bufptr = buf;
  1304. while (bufptr) {
  1305. if (*bufptr =='\n')
  1306. bufptr++;
  1307. if (!matchExtract("VmPeak:", bufptr, peakVm) &&
  1308. !matchExtract("VmHWM:", bufptr, peakResident))
  1309. {
  1310. //ignore this line
  1311. }
  1312. bufptr = strchr(bufptr, '\n');
  1313. }
  1314. #endif
  1315. }
  1316. #define RXMAX 1000000 // can be 10x bigger but this produces reasonable amounts
  1317. unsigned packetsLasttime;
  1318. __int64 packetsLastrx = -1;
  1319. __int64 packetsLasttx;
  1320. bool getPacketStats(unsigned & tx, unsigned & rx)
  1321. {
  1322. unsigned thistime = msTick();
  1323. JSocketStatistics jstats;
  1324. getSocketStatistics(jstats);
  1325. bool ret = true;
  1326. if(packetsLastrx!=-1)
  1327. {
  1328. tx = (unsigned) ((jstats.writesize-packetsLasttx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  1329. rx = (unsigned) ((jstats.readsize-packetsLastrx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  1330. }
  1331. else
  1332. ret = false;
  1333. packetsLastrx = jstats.readsize;
  1334. packetsLasttx = jstats.writesize;
  1335. packetsLasttime = thistime;
  1336. return ret;
  1337. }
  1338. #ifndef _WIN32
  1339. struct UserStatusInfo
  1340. {
  1341. public:
  1342. UserStatusInfo(pid_t _pid)
  1343. {
  1344. pid = _pid;
  1345. }
  1346. bool update()
  1347. {
  1348. StringBuffer fn;
  1349. fn.appendf("/proc/%d/stat", pid);
  1350. char buf[800]; /* about 40 fields, 64-bit decimal is about 20 chars */
  1351. int fd = open(fn.str(), O_RDONLY, 0);
  1352. if (fd==-1)
  1353. return false;
  1354. int rd = read(fd, buf, sizeof(buf)-1);
  1355. close(fd);
  1356. if (rd<80)
  1357. return false;
  1358. buf[rd] = 0;
  1359. char *s = strchr(buf,'(');
  1360. if (!s)
  1361. return false;
  1362. s++;
  1363. unsigned i = 0;
  1364. while (*s&&(*s!=')')&&(i<15))
  1365. cmd[i++] = *(s++);
  1366. if (*s != ')')
  1367. return false;
  1368. cmd[i] = 0;
  1369. s+=3; // Skip ") X" where X is the state
  1370. //The PID of the parent process
  1371. const char *num;
  1372. s = skipnumfld(s,num);
  1373. //int ppid = atoi(num);
  1374. // skip pgrp, session, tty_num, tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt
  1375. for (i=0;i<9;i++)
  1376. s = skipnumfld(s,num);
  1377. //utime - user mode time in clock ticks.
  1378. s = skipnumfld(s,num);
  1379. //printf("**N'%s'\n",num);
  1380. time.user = (unsigned)atoi64_l(num,strlen(num));
  1381. //stime - amount of time scheduled in kernel mode in clock ticks
  1382. s = skipnumfld(s,num);
  1383. //printf("**N'%s'\n",num);
  1384. time.system = (unsigned)atoi64_l(num,strlen(num));
  1385. return true;
  1386. }
  1387. public:
  1388. pid_t pid;
  1389. char cmd[16];
  1390. UserSystemTime_t time;
  1391. private:
  1392. char *skipnumfld(char *s, const char *&num)
  1393. {
  1394. while (*s && isspace(*s))
  1395. s++;
  1396. num = s;
  1397. if ((*s=='-')||(*s=='+'))
  1398. s++;
  1399. while (*s && isdigit(*s))
  1400. s++;
  1401. if (*s==' ')
  1402. *(s++) = 0; // terminate num
  1403. while (*s && isspace(*s))
  1404. s++;
  1405. return s;
  1406. }
  1407. };
  1408. struct CProcInfo: extends CInterface
  1409. {
  1410. UserStatusInfo info;
  1411. UserSystemTime_t delta;
  1412. bool active;
  1413. bool first;
  1414. CProcInfo(int _pid) : info(_pid)
  1415. {
  1416. active = false;
  1417. first = true;
  1418. }
  1419. inline pid_t pid() const { return info.pid; }
  1420. bool load()
  1421. {
  1422. UserSystemTime_t prev = info.time;
  1423. if (!info.update())
  1424. return false;
  1425. active = true;
  1426. if (first)
  1427. first = false;
  1428. else {
  1429. delta.system = info.time.system-prev.system;
  1430. delta.user = info.time.user-prev.user;
  1431. }
  1432. return true;
  1433. }
  1434. };
  1435. class CProcessMonitor
  1436. {
  1437. CIArrayOf<CProcInfo> processes;
  1438. unsigned tot_time;
  1439. bool busy;
  1440. CriticalSection sect;
  1441. static int compare(CInterface * const *i1, CInterface * const *i2)
  1442. {
  1443. CProcInfo *pi1 = QUERYINTERFACE(*i1,CProcInfo);
  1444. CProcInfo *pi2 = QUERYINTERFACE(*i2,CProcInfo);
  1445. return pi2->delta.system+pi2->delta.user-pi1->delta.system-pi1->delta.user;
  1446. }
  1447. public:
  1448. CProcessMonitor()
  1449. {
  1450. busy = false;
  1451. }
  1452. void scan()
  1453. {
  1454. #ifdef __linux__
  1455. ForEachItemIn(i1,processes)
  1456. processes.item(i1).active = false;
  1457. DIR *dir = opendir("/proc");
  1458. for (;;) {
  1459. CriticalBlock b(sect);
  1460. struct dirent *ent = readdir(dir);
  1461. if (!ent)
  1462. break;
  1463. if ((ent->d_name[0]>='0')&&(ent->d_name[0]<='9')) {
  1464. int pid = atoi(ent->d_name);
  1465. if (pid) {
  1466. CProcInfo *pi = NULL;
  1467. ForEachItemIn(i2,processes) {
  1468. if (processes.item(i2).pid() == pid) {
  1469. pi = &processes.item(i2);
  1470. break;
  1471. }
  1472. }
  1473. if (!pi) {
  1474. pi = new CProcInfo(pid);
  1475. processes.append(*pi);
  1476. }
  1477. pi->load();
  1478. }
  1479. }
  1480. }
  1481. closedir(dir);
  1482. tot_time = 0;
  1483. ForEachItemInRev(i3,processes) {
  1484. CProcInfo &pi = processes.item(i3);
  1485. if (pi.active)
  1486. tot_time += pi.delta.system+pi.delta.user;
  1487. else
  1488. processes.remove(i3);
  1489. }
  1490. #endif
  1491. #if defined (__FreeBSD__) || defined (__APPLE__)
  1492. UNIMPLEMENTED;
  1493. #endif
  1494. }
  1495. void print(unsigned n,StringBuffer &str)
  1496. {
  1497. if (!tot_time)
  1498. return;
  1499. assertex(n);
  1500. processes.sort(compare);
  1501. StringBuffer name;
  1502. ForEachItemIn(i1,processes) {
  1503. CProcInfo &pi = processes.item(i1);
  1504. if ((pi.delta.system==0)&&(pi.delta.user==0))
  1505. break;
  1506. getThreadName(pi.pid(),0,name.clear());
  1507. str.appendf("\n TT: PI=%d PN=%s PC=%d ST=%d UT=%d%s%s",
  1508. pi.pid(),pi.info.cmd,(pi.delta.system+pi.delta.user)*100/tot_time,pi.delta.system,pi.delta.user,name.length()?" TN=":"",name.str());
  1509. if (--n==0)
  1510. break;
  1511. }
  1512. }
  1513. void printBusy(unsigned pc,StringBuffer &str)
  1514. {
  1515. if (pc>90) {
  1516. scan();
  1517. if (busy)
  1518. print(3,str); // print top 3
  1519. else
  1520. busy = true;
  1521. }
  1522. else {
  1523. busy = false;
  1524. processes.kill();
  1525. }
  1526. }
  1527. };
  1528. #ifndef HZ
  1529. #define HZ 100
  1530. #endif
  1531. #define IDE0_MAJOR 3
  1532. #define SCSI_DISK0_MAJOR 8
  1533. #define SCSI_DISK1_MAJOR 65
  1534. #define SCSI_DISK7_MAJOR 71
  1535. #define SCSI_DISK10_MAJOR 128
  1536. #define SCSI_DISK17_MAJOR 135
  1537. #define IDE1_MAJOR 22
  1538. #define IDE2_MAJOR 33
  1539. #define IDE3_MAJOR 34
  1540. #define IDE4_MAJOR 56
  1541. #define IDE5_MAJOR 57
  1542. #define IDE6_MAJOR 88
  1543. #define IDE7_MAJOR 89
  1544. #define IDE8_MAJOR 90
  1545. #define IDE9_MAJOR 91
  1546. #define COMPAQ_SMART2_MAJOR 72
  1547. #define IDE_DISK_MAJOR(M) ((M) == IDE0_MAJOR || (M) == IDE1_MAJOR || \
  1548. (M) == IDE2_MAJOR || (M) == IDE3_MAJOR || \
  1549. (M) == IDE4_MAJOR || (M) == IDE5_MAJOR || \
  1550. (M) == IDE6_MAJOR || (M) == IDE7_MAJOR || \
  1551. (M) == IDE8_MAJOR || (M) == IDE9_MAJOR)
  1552. #define SCSI_DISK_MAJOR(M) ((M) == SCSI_DISK0_MAJOR || \
  1553. ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) || \
  1554. ((M) >= SCSI_DISK10_MAJOR && (M) <= SCSI_DISK17_MAJOR))
  1555. #define OTHER_DISK_MAJOR(M) ((M) == COMPAQ_SMART2_MAJOR) // by investigation!
  1556. // nvme disk major is often 259 (blkext) but others are also
  1557. //---------------------------------------------------------------------------
  1558. class OsDiskInfo
  1559. {
  1560. public:
  1561. OsDiskInfo();
  1562. ~OsDiskInfo();
  1563. unsigned getNumPartitions() const { return nparts; }
  1564. unsigned mapPartition(unsigned major, unsigned minor) const;
  1565. const char * queryPartitionName(unsigned p) const { return partition[p].name; }
  1566. protected:
  1567. void gatherPartitions();
  1568. void initMajorMinor();
  1569. bool isDisk(unsigned int major, unsigned int minor) const
  1570. {
  1571. unsigned mm = (major<<16)+minor;
  1572. bool found = diskMajorMinor.contains(mm);
  1573. if (found)
  1574. return true;
  1575. if (IDE_DISK_MAJOR(major))
  1576. return ((minor&0x3F)==0);
  1577. if (SCSI_DISK_MAJOR(major))
  1578. return ((minor&0x0F)==0);
  1579. if (OTHER_DISK_MAJOR(major))
  1580. return ((minor&0x0F)==0);
  1581. return 0;
  1582. }
  1583. private:
  1584. struct part_info
  1585. {
  1586. unsigned int major;
  1587. unsigned int minor;
  1588. char name[32];
  1589. };
  1590. unsigned nparts = 0;
  1591. part_info *partition = nullptr;
  1592. UnsignedArray diskMajorMinor;
  1593. };
  1594. OsDiskInfo::OsDiskInfo()
  1595. {
  1596. initMajorMinor();
  1597. gatherPartitions();
  1598. }
  1599. OsDiskInfo::~OsDiskInfo()
  1600. {
  1601. free(partition);
  1602. }
  1603. void OsDiskInfo::gatherPartitions()
  1604. {
  1605. char ln[256];
  1606. part_info pi;
  1607. FILE* diskfp = fopen("/proc/diskstats", "r");
  1608. if (!diskfp)
  1609. return;
  1610. nparts = 0;
  1611. while (fgets(ln, sizeof(ln), diskfp))
  1612. {
  1613. unsigned reads = 0;
  1614. if (sscanf(ln, "%4d %4d %31s %u", &pi.major, &pi.minor, pi.name, &reads) == 4)
  1615. {
  1616. unsigned p = 0;
  1617. while ((p<nparts) && (partition[p].major != pi.major || partition[p].minor != pi.minor))
  1618. p++;
  1619. if ((p==nparts) && reads && isDisk(pi.major,pi.minor))
  1620. {
  1621. nparts++;
  1622. partition = (part_info *)realloc(partition,nparts*sizeof(part_info));
  1623. partition[p] = pi;
  1624. }
  1625. }
  1626. }
  1627. fclose(diskfp);
  1628. }
  1629. void OsDiskInfo::initMajorMinor()
  1630. {
  1631. #ifdef __linux__
  1632. // MCK - wish libblkid could do this ...
  1633. // Another way might also be to look for:
  1634. // /sys/block/sd*
  1635. // /sys/block/nvme*
  1636. // and match those with entries in /proc/diskstats
  1637. StringBuffer cmd("lsblk -o TYPE,MAJ:MIN --pairs");
  1638. Owned<IPipeProcess> pipe = createPipeProcess();
  1639. if (pipe->run("list disks", cmd, nullptr, false, true, true, 8192))
  1640. {
  1641. StringBuffer output;
  1642. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  1643. readSimpleStream(output, *pipeReader);
  1644. unsigned exitcode = pipe->wait();
  1645. if ( (exitcode == 0) && (output.length() > 0) )
  1646. {
  1647. StringArray lines;
  1648. lines.appendList(output, "\n");
  1649. ForEachItemIn(idx, lines)
  1650. {
  1651. // line: TYPE="disk" MAJ:MIN="259:0"
  1652. unsigned majnum, minnum;
  1653. if (2 == sscanf(lines.item(idx), "TYPE=\"disk\" MAJ:MIN=\"%u:%u\"", &majnum, &minnum))
  1654. {
  1655. unsigned mm = (majnum<<16)+minnum;
  1656. diskMajorMinor.appendUniq(mm);
  1657. }
  1658. }
  1659. }
  1660. else
  1661. {
  1662. StringBuffer outputErr;
  1663. Owned<ISimpleReadStream> pipeReaderErr = pipe->getErrorStream();
  1664. readSimpleStream(outputErr, *pipeReaderErr);
  1665. if (outputErr.length() > 0)
  1666. WARNLOG("WARNING: Pipe: output: %s", outputErr.str());
  1667. }
  1668. }
  1669. #endif // __linux__
  1670. }
  1671. unsigned OsDiskInfo::mapPartition(unsigned major, unsigned minor) const
  1672. {
  1673. for (unsigned p = 0; p < nparts; p++)
  1674. {
  1675. if (partition[p].major == major && partition[p].minor == minor)
  1676. return p;
  1677. }
  1678. return (unsigned)-1;
  1679. }
  1680. static Singleton<OsDiskInfo> globalOsDiskInfo;
  1681. MODULE_INIT(INIT_PRIORITY_JDEBUG2)
  1682. {
  1683. return true;
  1684. }
  1685. MODULE_EXIT()
  1686. {
  1687. delete globalOsDiskInfo.queryExisting();
  1688. }
  1689. const OsDiskInfo & queryGlobalOsDiskInfo()
  1690. {
  1691. return *globalOsDiskInfo.query([] { return new OsDiskInfo; });
  1692. }
  1693. #endif
  1694. //---------------------------------------------------------------------------------------------------------------------
  1695. OsDiskStats::OsDiskStats()
  1696. {
  1697. stats = new BlockIoStats[getNumPartitions()];
  1698. }
  1699. OsDiskStats::OsDiskStats(bool updateNow) : OsDiskStats()
  1700. {
  1701. if (updateNow)
  1702. updateCurrent();
  1703. }
  1704. OsDiskStats::~OsDiskStats()
  1705. {
  1706. delete [] stats;
  1707. }
  1708. unsigned OsDiskStats::getNumPartitions() const
  1709. {
  1710. #ifdef _WIN32
  1711. return 0;
  1712. #else
  1713. return queryGlobalOsDiskInfo().getNumPartitions();
  1714. #endif
  1715. }
  1716. bool OsDiskStats::updateCurrent()
  1717. {
  1718. #ifdef _WIN32
  1719. //MORE: This should be updated (probably using the performance counters api in windows).
  1720. //Revisit if windows ever becomes a supported server platform
  1721. return false;
  1722. #else
  1723. FILE* diskfp = fopen("/proc/diskstats", "r");
  1724. if (!diskfp)
  1725. return false;
  1726. total.clear();
  1727. char ln[256];
  1728. while (fgets(ln, sizeof(ln), diskfp))
  1729. {
  1730. unsigned major, minor;
  1731. BlockIoStats blkio;
  1732. unsigned items = sscanf(ln, "%4d %4d %*s %u %u %llu %u %u %u %llu %u %*u %u %u",
  1733. &major, &minor,
  1734. &blkio.rd_ios, &blkio.rd_merges,
  1735. &blkio.rd_sectors, &blkio.rd_ticks,
  1736. &blkio.wr_ios, &blkio.wr_merges,
  1737. &blkio.wr_sectors, &blkio.wr_ticks,
  1738. &blkio.ticks, &blkio.aveq);
  1739. if (items == 6)
  1740. {
  1741. // hopefully not this branch!
  1742. blkio.rd_sectors = blkio.rd_merges;
  1743. blkio.wr_sectors = blkio.rd_ticks;
  1744. blkio.rd_ios = 0;
  1745. blkio.rd_merges = 0;
  1746. blkio.rd_ticks = 0;
  1747. blkio.wr_ios = 0;
  1748. blkio.wr_merges = 0;
  1749. blkio.wr_ticks = 0;
  1750. blkio.ticks = 0;
  1751. blkio.aveq = 0;
  1752. items = 12;
  1753. }
  1754. if (items == 12)
  1755. {
  1756. unsigned match = queryGlobalOsDiskInfo().mapPartition(major, minor);
  1757. if (match != NotFound)
  1758. {
  1759. stats[match] = blkio;
  1760. total += blkio;
  1761. }
  1762. }
  1763. }
  1764. fclose(diskfp);
  1765. return true;
  1766. #endif
  1767. }
  1768. //---------------------------------------------------------------------------------------------------------------------
  1769. OsNetworkStats::OsNetworkStats(const char * ifname)
  1770. {
  1771. updateCurrent(ifname);
  1772. }
  1773. OsNetworkStats OsNetworkStats::operator - (const OsNetworkStats & other) const
  1774. {
  1775. OsNetworkStats result;
  1776. result.rxbytes = rxbytes - other.rxbytes;
  1777. result.rxpackets = rxpackets - other.rxpackets;
  1778. result.rxerrors = rxerrors - other.rxerrors;
  1779. result.rxdrops = rxdrops - other.rxdrops;
  1780. result.txbytes = txbytes - other.txbytes;
  1781. result.txpackets = txpackets - other.txpackets;
  1782. result.txerrors = txerrors - other.txerrors;
  1783. result.txdrops = txdrops - other.txdrops;
  1784. return result;
  1785. }
  1786. bool OsNetworkStats::updateCurrent(const char * ifname)
  1787. {
  1788. #ifdef _WIN32
  1789. //MORE: Implement on windows when we have a requirement
  1790. return false;
  1791. #else
  1792. FILE *netfp = fopen("/proc/net/dev", "r");
  1793. if (!netfp)
  1794. return false;
  1795. char ln[512];
  1796. // Read two lines
  1797. if (!fgets(ln, sizeof(ln), netfp) || !fgets(ln, sizeof(ln), netfp)) {
  1798. fclose(netfp);
  1799. return false;
  1800. }
  1801. unsigned txskip = 2;
  1802. bool hasbyt = false;
  1803. if (strstr(ln,"compressed")) {
  1804. txskip = 4;
  1805. hasbyt = true;
  1806. }
  1807. else if (strstr(ln,"bytes"))
  1808. hasbyt = true;
  1809. size_t ilen = ifname ? strlen(ifname) : 0;
  1810. while (fgets(ln, sizeof(ln), netfp)) {
  1811. const char *s = ln;
  1812. skipSp(s);
  1813. const char * next = nullptr;
  1814. if (!ifname)
  1815. {
  1816. const char * colon = strchr(s, ':');
  1817. if (colon)
  1818. next = colon + 1;
  1819. }
  1820. else
  1821. {
  1822. if ((strncmp(s, ifname, ilen)==0) && (s[ilen]==':'))
  1823. next = s + ilen + 1;
  1824. }
  1825. if (next)
  1826. {
  1827. s = next;
  1828. skipSp(s);
  1829. if (hasbyt) {
  1830. rxbytes = readDecNum(s);
  1831. skipSp(s);
  1832. }
  1833. else
  1834. rxbytes = 0;
  1835. rxpackets = readDecNum(s);
  1836. skipSp(s);
  1837. rxerrors = readDecNum(s);
  1838. skipSp(s);
  1839. rxdrops = readDecNum(s);
  1840. skipSp(s);
  1841. while (txskip--) {
  1842. readDecNum(s);
  1843. skipSp(s);
  1844. }
  1845. if (hasbyt) {
  1846. txbytes = readDecNum(s);
  1847. skipSp(s);
  1848. }
  1849. else
  1850. txbytes = 0;
  1851. txpackets = readDecNum(s);
  1852. skipSp(s);
  1853. txerrors = readDecNum(s);
  1854. skipSp(s);
  1855. txdrops = readDecNum(s);
  1856. if (ifname)
  1857. break;
  1858. }
  1859. }
  1860. fclose(netfp);
  1861. return true;
  1862. #endif
  1863. }
  1864. //---------------------------------------------------------------------------------------------------------------------
  1865. #ifndef _WIN32
  1866. //---------------------------------------------------------------------------
  1867. class CExtendedStats // Disk network and cpu stats
  1868. {
  1869. unsigned nparts;
  1870. OsDiskStats *newDiskStats;
  1871. OsDiskStats *oldDiskStats;
  1872. CpuInfo newcpu;
  1873. unsigned numcpu;
  1874. CpuInfo oldcpu;
  1875. CpuInfo cpu;
  1876. OsNetworkStats oldnet;
  1877. OsNetworkStats newnet;
  1878. unsigned ncpu;
  1879. bool first;
  1880. char *kbuf;
  1881. size32_t kbufmax;
  1882. int kbadcnt;
  1883. unsigned short kbufcrc;
  1884. __uint64 totalcpu;
  1885. unsigned ndisks;
  1886. StringBuffer ifname;
  1887. bool getNextCPU()
  1888. {
  1889. if (!ncpu) {
  1890. unsigned speed;
  1891. getCpuInfo(ncpu, speed);
  1892. if (!ncpu)
  1893. ncpu = 1;
  1894. }
  1895. oldcpu = newcpu;
  1896. if (newcpu.getSystemTimes())
  1897. {
  1898. cpu = newcpu - oldcpu;
  1899. totalcpu = cpu.getTotal();
  1900. return true;
  1901. }
  1902. else
  1903. {
  1904. cpu.clear();
  1905. totalcpu = 0;
  1906. return false;
  1907. }
  1908. }
  1909. bool getDiskInfo()
  1910. {
  1911. if (!newDiskStats)
  1912. {
  1913. newDiskStats = new OsDiskStats;
  1914. oldDiskStats = new OsDiskStats;
  1915. }
  1916. return newDiskStats->updateCurrent();
  1917. }
  1918. bool getNetInfo()
  1919. {
  1920. return newnet.updateCurrent(ifname);
  1921. }
  1922. size32_t getKLog(const char *&data)
  1923. {
  1924. #ifdef __linux__
  1925. if (kbufmax)
  1926. {
  1927. data = nullptr;
  1928. size32_t ksz = 0;
  1929. unsigned short lastCRC = 0;
  1930. // NOTE: allocated 2*kbufmax to work around kernel bug
  1931. // where klogctl() could sometimes return more than requested
  1932. size32_t sz = klogctl(3, kbuf, kbufmax);
  1933. if ((int)sz < 0)
  1934. {
  1935. if (kbadcnt < 5)
  1936. {
  1937. ERRLOG("klogctl SYSLOG_ACTION_READ_ALL error %d", errno);
  1938. kbadcnt++;
  1939. }
  1940. else
  1941. kbufmax = 0;
  1942. return 0;
  1943. }
  1944. #if 0
  1945. kbuf[sz] = '\0';
  1946. #endif
  1947. if (kbufcrc)
  1948. {
  1949. data = kbuf;
  1950. ksz = sz;
  1951. }
  1952. // determine where new info starts ...
  1953. StringBuffer ln;
  1954. const char *p = kbuf;
  1955. const char *e = p+sz;
  1956. while (p && p!=e)
  1957. {
  1958. if (*p=='<')
  1959. {
  1960. ln.clear();
  1961. while ((p && p!=e)&&(*p!='\n'))
  1962. {
  1963. ln.append(*p);
  1964. p++;
  1965. sz--;
  1966. }
  1967. lastCRC = chksum16(ln.str(), ln.length());
  1968. if (kbufcrc && kbufcrc == lastCRC)
  1969. {
  1970. ksz = sz - 1;
  1971. if (ksz && sz)
  1972. data = p + 1;
  1973. else
  1974. data = nullptr;
  1975. }
  1976. }
  1977. while ((p && p!=e)&&(*p!='\n'))
  1978. {
  1979. p++;
  1980. sz--;
  1981. }
  1982. if (p && p!=e)
  1983. {
  1984. p++;
  1985. sz--;
  1986. }
  1987. }
  1988. if (lastCRC)
  1989. kbufcrc = lastCRC;
  1990. if (!ksz)
  1991. data = nullptr;
  1992. return ksz;
  1993. }
  1994. #endif
  1995. data = nullptr;
  1996. return 0;
  1997. }
  1998. inline double perSec(double v,double deltams)
  1999. {
  2000. return 1000.0*v/deltams;
  2001. }
  2002. public:
  2003. unsigned getCPU()
  2004. {
  2005. if (!getNextCPU())
  2006. return (unsigned)-1;
  2007. return cpu.getPercentCpu();
  2008. }
  2009. CExtendedStats(bool printklog)
  2010. {
  2011. nparts = queryGlobalOsDiskInfo().getNumPartitions();
  2012. newDiskStats = NULL;
  2013. oldDiskStats = NULL;
  2014. first = true;
  2015. ncpu = 0;
  2016. kbuf = nullptr;
  2017. kbufcrc = 0;
  2018. totalcpu = 0;
  2019. numcpu = 0;
  2020. ndisks = 0;
  2021. kbadcnt = 0;
  2022. if (printklog)
  2023. {
  2024. kbufmax = 0x1000;
  2025. kbuf = (char *)malloc(kbufmax*2);
  2026. if (!kbuf)
  2027. kbufmax = 0;
  2028. }
  2029. else
  2030. kbufmax = 0;
  2031. if (!getInterfaceName(ifname))
  2032. ifname.set("eth0");
  2033. }
  2034. ~CExtendedStats()
  2035. {
  2036. free(newDiskStats);
  2037. free(oldDiskStats);
  2038. if (kbuf != nullptr)
  2039. free(kbuf);
  2040. }
  2041. bool getLine(StringBuffer &out)
  2042. {
  2043. std::swap(oldDiskStats, newDiskStats);
  2044. oldnet = newnet;
  2045. bool gotdisk = getDiskInfo()&&nparts;
  2046. bool gotnet = getNetInfo();
  2047. if (first)
  2048. {
  2049. first = false;
  2050. return false;
  2051. }
  2052. double deltams = ((double)totalcpu*1000) / ncpu / HZ;
  2053. if (deltams<10)
  2054. return false;
  2055. if (gotdisk)
  2056. {
  2057. if (out.length()&&(out.charAt(out.length()-1)!=' '))
  2058. out.append(' ');
  2059. out.append("DSK: ");
  2060. for (unsigned p = 0; p < nparts; p++)
  2061. {
  2062. const BlockIoStats & oldStats = oldDiskStats->queryStats(p);
  2063. const BlockIoStats & newStats = newDiskStats->queryStats(p);
  2064. BlockIoStats diff = newStats - oldStats;
  2065. unsigned busy = (unsigned)(100*diff.ticks/deltams);
  2066. if (busy>100)
  2067. busy = 100;
  2068. out.appendf("[%s] r/s=%0.1f kr/s=%0.1f w/s=%0.1f kw/s=%0.1f bsy=%d",
  2069. queryGlobalOsDiskInfo().queryPartitionName(p),
  2070. perSec(diff.rd_ios,deltams),
  2071. perSec(diff.rd_sectors,deltams)/2.0,
  2072. perSec(diff.wr_ios,deltams),
  2073. perSec(diff.wr_sectors,deltams)/2.0,
  2074. busy);
  2075. out.append(' ');
  2076. }
  2077. }
  2078. if (gotnet)
  2079. {
  2080. if (out.length()&&(out.charAt(out.length()-1)!=' '))
  2081. out.append(' ');
  2082. out.appendf("NIC: [%s] ", ifname.str());
  2083. OsNetworkStats diff = newnet - oldnet;
  2084. out.appendf("rxp/s=%0.1f rxk/s=%0.1f txp/s=%0.1f txk/s=%0.1f rxerrs=%" I64F "d rxdrps=%" I64F "d txerrs=%" I64F "d txdrps=%" I64F "d",
  2085. perSec(diff.rxpackets,deltams),
  2086. perSec(diff.rxbytes/1024.0,deltams),
  2087. perSec(diff.txpackets,deltams),
  2088. perSec(diff.txbytes/1024.0,deltams),
  2089. diff.rxerrors, diff.rxdrops, diff.txerrors, diff.txdrops);
  2090. out.append(' ');
  2091. }
  2092. if (totalcpu)
  2093. {
  2094. if (out.length()&&(out.charAt(out.length()-1)!=' '))
  2095. out.append(' ');
  2096. out.appendf("CPU: usr=%d sys=%d iow=%d idle=%d", cpu.getUserPercent(), cpu.getSystemPercent(), cpu.getIoWaitPercent(), cpu.getIdlePercent());
  2097. }
  2098. return true;
  2099. }
  2100. #define KERN_EMERG "<0>" // system is unusable
  2101. #define KERN_ALERT "<1>" // action must be taken immediately
  2102. #define KERN_CRIT "<2>" // critical conditions
  2103. #define KERN_ERR "<3>" // error conditions
  2104. #define KERN_WARNING "<4>" // warning conditions
  2105. #define KERN_NOTICE "<5>" // normal but significant condition
  2106. #define KERN_INFO "<6>" // informational
  2107. #define KERN_DEBUG "<7>" // debug-level messages
  2108. #define KMSGTEST(S) if (memcmp(p,S,3)==0) { ln.append(#S); level = p[1]-'0'; }
  2109. void printKLog(IPerfMonHook *hook)
  2110. {
  2111. const char *p = nullptr;
  2112. size32_t sz = getKLog(p);
  2113. #if 0
  2114. DBGLOG("getKLog() returns: %u <%s>", sz, p);
  2115. #endif
  2116. StringBuffer ln;
  2117. const char *e = p+sz;
  2118. while (p && (p!=e)) {
  2119. if (*p=='<') {
  2120. ln.clear();
  2121. int level = -1;
  2122. KMSGTEST(KERN_EMERG)
  2123. else KMSGTEST(KERN_ALERT)
  2124. else KMSGTEST(KERN_CRIT)
  2125. else KMSGTEST(KERN_ERR)
  2126. else KMSGTEST(KERN_WARNING)
  2127. else KMSGTEST(KERN_NOTICE)
  2128. else KMSGTEST(KERN_INFO)
  2129. else KMSGTEST(KERN_DEBUG)
  2130. else {
  2131. ln.append("KERN_UNKNOWN");
  2132. p -= 3;
  2133. }
  2134. p += 3;
  2135. ln.append(": ");
  2136. while ((p && p!=e)&&(*p!='\n'))
  2137. ln.append(*(p++));
  2138. if (hook)
  2139. hook->log(level, ln.str());
  2140. else
  2141. PROGLOG("%s",ln.str());
  2142. }
  2143. while ((p && p!=e)&&(*p!='\n'))
  2144. p++;
  2145. if (p && p!=e)
  2146. p++;
  2147. }
  2148. }
  2149. };
  2150. #endif
  2151. struct PortStats
  2152. {
  2153. unsigned port;
  2154. unsigned drops;
  2155. unsigned rx_queue;
  2156. };
  2157. typedef MapBetween<unsigned, unsigned, PortStats, PortStats> MapPortToPortStats;
  2158. class CUdpStatsReporter
  2159. {
  2160. public:
  2161. CUdpStatsReporter()
  2162. {
  2163. dropsCol = -1;
  2164. portCol = -1;
  2165. uidCol = -1;
  2166. queueCol = -1;
  2167. }
  2168. bool reportUdpInfo(unsigned traceLevel)
  2169. {
  2170. #ifdef _WIN32
  2171. return false;
  2172. #else
  2173. if (uidCol==-1 && columnNames.length())
  2174. return false;
  2175. FILE *netfp = fopen("/proc/net/udp", "r");
  2176. if (!netfp)
  2177. return false;
  2178. char ln[512];
  2179. // Read header
  2180. if (!fgets(ln, sizeof(ln), netfp)) {
  2181. fclose(netfp);
  2182. return false;
  2183. }
  2184. if (!columnNames.length())
  2185. {
  2186. columnNames.appendList(ln, " ");
  2187. ForEachItemInRev(idx, columnNames)
  2188. {
  2189. if (streq(columnNames.item(idx), "rem_address"))
  2190. columnNames.add("rem_port", idx+1);
  2191. else if (streq(columnNames.item(idx), "local_address"))
  2192. columnNames.add("local_port", idx+1);
  2193. }
  2194. ForEachItemIn(idx2, columnNames)
  2195. {
  2196. if (streq(columnNames.item(idx2), "drops"))
  2197. dropsCol = idx2;
  2198. else if (streq(columnNames.item(idx2), "local_port"))
  2199. portCol = idx2;
  2200. else if (streq(columnNames.item(idx2), "rx_queue"))
  2201. queueCol = idx2;
  2202. else if (streq(columnNames.item(idx2), "uid"))
  2203. uidCol = idx2;
  2204. }
  2205. if (portCol == -1 || queueCol == -1 || uidCol == -1)
  2206. {
  2207. uidCol = -1;
  2208. fclose(netfp);
  2209. return false;
  2210. }
  2211. }
  2212. int myUid = geteuid();
  2213. while (fgets(ln, sizeof(ln), netfp))
  2214. {
  2215. StringArray cols;
  2216. cols.appendList(ln, " :");
  2217. if (cols.length() >= columnNames.length() && atoi(cols.item(uidCol))==myUid)
  2218. {
  2219. unsigned queue = strtoul(cols.item(queueCol), NULL, 16);
  2220. unsigned drops = 0;
  2221. if (dropsCol >= 0)
  2222. drops = strtoul(cols.item(dropsCol), NULL, 10);
  2223. if (queue || drops)
  2224. {
  2225. unsigned port = strtoul(cols.item(portCol), NULL, 16);
  2226. if (traceLevel > 0)
  2227. DBGLOG("From /proc/net/udp: port %d rx_queue=%u drops=%u", port, queue, drops);
  2228. PortStats *ret = map.getValue(port);
  2229. if (!ret)
  2230. {
  2231. PortStats e = {port, 0, 0};
  2232. map.setValue(port, e);
  2233. ret = map.getValue(port);
  2234. assertex(ret);
  2235. }
  2236. if (queue > ret->rx_queue)
  2237. {
  2238. DBGLOG("UDP queue: new max rx_queue: port %d rx_queue=%u drops=%u", port, queue, drops);
  2239. ret->rx_queue = queue;
  2240. }
  2241. if (drops > ret->drops)
  2242. {
  2243. LOG(MCoperatorError, unknownJob, "DROPPED UDP PACKETS: port %d rx_queue=%u (peak %u) drops=%u (total %i)", port, queue, ret->rx_queue, drops-ret->drops, drops);
  2244. ret->drops = drops;
  2245. }
  2246. }
  2247. }
  2248. }
  2249. fclose(netfp);
  2250. return true;
  2251. #endif
  2252. }
  2253. private:
  2254. MapPortToPortStats map;
  2255. StringArray columnNames;
  2256. int dropsCol;
  2257. int portCol;
  2258. int uidCol;
  2259. int queueCol;
  2260. };
  2261. class CSnmpStatsReporter
  2262. {
  2263. public:
  2264. CSnmpStatsReporter()
  2265. {
  2266. inErrorsCol = -1;
  2267. prevErrors = 0;
  2268. firstCall = true;
  2269. }
  2270. bool reportSnmpInfo()
  2271. {
  2272. #ifdef _WIN32
  2273. return false;
  2274. #else
  2275. if (inErrorsCol==-1 && columnNames.length())
  2276. return false;
  2277. FILE *netfp = fopen("/proc/net/snmp", "r");
  2278. if (!netfp)
  2279. return false;
  2280. char ln[512];
  2281. bool ok = false;
  2282. while (fgets(ln, sizeof(ln), netfp))
  2283. {
  2284. if (strncmp(ln, "Udp:", 4)==0)
  2285. {
  2286. if (!columnNames.length())
  2287. {
  2288. columnNames.appendList(ln, " ");
  2289. ForEachItemIn(idx, columnNames)
  2290. {
  2291. if (streq(columnNames.item(idx), "InErrors"))
  2292. inErrorsCol = idx;
  2293. }
  2294. if (inErrorsCol == -1)
  2295. break;
  2296. }
  2297. if (fgets(ln, sizeof(ln), netfp))
  2298. {
  2299. StringArray cols;
  2300. cols.appendList(ln, " ");
  2301. if (cols.length() >= columnNames.length())
  2302. {
  2303. ok = true;
  2304. unsigned errors = strtoul(cols.item(inErrorsCol), NULL, 10);
  2305. if (firstCall)
  2306. {
  2307. firstCall = false;
  2308. if (errors)
  2309. LOG(MCoperatorWarning, unknownJob, "UDP Initial InError total: %u", errors);
  2310. }
  2311. else if (errors > prevErrors)
  2312. LOG(MCoperatorError, unknownJob, "UDP InErrors: %u (total %u)", errors-prevErrors, errors);
  2313. prevErrors = errors;
  2314. }
  2315. }
  2316. break;
  2317. }
  2318. }
  2319. fclose(netfp);
  2320. return ok;
  2321. #endif
  2322. }
  2323. private:
  2324. StringArray columnNames;
  2325. int inErrorsCol;
  2326. unsigned prevErrors;
  2327. bool firstCall;
  2328. };
  2329. static class CMemoryUsageReporter: public Thread
  2330. {
  2331. bool term;
  2332. unsigned interval;
  2333. Semaphore sem;
  2334. PerfMonMode traceMode;
  2335. Linked<IPerfMonHook> hook;
  2336. unsigned latestCPU;
  2337. #ifdef _WIN32
  2338. LONG status;
  2339. CpuInfo prevTime;
  2340. CpuInfo deltaTime;
  2341. #else
  2342. CProcessMonitor procmon;
  2343. CExtendedStats extstats;
  2344. #endif
  2345. StringBuffer primaryfs;
  2346. StringBuffer secondaryfs;
  2347. CriticalSection sect; // for getSystemTraceInfo
  2348. CSnmpStatsReporter snmpStats;
  2349. CUdpStatsReporter udpStats;
  2350. public:
  2351. CMemoryUsageReporter(unsigned _interval, PerfMonMode _traceMode, IPerfMonHook * _hook, bool printklog)
  2352. : Thread("CMemoryUsageReporter"), traceMode(_traceMode)
  2353. #ifndef _WIN32
  2354. , extstats(printklog)
  2355. #endif
  2356. {
  2357. interval = _interval;
  2358. hook.set(_hook);
  2359. term = false;
  2360. latestCPU = 0;
  2361. // UDP stats reported unless explicitly disabled
  2362. if (queryEnvironmentConf().getPropBool("udp_stats", true))
  2363. traceMode |= PerfMonUDP;
  2364. #ifdef _WIN32
  2365. primaryfs.append("C:");
  2366. #else
  2367. primaryfs.append("/");
  2368. #endif
  2369. }
  2370. void setPrimaryFileSystem(char const * _primaryfs)
  2371. {
  2372. CriticalBlock block(sect);
  2373. primaryfs.clear();
  2374. if(_primaryfs)
  2375. primaryfs.append(_primaryfs);
  2376. }
  2377. void setSecondaryFileSystem(char const * _secondaryfs)
  2378. {
  2379. CriticalBlock block(sect);
  2380. secondaryfs.clear();
  2381. if(_secondaryfs)
  2382. secondaryfs.append(_secondaryfs);
  2383. }
  2384. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  2385. {
  2386. CriticalBlock block(sect);
  2387. #ifdef _WIN32
  2388. CpuInfo current;
  2389. current.getSystemTimes();
  2390. if (prevTime.getTotal())
  2391. {
  2392. deltaTime = current - prevTime;
  2393. latestCPU = 100 - deltaTime.getIdlePercent();
  2394. }
  2395. prevTime = current;
  2396. MEMORYSTATUSEX memstatus;
  2397. memstatus.dwLength = sizeof(memstatus);
  2398. GlobalMemoryStatusEx(&memstatus);
  2399. DWORDLONG vmTotal = memstatus.ullTotalVirtual;
  2400. DWORDLONG vmAvail = memstatus.ullAvailVirtual;
  2401. DWORDLONG vmInUse = vmTotal - vmAvail;
  2402. DWORDLONG physTotal = memstatus.ullAvailPhys;
  2403. DWORDLONG physAvail = memstatus.ullTotalPhys;
  2404. DWORDLONG physInUse = physTotal - physAvail;
  2405. ULARGE_INTEGER diskAvailStruct;
  2406. ULARGE_INTEGER diskTotalStruct;
  2407. unsigned __int64 firstDriveTotal = 0;
  2408. unsigned __int64 firstDriveInUse = 0;
  2409. unsigned __int64 secondDriveTotal = 0;
  2410. unsigned __int64 secondDriveInUse = 0;
  2411. if(primaryfs.length())
  2412. {
  2413. diskAvailStruct.QuadPart = 0;
  2414. diskTotalStruct.QuadPart = 0;
  2415. GetDiskFreeSpaceEx(primaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  2416. firstDriveTotal = diskTotalStruct.QuadPart;
  2417. firstDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  2418. }
  2419. if(secondaryfs.length())
  2420. {
  2421. diskAvailStruct.QuadPart = 0;
  2422. diskTotalStruct.QuadPart = 0;
  2423. GetDiskFreeSpaceEx(secondaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  2424. secondDriveTotal = diskTotalStruct.QuadPart;
  2425. secondDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  2426. }
  2427. if(hook)
  2428. hook->processPerfStats(latestCPU, (unsigned)(vmInUse/1024), (unsigned)(vmTotal/1024), firstDriveInUse, firstDriveTotal, secondDriveInUse, secondDriveTotal, getThreadCount());
  2429. if(!mode)
  2430. return;
  2431. if(mode & PerfMonProcMem)
  2432. {
  2433. str.appendf("PU=%3d%%",latestCPU);
  2434. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmInUse*100/(__int64)vmTotal));
  2435. str.appendf(" PY=%3u%%",(unsigned)((__int64)physInUse*100/(__int64)physTotal));
  2436. if (hook)
  2437. hook->extraLogging(str);
  2438. #ifdef _USE_MALLOC_HOOK
  2439. if (totalMem)
  2440. str.appendf(" TM=%" I64F "d",totalMem);
  2441. #endif
  2442. }
  2443. if(mode & PerfMonPackets)
  2444. {
  2445. unsigned tx, rx;
  2446. if(getPacketStats(tx, rx))
  2447. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  2448. else
  2449. str.appendf(" ");
  2450. }
  2451. if(mode & PerfMonDiskUsage)
  2452. {
  2453. if(firstDriveTotal) str.appendf(" D1=%3u%%", (unsigned)(firstDriveInUse*100/firstDriveTotal));
  2454. if(secondDriveTotal) str.appendf(" D2=%3u%%", (unsigned)(secondDriveInUse*100/secondDriveTotal));
  2455. }
  2456. if(mode & PerfMonExtended)
  2457. {
  2458. __IO_COUNTERS ioc;
  2459. KERNEL_USER_TIMES kut;
  2460. POOLED_USAGE_AND_LIMITS put;
  2461. VM_COUNTERS vmc;
  2462. DWORD dwSize;
  2463. DWORD dwHandles;
  2464. dwSize = 0;
  2465. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  2466. dwHandles = 0;
  2467. dwSize = 0;
  2468. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessHandleCount, &dwHandles, sizeof(dwHandles), &dwSize);
  2469. dwSize = 0;
  2470. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessIoCounters, &ioc, sizeof(ioc), &dwSize);
  2471. dwSize = 0;
  2472. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessTimes, &kut, sizeof(kut), &dwSize);
  2473. dwSize = 0;
  2474. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessPooledUsageAndLimits, &put, sizeof(put), &dwSize);
  2475. str.appendf(" WS=%10u ",vmc.WorkingSetSize);
  2476. str.appendf("PP=%10u ",put.PagedPoolUsage);
  2477. str.appendf("NP=%10u ",put.NonPagedPoolUsage);
  2478. str.appendf("HC=%5u ",dwHandles);
  2479. str.appendf("TC=%5u ",getThreadCount());
  2480. str.appendf("IR=%10u ",(unsigned)(ioc.ReadTransferCount/1024));
  2481. str.appendf("IW=%10u ",(unsigned)(ioc.WriteTransferCount/1024));
  2482. str.appendf("IO=%10u ",(unsigned)(ioc.OtherTransferCount/1024));
  2483. str.appendf("KT=%16" I64F "u ",kut.KernelTime);
  2484. str.appendf("UT=%16" I64F "u ",kut.UserTime);
  2485. }
  2486. #else
  2487. bool outofhandles = false;
  2488. latestCPU = extstats.getCPU();
  2489. if (latestCPU==(unsigned)-1) {
  2490. outofhandles = true;
  2491. latestCPU = 0;
  2492. }
  2493. unsigned __int64 primaryfsTotal = 0;
  2494. unsigned __int64 primaryfsInUse = 0;
  2495. unsigned __int64 secondaryfsTotal = 0;
  2496. unsigned __int64 secondaryfsInUse = 0;
  2497. if(primaryfs.length())
  2498. getDiskUsage(primaryfs.str(), primaryfsTotal, primaryfsInUse);
  2499. if(secondaryfs.length())
  2500. getDiskUsage(secondaryfs.str(), secondaryfsTotal, secondaryfsInUse);
  2501. if(!mode) return;
  2502. unsigned memused=0;
  2503. unsigned memtot=0;
  2504. str.appendf("LPT=%u ", queryNumLocalTrees());
  2505. str.appendf("APT=%u ", queryNumAtomTrees());
  2506. if(mode & PerfMonProcMem)
  2507. {
  2508. if (!outofhandles)
  2509. str.appendf("PU=%3d%% ", latestCPU);
  2510. else
  2511. str.appendf("PU=OOH ");
  2512. getMemStats(str,memused,memtot);
  2513. if (hook)
  2514. hook->extraLogging(str);
  2515. procmon.printBusy(latestCPU,str);
  2516. }
  2517. if (hook) {
  2518. if (!memtot) {
  2519. unsigned mu;
  2520. unsigned ma;
  2521. unsigned mt;
  2522. unsigned st;
  2523. unsigned su;
  2524. getMemUsage(mu,ma,mt,st,su);
  2525. memused = mu+su;
  2526. memtot = mt+st;
  2527. }
  2528. hook->processPerfStats(latestCPU, memused, memtot, primaryfsInUse, primaryfsTotal, secondaryfsInUse, secondaryfsTotal, getThreadCount());
  2529. }
  2530. if(mode & PerfMonPackets)
  2531. {
  2532. unsigned tx, rx;
  2533. if(getPacketStats(tx, rx))
  2534. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  2535. else
  2536. str.appendf(" ");
  2537. }
  2538. if(mode & PerfMonDiskUsage)
  2539. {
  2540. if(primaryfsTotal) str.appendf(" D1=%3u%%", (unsigned)(primaryfsInUse*100/primaryfsTotal));
  2541. if(secondaryfsTotal) str.appendf(" D2=%3u%%", (unsigned)(secondaryfsInUse*100/secondaryfsTotal));
  2542. }
  2543. if(mode & PerfMonExtended)
  2544. {
  2545. extstats.getLine(str);
  2546. }
  2547. #endif
  2548. }
  2549. #define NAMEDCOUNTPERIOD 60*30
  2550. int run()
  2551. {
  2552. StringBuffer str;
  2553. getSystemTraceInfo(str, traceMode&~PerfMonExtended); // initializes the values so that first one we print is meaningful rather than always saying PU=0%
  2554. if (traceMode&PerfMonUDP)
  2555. {
  2556. snmpStats.reportSnmpInfo();
  2557. udpStats.reportUdpInfo(0);
  2558. }
  2559. CTimeMon tm(NAMEDCOUNTPERIOD*1000);
  2560. while (!term) {
  2561. if (sem.wait(interval))
  2562. break;
  2563. str.clear();
  2564. getSystemTraceInfo(str, traceMode&~PerfMonExtended);
  2565. #ifdef NAMEDCOUNTS
  2566. if (tm.timedout())
  2567. {
  2568. dumpNamedCounts(str.newline());
  2569. tm.reset(NAMEDCOUNTPERIOD*1000);
  2570. }
  2571. #endif
  2572. if (traceMode&PerfMonUDP)
  2573. {
  2574. snmpStats.reportSnmpInfo();
  2575. udpStats.reportUdpInfo(0);
  2576. }
  2577. if(traceMode&&str.length()) {
  2578. LOG(MCdebugInfo, unknownJob, "SYS: %s", str.str());
  2579. #ifndef _WIN32
  2580. if (traceMode&PerfMonExtended) {
  2581. if (extstats.getLine(str.clear()))
  2582. LOG(MCdebugInfo, unknownJob, "%s", str.str());
  2583. {
  2584. CriticalBlock block(sect);
  2585. extstats.printKLog(hook);
  2586. }
  2587. }
  2588. #endif
  2589. }
  2590. }
  2591. return 0;
  2592. }
  2593. void stop()
  2594. {
  2595. term = true;
  2596. sem.signal();
  2597. join();
  2598. }
  2599. unsigned queryLatestCPU() const
  2600. {
  2601. return latestCPU;
  2602. }
  2603. void setHook(IPerfMonHook *_hook)
  2604. {
  2605. CriticalBlock block(sect);
  2606. hook.set(_hook);
  2607. }
  2608. } *MemoryUsageReporter=NULL;
  2609. #ifdef _WIN32
  2610. static inline unsigned scaleFileTimeToMilli(unsigned __int64 nano100)
  2611. {
  2612. return (unsigned)(nano100 / 10000);
  2613. }
  2614. void getProcessTime(UserSystemTime_t & result)
  2615. {
  2616. LARGE_INTEGER startTime, exitTime, kernelTime, userTime;
  2617. if (GetProcessTimes(GetCurrentProcess(), (FILETIME *)&startTime, (FILETIME *)&exitTime, (FILETIME *)&kernelTime, (FILETIME *)&userTime))
  2618. {
  2619. result.user = scaleFileTimeToMilli(userTime.QuadPart);
  2620. result.system = scaleFileTimeToMilli(kernelTime.QuadPart);
  2621. }
  2622. }
  2623. #else
  2624. void getProcessTime(UserSystemTime_t & result)
  2625. {
  2626. UserStatusInfo info(GetCurrentProcessId());
  2627. if (info.update())
  2628. result = info.time;
  2629. }
  2630. #endif
  2631. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  2632. {
  2633. if (!MemoryUsageReporter)
  2634. MemoryUsageReporter = new CMemoryUsageReporter(1000, mode, 0, false);
  2635. MemoryUsageReporter->getSystemTraceInfo(str, mode);
  2636. }
  2637. void startPerformanceMonitor(unsigned interval, PerfMonMode traceMode, IPerfMonHook * hook)
  2638. {
  2639. stopPerformanceMonitor();
  2640. if (!MemoryUsageReporter) {
  2641. MemoryUsageReporter = new CMemoryUsageReporter(interval, traceMode, hook, (traceMode&PerfMonExtended)!=0);
  2642. MemoryUsageReporter->start();
  2643. }
  2644. }
  2645. void stopPerformanceMonitor()
  2646. {
  2647. if (MemoryUsageReporter) {
  2648. MemoryUsageReporter->stop();
  2649. delete MemoryUsageReporter;
  2650. MemoryUsageReporter = NULL;
  2651. }
  2652. }
  2653. void setPerformanceMonitorHook(IPerfMonHook *hook)
  2654. {
  2655. if (MemoryUsageReporter)
  2656. MemoryUsageReporter->setHook(hook);
  2657. }
  2658. void setPerformanceMonitorPrimaryFileSystem(char const * fs)
  2659. {
  2660. if(MemoryUsageReporter)
  2661. MemoryUsageReporter->setPrimaryFileSystem(fs);
  2662. }
  2663. void setPerformanceMonitorSecondaryFileSystem(char const * fs)
  2664. {
  2665. if(MemoryUsageReporter)
  2666. MemoryUsageReporter->setSecondaryFileSystem(fs);
  2667. }
  2668. unsigned getLatestCPUUsage()
  2669. {
  2670. if (MemoryUsageReporter)
  2671. return MemoryUsageReporter->queryLatestCPU();
  2672. else
  2673. return 0;
  2674. }
  2675. void getHardwareInfo(HardwareInfo &hdwInfo, const char *primDiskPath, const char *secDiskPath)
  2676. {
  2677. memset(&hdwInfo, 0, sizeof(HardwareInfo));
  2678. getCpuInfo(hdwInfo.numCPUs, hdwInfo.CPUSpeed);
  2679. #ifdef _WIN32
  2680. MEMORYSTATUS memstatus;
  2681. GlobalMemoryStatus(&memstatus);
  2682. hdwInfo.totalMemory = (unsigned)(memstatus.dwTotalPhys / (1024*1024)); // in MB
  2683. ULARGE_INTEGER diskAvailStruct;
  2684. ULARGE_INTEGER diskTotalStruct;
  2685. if (primDiskPath)
  2686. {
  2687. diskTotalStruct.QuadPart = 0;
  2688. GetDiskFreeSpaceEx(primDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  2689. hdwInfo.primDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  2690. hdwInfo.primFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  2691. }
  2692. if (secDiskPath)
  2693. {
  2694. diskTotalStruct.QuadPart = 0;
  2695. GetDiskFreeSpaceEx(secDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  2696. hdwInfo.secDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  2697. hdwInfo.secFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  2698. }
  2699. // MORE: Find win32 call for NIC speed
  2700. #else // linux
  2701. unsigned memUsed, memActive, memSwap, memSwapUsed;
  2702. getMemUsage(memUsed, memActive, hdwInfo.totalMemory, memSwap, memSwapUsed);
  2703. hdwInfo.totalMemory /= 1024; // in MB
  2704. unsigned __int64 diskSize;
  2705. unsigned __int64 diskUsed;
  2706. if (primDiskPath)
  2707. {
  2708. getDiskUsage(primDiskPath, diskSize, diskUsed);
  2709. hdwInfo.primDiskSize = diskSize / (1024*1024*1024); // in GB
  2710. hdwInfo.primFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  2711. }
  2712. if (secDiskPath)
  2713. {
  2714. getDiskUsage(secDiskPath, diskSize, diskUsed);
  2715. hdwInfo.secDiskSize = diskSize / (1024*1024*1024); // in GB
  2716. hdwInfo.secFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  2717. }
  2718. // MORE: Find linux call for NIC speed -- mii-tool does not seem to work on our roxie clusters?
  2719. #endif
  2720. }
  2721. //===========================================================================
  2722. enum SegTypes {
  2723. segtype_free, //
  2724. segtype_heap, // rw-p named [heap]
  2725. segtype_data, // rw-p unnamed
  2726. segtype_guard, // ---p unnamed/named
  2727. segtype_stack, // rwxp
  2728. segtype_qlibcode, // r-xp named */lib200
  2729. segtype_qlibdata, // rw-p named */lib200
  2730. segtype_libcode, // r-xp named *
  2731. segtype_libdata, // rw-p named *
  2732. segtype_pstack, // rwxp named [stack]
  2733. segtype_const, // r--p
  2734. segtype_null // must be last
  2735. };
  2736. struct SegTypeRec
  2737. {
  2738. offset_t total;
  2739. unsigned n;
  2740. offset_t largest;
  2741. };
  2742. const char *PROCMAPHEADER =
  2743. "FREE,NFREE,MAXFREE,HEAP,STACK,NSTACKS,DATA,NDATA,MAXDATA,LIBDATA,QUERYDATA,MAXQUERYDATA,LIBCODE,QUERYCODE,MAXQLIBCODE";
  2744. class CProcReader
  2745. {
  2746. // Cant use JFile for /proc filesystem as seek doesn't work
  2747. public:
  2748. char ln [512];
  2749. FILE *file;
  2750. const char *buf;
  2751. size32_t bufsize;
  2752. CProcReader(const char *filename,const void *_buf,size32_t _buflen)
  2753. {
  2754. buf = (const char *)_buf;
  2755. bufsize = buf?_buflen:0;
  2756. file = buf?NULL:fopen(filename,"r");
  2757. }
  2758. ~CProcReader()
  2759. {
  2760. if (file)
  2761. fclose(file);
  2762. }
  2763. bool nextln()
  2764. {
  2765. if (buf) {
  2766. if (bufsize&&*buf) {
  2767. unsigned i = 0;
  2768. while (bufsize&&(i<sizeof(ln)-1)&&*buf&&(*buf!=10)&&(*buf!=13)) {
  2769. ln[i++] = *(buf++);
  2770. bufsize--;
  2771. }
  2772. ln[i] = 0;
  2773. while (bufsize&&*buf&&((*buf==10)||(*buf==13))) {
  2774. buf++;
  2775. bufsize--;
  2776. }
  2777. return true;
  2778. }
  2779. }
  2780. else if (file&&fgets (ln, sizeof(ln), file)) {
  2781. size_t i = strlen(ln);
  2782. while (i&&((ln[i-1]==10)||(ln[i-1]==13)))
  2783. i--;
  2784. ln[i] = 0;
  2785. return true;
  2786. }
  2787. if (file) {
  2788. fclose(file);
  2789. file = NULL;
  2790. }
  2791. return false;
  2792. }
  2793. void dump(bool useprintf)
  2794. {
  2795. while (nextln()) {
  2796. if (useprintf)
  2797. printf("%s\n",ln);
  2798. else
  2799. PROGLOG("%s",ln);
  2800. }
  2801. }
  2802. };
  2803. void printProcMap(const char *fn, bool printbody, bool printsummary, StringBuffer *lnout, MemoryBuffer *mb, bool useprintf)
  2804. {
  2805. CProcReader reader(fn,mb?mb->toByteArray():NULL,mb?mb->length():0);
  2806. unsigned i;
  2807. SegTypeRec recs[segtype_null];
  2808. memset(&recs,0,sizeof(recs));
  2809. offset_t last=0;
  2810. if (printbody) {
  2811. if (useprintf)
  2812. printf("START,END,SIZE,OFFSET,PERMS,PATH\n");
  2813. else
  2814. PROGLOG("START,END,SIZE,OFFSET,PERMS,PATH");
  2815. }
  2816. while (reader.nextln()) {
  2817. const char *ln = reader.ln;
  2818. unsigned n=0;
  2819. if (*ln) {
  2820. offset_t start = readHexNum(ln);
  2821. if (last&&(last!=start)) {
  2822. recs[segtype_free].n++;
  2823. offset_t ssz = start-last;
  2824. recs[segtype_free].total += ssz;
  2825. if (ssz>recs[segtype_free].largest)
  2826. recs[segtype_free].largest = ssz;
  2827. }
  2828. if (*ln=='-') {
  2829. ln++;
  2830. offset_t end = readHexNum(ln);
  2831. char perms[5];
  2832. skipSp(ln);
  2833. for (i=0;i<4;)
  2834. if (*ln)
  2835. perms[i++] = *(ln++);
  2836. perms[i] = 0;
  2837. skipSp(ln);
  2838. offset_t offset = readHexNum(ln);
  2839. skipSp(ln);
  2840. char dev[6];
  2841. for (i=0;i<5;)
  2842. if (*ln)
  2843. dev[i++] = *(ln++);
  2844. dev[i] = 0;
  2845. skipSp(ln);
  2846. unsigned inode __attribute__((unused)) = (unsigned) readDecNum(ln);
  2847. skipSp(ln);
  2848. const char *path = ln;
  2849. if (printbody) {
  2850. if (useprintf)
  2851. printf("%08" I64F "x,%08" I64F "x,%" I64F "d,%08" I64F "x,%s,%s,%s\n",start,end,(offset_t)(end-start),offset,perms,dev,path);
  2852. else
  2853. PROGLOG("%08" I64F "x,%08" I64F "x,%" I64F "d,%08" I64F "x,%s,%s,%s",start,end,(offset_t)(end-start),offset,perms,dev,path);
  2854. }
  2855. SegTypes t = segtype_data;
  2856. if (strcmp(perms,"---p")==0)
  2857. t = segtype_guard;
  2858. else if (strcmp(perms,"rwxp")==0) {
  2859. if (memicmp(ln,"[stack]",7)==0)
  2860. t = segtype_pstack;
  2861. else
  2862. t = segtype_stack;
  2863. }
  2864. else if (strcmp(perms,"rw-p")==0) {
  2865. if (memicmp(ln,"[heap]",6)==0)
  2866. t = segtype_heap;
  2867. else if (strstr(ln,"/libW200"))
  2868. t = segtype_qlibdata;
  2869. else if (*ln)
  2870. t = segtype_libdata;
  2871. else
  2872. t = segtype_data;
  2873. }
  2874. else if (strcmp(perms,"r-xp")==0) {
  2875. if (strstr(ln,"/libW200"))
  2876. t = segtype_qlibcode;
  2877. else if (*ln)
  2878. t = segtype_libcode;
  2879. }
  2880. else if (strcmp(perms,"r--p")==0)
  2881. t = segtype_const;
  2882. else {
  2883. ERRLOG("%s - unknown perms",perms);
  2884. continue;
  2885. }
  2886. recs[t].n++;
  2887. offset_t ssz = end-start;
  2888. recs[t].total += ssz;
  2889. if (ssz>recs[t].largest)
  2890. recs[t].largest = ssz;
  2891. n++;
  2892. last = end;
  2893. #ifndef __64BIT__
  2894. if ((end<0xffffffff)&&(end>=0xc0000000)) // rest is OS (32-bit only)
  2895. break;
  2896. #endif
  2897. }
  2898. }
  2899. }
  2900. if (printsummary||lnout) {
  2901. StringBuffer tln;
  2902. if (lnout==NULL)
  2903. lnout = &tln;
  2904. lnout->appendf("%" I64F "u," // total
  2905. "%u," // n
  2906. "%" I64F "u," // largest
  2907. "%" I64F "u," // total
  2908. "%" I64F "u," // total
  2909. "%u," // n
  2910. "%" I64F "u," // total
  2911. "%u," // n
  2912. "%" I64F "u," // largest
  2913. "%" I64F "u," // total
  2914. "%" I64F "u," // total
  2915. "%" I64F "u," // largest
  2916. "%" I64F "u," // total
  2917. "%" I64F "u," // total
  2918. "%" I64F "u" // largest
  2919. ,
  2920. recs[segtype_free].total,
  2921. recs[segtype_free].n,
  2922. recs[segtype_free].largest,
  2923. recs[segtype_heap].total,
  2924. recs[segtype_stack].total,
  2925. recs[segtype_stack].n,
  2926. recs[segtype_data].total,
  2927. recs[segtype_data].n,
  2928. recs[segtype_data].largest,
  2929. recs[segtype_libdata].total,
  2930. recs[segtype_qlibdata].total,
  2931. recs[segtype_qlibdata].largest,
  2932. recs[segtype_libcode].total,
  2933. recs[segtype_qlibcode].total,
  2934. recs[segtype_qlibcode].largest
  2935. );
  2936. if (printsummary) {
  2937. if (useprintf)
  2938. printf("%s\n%s\n",PROCMAPHEADER,tln.str());
  2939. else {
  2940. PROGLOG("%s",PROCMAPHEADER);
  2941. PROGLOG("%s",tln.str());
  2942. }
  2943. }
  2944. }
  2945. }
  2946. #ifdef _WIN32
  2947. // stubs
  2948. void PrintMemoryReport(bool full)
  2949. {
  2950. StringBuffer s;
  2951. getSystemTraceInfo(s,PerfMonProcMem);
  2952. PROGLOG("%s",s.str());
  2953. }
  2954. #else
  2955. void PrintMemoryReport(bool full)
  2956. {
  2957. // may be very close to oom so protect against re-entry
  2958. static int recurse=0;
  2959. if (recurse++==0) {
  2960. try {
  2961. printProcMap("/proc/self/maps",full,true,NULL,NULL,false);
  2962. }
  2963. catch (IException *e) {
  2964. e->Release();
  2965. }
  2966. catch (...) {
  2967. }
  2968. try {
  2969. PROGLOG("/proc/meminfo:");
  2970. CProcReader reader("/proc/meminfo",NULL,0);
  2971. reader.dump(false);
  2972. }
  2973. catch (IException *e) {
  2974. e->Release();
  2975. }
  2976. catch (...) {
  2977. }
  2978. try {
  2979. PROGLOG("/proc/self/status:");
  2980. CProcReader reader("/proc/self/status",NULL,0);
  2981. reader.dump(false);
  2982. }
  2983. catch (IException *e) {
  2984. e->Release();
  2985. }
  2986. catch (...) {
  2987. }
  2988. try {
  2989. StringBuffer s;
  2990. getSystemTraceInfo(s,PerfMonProcMem);
  2991. PROGLOG("%s",s.str());
  2992. PROGLOG("===============================================================");
  2993. }
  2994. catch (IException *e) {
  2995. e->Release();
  2996. }
  2997. catch (...) {
  2998. }
  2999. }
  3000. recurse--;
  3001. }
  3002. #endif
  3003. bool areTransparentHugePagesEnabled(HugePageMode mode)
  3004. {
  3005. return (mode != HugePageMode::Never) && (mode != HugePageMode::Unknown);
  3006. }
  3007. HugePageMode queryTransparentHugePagesMode()
  3008. {
  3009. #ifdef __linux__
  3010. StringBuffer contents;
  3011. try
  3012. {
  3013. contents.loadFile("/sys/kernel/mm/transparent_hugepage/enabled");
  3014. if (strstr(contents.str(), "[never]"))
  3015. return HugePageMode::Never;
  3016. if (strstr(contents.str(), "[madvise]"))
  3017. return HugePageMode::Madvise;
  3018. if (strstr(contents.str(), "[always]"))
  3019. return HugePageMode::Always;
  3020. }
  3021. catch (IException * e)
  3022. {
  3023. e->Release();
  3024. }
  3025. return HugePageMode::Unknown;
  3026. #endif
  3027. return HugePageMode::Never;
  3028. }
  3029. memsize_t getHugePageSize()
  3030. {
  3031. #ifdef __linux__
  3032. StringBuffer contents;
  3033. try
  3034. {
  3035. //Search for an entry Hugepagesize: xxxx kB
  3036. const char * const tag = "Hugepagesize:";
  3037. contents.loadFile("/proc/meminfo");
  3038. const char * hugepage = strstr(contents.str(), tag);
  3039. if (hugepage)
  3040. {
  3041. const char * next = hugepage + strlen(tag);
  3042. char * end;
  3043. memsize_t size = strtoul(next, &end, 10);
  3044. if (strncmp(end, " kB", 3) == 0)
  3045. return size * 0x400;
  3046. }
  3047. }
  3048. catch (IException * e)
  3049. {
  3050. e->Release();
  3051. }
  3052. #endif
  3053. return 0x200000; // Default for an x86 system
  3054. }
  3055. //===========================================================================
  3056. #ifdef LEAK_CHECK
  3057. #ifdef _WIN32
  3058. LeakChecker::LeakChecker(const char * _title) : title(_title)
  3059. {
  3060. _CrtMemCheckpoint(&oldMemState);
  3061. }
  3062. LeakChecker::~LeakChecker()
  3063. {
  3064. _CrtMemState newMemState, diffMemState;
  3065. _CrtMemCheckpoint(&newMemState);
  3066. if(_CrtMemDifference(&diffMemState, &oldMemState, &newMemState))
  3067. {
  3068. _RPT1(_CRT_WARN, "----- Memory leaks in '%s' -----\n", title);
  3069. _CrtMemDumpStatistics(&diffMemState);
  3070. _CrtMemDumpAllObjectsSince(&oldMemState);
  3071. _RPT0(_CRT_WARN, "----- End of leaks -----\n");
  3072. }
  3073. }
  3074. static char _logFile[255]; // used to hold last file name of log file for memory leak logging
  3075. static FILE *_logHandle = NULL;
  3076. _CRT_REPORT_HOOK oldReport;
  3077. static int MemoryLeakReportHook(int nRptType,char *szMsg,int *retVal)
  3078. {
  3079. if (szMsg && *szMsg)
  3080. {
  3081. if (_logHandle)
  3082. fprintf(_logHandle, szMsg);
  3083. if (*_logFile)
  3084. {
  3085. #if 1
  3086. // this works better in VS 2008 libraries (which fault in fopen)
  3087. int handle = _open(_logFile, O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);
  3088. _lseek(handle,0,SEEK_END);
  3089. _write(handle,szMsg,(unsigned)strlen(szMsg));
  3090. _close(handle);
  3091. #else
  3092. FILE *handle = fopen(_logFile, "a");
  3093. fprintf(handle, szMsg);
  3094. fclose(handle);
  3095. #endif
  3096. }
  3097. }
  3098. if (oldReport)
  3099. return oldReport(nRptType,szMsg,retVal);
  3100. else
  3101. return false;
  3102. }
  3103. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  3104. {
  3105. oldReport = _CrtSetReportHook(MemoryLeakReportHook);
  3106. return 1;
  3107. }
  3108. void logLeaks (const char *logFile)
  3109. {
  3110. if (logFile)
  3111. strncpy(_logFile, logFile, sizeof(_logFile));
  3112. else
  3113. _logFile[0] = 0;
  3114. }
  3115. void logLeaks (FILE *logHandle)
  3116. {
  3117. _logHandle = logHandle;
  3118. }
  3119. #else
  3120. #endif
  3121. #endif
  3122. #if !defined(USING_MPATROL) && defined(WIN32) && defined(_DEBUG)
  3123. void jlib_decl enableMemLeakChecking(bool enable)
  3124. {
  3125. int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  3126. if (enable)
  3127. tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
  3128. else
  3129. tmpFlag &= ~_CRTDBG_LEAK_CHECK_DF;
  3130. _CrtSetDbgFlag( tmpFlag );
  3131. }
  3132. #endif
  3133. #if defined(_WIN32) && defined(_DEBUG)
  3134. //#include <dbgint.h>
  3135. const unsigned maxUnique = 10000;
  3136. typedef struct _CrtMemBlockHeader
  3137. {
  3138. // Pointer to the block allocated just before this one:
  3139. struct _CrtMemBlockHeader *pBlockHeaderNext;
  3140. // Pointer to the block allocated just after this one:
  3141. struct _CrtMemBlockHeader *pBlockHeaderPrev;
  3142. char *szFileName; // File name
  3143. int nLine; // Line number
  3144. size_t nDataSize; // Size of user block
  3145. int nBlockUse; // Type of block
  3146. long lRequest; // Allocation number
  3147. } _CrtMemBlockHeader;
  3148. int compareFile(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  3149. {
  3150. int compare;
  3151. if (left->szFileName && right->szFileName)
  3152. compare = strcmp(left->szFileName, right->szFileName);
  3153. else if (left->szFileName)
  3154. compare = -1;
  3155. else if (right->szFileName)
  3156. compare = +1;
  3157. else
  3158. compare = 0;
  3159. return compare;
  3160. }
  3161. int compareLocation(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  3162. {
  3163. int compare = compareFile(left, right);
  3164. if (compare != 0)
  3165. return compare;
  3166. return left->nLine - right->nLine;
  3167. }
  3168. int compareBlocks(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  3169. {
  3170. int compare = compareLocation(left, right);
  3171. if (compare != 0)
  3172. return compare;
  3173. return (int)(right->nDataSize - left->nDataSize);
  3174. }
  3175. void addLocation(unsigned & numUnique, _CrtMemBlockHeader * * locations, unsigned * counts, _CrtMemBlockHeader * search)
  3176. {
  3177. int left = 0;
  3178. int right = numUnique;
  3179. while (left < right)
  3180. {
  3181. int mid = (left + right) >> 1;
  3182. int cmp = compareBlocks(search, locations[mid]);
  3183. if (cmp < 0)
  3184. right = mid;
  3185. else if (cmp > 0)
  3186. left = mid+1;
  3187. else
  3188. {
  3189. //Save the lowest allocation number (so quicker to set a subsequent breakpoint)
  3190. if (search->lRequest < locations[mid]->lRequest)
  3191. locations[mid] = search;
  3192. counts[mid]++;
  3193. return;
  3194. }
  3195. }
  3196. if (numUnique != maxUnique)
  3197. {
  3198. assertex(left == right);
  3199. memmove(locations + left+1, locations + left, (numUnique-left)*sizeof(*locations));
  3200. memmove(counts + left+1, counts + left, (numUnique-left)*sizeof(*counts));
  3201. locations[left] = search;
  3202. counts[left] = 1;
  3203. numUnique++;
  3204. }
  3205. else
  3206. counts[maxUnique]++;
  3207. }
  3208. unsigned dumpMemory(unsigned lenTarget, char * target, unsigned lenSrc, const void * ptr)
  3209. {
  3210. if (lenSrc > lenTarget)
  3211. lenSrc = lenTarget;
  3212. const char * src = (const char *)ptr;
  3213. for (unsigned i=0; i < lenSrc; i++)
  3214. {
  3215. byte next = src[i];
  3216. target[i] = (next >= 0x20 && next <= 0x7e) ? next : '.';
  3217. }
  3218. return lenSrc;
  3219. }
  3220. void printAllocationSummary()
  3221. {
  3222. _CrtMemState state;
  3223. _CrtMemCheckpoint(&state);
  3224. unsigned numUnique = 0;
  3225. _CrtMemBlockHeader * locations[maxUnique+1];
  3226. unsigned counts[maxUnique+1];
  3227. _clear(counts);
  3228. unsigned __int64 totalFree = 0;
  3229. unsigned __int64 totalAllocated = 0;
  3230. //Walk the heap, keeping a tally of (filename, line, size)->count
  3231. _CrtMemBlockHeader * cur;
  3232. for (cur = state.pBlockHeader; cur; cur=cur->pBlockHeaderNext)
  3233. {
  3234. switch (cur->nBlockUse)
  3235. {
  3236. case _NORMAL_BLOCK:
  3237. {
  3238. addLocation(numUnique, locations, counts, cur);
  3239. totalAllocated += cur->nDataSize;
  3240. break;
  3241. }
  3242. case _FREE_BLOCK:
  3243. totalFree += cur->nDataSize;
  3244. break;
  3245. }
  3246. }
  3247. PROGLOG("%d Unique allocations by <filename>(line)@size", numUnique);
  3248. for (unsigned i2 = 0; i2 < numUnique; i2++)
  3249. {
  3250. _CrtMemBlockHeader * display = locations[i2];
  3251. //char tempBuffer[16];
  3252. //unsigned len = dumpMemory(sizeof(tempBuffer), tempBuffer, display->nDataSize,
  3253. PROGLOG("%s(%d) %d:%d {%ld} = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, display->nDataSize, counts[i2], display->lRequest, display->nDataSize * counts[i2]);
  3254. }
  3255. PROGLOG("Ungrouped: %d Total %" I64F "d", counts[maxUnique], totalAllocated);
  3256. PROGLOG("Summary by location");
  3257. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  3258. {
  3259. _CrtMemBlockHeader * display = locations[iSummary2];
  3260. unsigned count = counts[iSummary2];
  3261. unsigned __int64 size = count * display->nDataSize;
  3262. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  3263. {
  3264. _CrtMemBlockHeader * next = locations[iSummary2];
  3265. if (compareLocation(display, next) != 0)
  3266. break;
  3267. count += counts[iSummary2];
  3268. size += (counts[iSummary2] * next->nDataSize);
  3269. }
  3270. PROGLOG("%s(%d) %d = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, count, size);
  3271. }
  3272. PROGLOG("Summary by source");
  3273. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  3274. {
  3275. _CrtMemBlockHeader * display = locations[iSummary2];
  3276. unsigned count = counts[iSummary2];
  3277. unsigned __int64 size = count * display->nDataSize;
  3278. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  3279. {
  3280. _CrtMemBlockHeader * next = locations[iSummary2];
  3281. if (compareFile(display, next) != 0)
  3282. break;
  3283. count += counts[iSummary2];
  3284. size += (counts[iSummary2] * next->nDataSize);
  3285. }
  3286. PROGLOG("%s %d = %d", display->szFileName ? display->szFileName : "<unknown>", count, size);
  3287. }
  3288. }
  3289. #else
  3290. void printAllocationSummary()
  3291. {
  3292. }
  3293. #endif
  3294. #ifdef _USE_MALLOC_HOOK
  3295. // Note memory hooks should not be enabled for release (as not re-entrant in linux)
  3296. static CriticalSection hookSect;
  3297. #ifdef __linux__
  3298. static void *(*old_malloc_hook)(size_t, const void *);
  3299. static void (*old_free_hook)(void *, const void *);
  3300. static void *(*old_realloc_hook)(void *, size_t, const void *);
  3301. static void * jlib_malloc_hook (size_t size, const void *caller) ;
  3302. static void jlib_free_hook (void *ptr, const void *caller);
  3303. static void *jlib_realloc_hook (void *ptr, size_t size, const void *caller);
  3304. static int jlib_hooknest = 0; // this *shouldn't* really be needed
  3305. inline void restore_malloc_hooks()
  3306. {
  3307. if (--jlib_hooknest==0) {
  3308. __malloc_hook = old_malloc_hook;
  3309. __realloc_hook = old_realloc_hook;
  3310. __free_hook = old_free_hook;
  3311. }
  3312. }
  3313. inline void set_malloc_hooks()
  3314. {
  3315. assertex(jlib_hooknest==0);
  3316. old_malloc_hook = __malloc_hook;
  3317. old_free_hook = __free_hook;
  3318. old_realloc_hook = __realloc_hook;
  3319. __malloc_hook = jlib_malloc_hook;
  3320. __free_hook = jlib_free_hook;
  3321. __realloc_hook = jlib_realloc_hook;
  3322. jlib_hooknest = 1;
  3323. }
  3324. inline void reset_malloc_hooks()
  3325. {
  3326. if (jlib_hooknest++==0) {
  3327. __malloc_hook = jlib_malloc_hook;
  3328. __free_hook = jlib_free_hook;
  3329. __realloc_hook = jlib_realloc_hook;
  3330. }
  3331. }
  3332. inline void incCount(unsigned sz,bool inc)
  3333. {
  3334. int i=0;
  3335. size32_t s=sz;
  3336. while (s) {
  3337. s /= 2;
  3338. i++;
  3339. }
  3340. if (inc)
  3341. memArea[i] += sz;
  3342. else
  3343. memArea[i] -= sz;
  3344. }
  3345. void * jlib_malloc_hook (size_t size, const void *caller)
  3346. {
  3347. CriticalBlock block(hookSect);
  3348. void *res;
  3349. restore_malloc_hooks();
  3350. res = malloc (size);
  3351. if (res) {
  3352. size = malloc_usable_size(res);
  3353. totalMem+=size;
  3354. if (totalMem>hwmTotalMem) {
  3355. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  3356. PrintStackReport();
  3357. PROGLOG("TOTALMEM(%" I64F "d): malloc %u",totalMem,(unsigned)size);
  3358. }
  3359. hwmTotalMem = totalMem;
  3360. }
  3361. }
  3362. else
  3363. size = 0;
  3364. incCount(size,true);
  3365. if (size>REPORT_LARGER_BLOCK_THAN) {
  3366. PrintStackReport();
  3367. PROGLOG("LARGEALLOC(%u): %p",(unsigned)size,res);
  3368. }
  3369. reset_malloc_hooks();
  3370. return res;
  3371. }
  3372. void jlib_free_hook (void *ptr, const void *caller)
  3373. {
  3374. if (!ptr)
  3375. return;
  3376. CriticalBlock block(hookSect);
  3377. restore_malloc_hooks();
  3378. size32_t sz = malloc_usable_size(ptr);
  3379. free (ptr);
  3380. totalMem -= sz;
  3381. incCount(sz,false);
  3382. if (sz>REPORT_LARGER_BLOCK_THAN) {
  3383. PROGLOG("LARGEFREE(%u): %p",(unsigned)sz,ptr);
  3384. }
  3385. reset_malloc_hooks();
  3386. }
  3387. void *jlib_realloc_hook (void *ptr, size_t size, const void *caller)
  3388. {
  3389. CriticalBlock block(hookSect);
  3390. restore_malloc_hooks();
  3391. size32_t oldsz = ptr?malloc_usable_size(ptr):0;
  3392. void *res = realloc (ptr,size);
  3393. if (res) {
  3394. size = malloc_usable_size(res);
  3395. totalMem += size;
  3396. }
  3397. else
  3398. size = 0;
  3399. totalMem -= oldsz;
  3400. if (totalMem>hwmTotalMem) {
  3401. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  3402. PrintStackReport();
  3403. PROGLOG("TOTALMEM(%" I64F "d): realloc %u %u",totalMem,(unsigned)oldsz,(unsigned)size);
  3404. }
  3405. hwmTotalMem = totalMem;
  3406. }
  3407. incCount(size,true);
  3408. incCount(oldsz,false);
  3409. if ((size>REPORT_LARGER_BLOCK_THAN)||(oldsz>REPORT_LARGER_BLOCK_THAN)) {
  3410. if (size>oldsz) {
  3411. PrintStackReport();
  3412. PROGLOG("LARGEREALLOC_UP(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  3413. }
  3414. else {
  3415. PROGLOG("LARGEREALLOC_DN(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  3416. }
  3417. }
  3418. reset_malloc_hooks();
  3419. return res;
  3420. }
  3421. void jlib_decl jlib_init_hook()
  3422. {
  3423. set_malloc_hooks();
  3424. }
  3425. __int64 jlib_decl setAllocHook(bool on,bool clear)
  3426. {
  3427. CriticalBlock block(hookSect);
  3428. __int64 ret = totalMem;
  3429. if (clear) {
  3430. totalMem = 0;
  3431. hwmTotalMem = 0;
  3432. }
  3433. if (on) {
  3434. if (jlib_hooknest==0)
  3435. set_malloc_hooks();
  3436. }
  3437. else {
  3438. while (jlib_hooknest) {
  3439. restore_malloc_hooks();
  3440. //printf("Total = %d bytes\n",totalMem);
  3441. }
  3442. }
  3443. return ret;
  3444. }
  3445. unsigned jlib_decl setAllocHook(bool on)
  3446. {
  3447. // bwd compatible - should use above version in preference
  3448. CriticalBlock block(hookSect);
  3449. if (on) {
  3450. if (jlib_hooknest==0) {
  3451. set_malloc_hooks();
  3452. totalMem = 0;
  3453. hwmTotalMem = 0;
  3454. }
  3455. }
  3456. else {
  3457. while (jlib_hooknest) {
  3458. restore_malloc_hooks();
  3459. //printf("Total = %d bytes\n",totalMem);
  3460. }
  3461. }
  3462. return (unsigned)totalMem;
  3463. }
  3464. #else // windows
  3465. static _CRT_ALLOC_HOOK oldHook = NULL;
  3466. static int allocHook( int allocType, void *userData, size_t size, int nBlockUse,
  3467. long requestNumber, const unsigned char *filename, int lineNumber)
  3468. {
  3469. CriticalBlock block(hookSect);
  3470. if ( nBlockUse == _CRT_BLOCK ) // Ignore internal C runtime library allocations
  3471. return TRUE;
  3472. static bool recurse = false;
  3473. if (recurse)
  3474. return TRUE;
  3475. recurse = true;
  3476. char *operation[] = { "", "allocating", "re-allocating", "freeing" };
  3477. char *blockType[] = { "Free", "Normal", "CRT", "Ignore", "Client" };
  3478. switch (allocType) {
  3479. case _HOOK_REALLOC:
  3480. if (userData==NULL)
  3481. printf("no data on realloc\n");
  3482. else
  3483. totalMem-=_msize(userData);
  3484. // fall through
  3485. case _HOOK_ALLOC:
  3486. totalMem+=size;
  3487. break;
  3488. case _HOOK_FREE:
  3489. if (userData)
  3490. totalMem-=_msize(userData);
  3491. break;
  3492. }
  3493. // printf( "Memory operation in %s, line %d: %s a %d-byte '%s' block (#%ld)\n",
  3494. // filename, lineNumber, operation[allocType], size,
  3495. // blockType[nBlockUse], requestNumber );
  3496. recurse = false;
  3497. return TRUE; // Allow the memory operation to proceed
  3498. }
  3499. unsigned jlib_decl setAllocHook(bool on)
  3500. {
  3501. CriticalBlock block(hookSect);
  3502. if (on) {
  3503. if (oldHook==NULL) {
  3504. oldHook = _CrtSetAllocHook( allocHook );
  3505. totalMem = 0;
  3506. }
  3507. }
  3508. else {
  3509. if (oldHook!=NULL)
  3510. _CrtSetAllocHook( oldHook );
  3511. oldHook = NULL;
  3512. //printf("Total = %d bytes\n",totalMem);
  3513. }
  3514. return (unsigned)totalMem; // return unsigned for bwd compat
  3515. }
  3516. #endif
  3517. __int64 getTotalMem()
  3518. {
  3519. return totalMem;
  3520. }
  3521. #else // release
  3522. unsigned jlib_decl setAllocHook(bool on __attribute__((unused)))
  3523. {
  3524. return 0;
  3525. }
  3526. __int64 jlib_decl setAllocHook(bool on __attribute__((unused)), bool clear __attribute__((unused)))
  3527. {
  3528. return 0;
  3529. }
  3530. __int64 jlib_decl getTotalMem()
  3531. {
  3532. return 0;
  3533. }
  3534. void jlib_decl jlib_init_hook()
  3535. {
  3536. }
  3537. #endif
  3538. class UserMetricMsgHandler : public CInterface, implements ILogMsgHandler, implements IUserMetric
  3539. {
  3540. mutable unsigned __int64 counter;
  3541. StringAttr metricName;
  3542. StringAttr regex;
  3543. Owned<ILogMsgFilter> regexFilter;
  3544. public:
  3545. virtual void Link(void) const { CInterface::Link(); }
  3546. virtual bool Release(void) const
  3547. {
  3548. if (CInterface::Release())
  3549. return true;
  3550. if (!IsShared())
  3551. {
  3552. queryLogMsgManager()->removeMonitor(const_cast<UserMetricMsgHandler *>(this)); // removeMonitor should take a const param really
  3553. }
  3554. return false;
  3555. }
  3556. UserMetricMsgHandler(const char *_name, const char *_regex) : metricName(_name), regex(_regex)
  3557. {
  3558. counter = 0;
  3559. regexFilter.setown(getRegexLogMsgFilter(regex, true));
  3560. queryLogMsgManager()->addMonitor(this, regexFilter);
  3561. }
  3562. // interface ILogMsgHandler
  3563. virtual void handleMessage(const LogMsg & msg __attribute__((unused))) const { counter++; }
  3564. virtual bool needsPrep() const { return false; }
  3565. virtual void prep() {}
  3566. virtual unsigned queryMessageFields() const { return MSGFIELD_detail; }
  3567. virtual void setMessageFields(unsigned _fields __attribute__((unused)) = MSGFIELD_all) {}
  3568. virtual void addToPTree(IPropertyTree * parent __attribute__((unused))) const {}
  3569. virtual int flush() { return 0; }
  3570. virtual char const *disable() { return 0; }
  3571. virtual void enable() {}
  3572. virtual bool getLogName(StringBuffer &name __attribute__((unused))) const { return false; }
  3573. virtual offset_t getLogPosition(StringBuffer &logFileName __attribute__((unused))) const { return 0; };
  3574. // interface IUserMetric
  3575. virtual unsigned __int64 queryCount() const { return counter; }
  3576. virtual const char *queryName() const { return metricName; }
  3577. virtual const char *queryMatchString() const { return regex; }
  3578. virtual void inc() { counter++; }
  3579. virtual void reset() { counter = 0; }
  3580. };
  3581. jlib_decl IUserMetric *createUserMetric(const char *name, const char *matchString)
  3582. {
  3583. return new UserMetricMsgHandler(name, matchString);
  3584. }