jdebug.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jdebug.hpp"
  16. #include "jstring.hpp"
  17. #include "jhash.hpp"
  18. #include "jmisc.hpp"
  19. #include "jexcept.hpp"
  20. #include "jmutex.hpp"
  21. #include "jtime.hpp"
  22. #include <stdio.h>
  23. #include <time.h>
  24. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  25. #undef new
  26. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  27. #endif
  28. #ifdef __linux__
  29. #include <sys/time.h>
  30. #include <sys/resource.h>
  31. #include <unistd.h>
  32. #include <sys/vfs.h>
  33. #include <sys/types.h>
  34. #include <sys/stat.h>
  35. #include <sys/klog.h>
  36. #include <dirent.h>
  37. #endif
  38. //===========================================================================
  39. #ifdef _DEBUG
  40. // #define _USE_MALLOC_HOOK // Only enable if you need it - slow!
  41. #else
  42. #undef _USE_MALLOC_HOOK // don't define for release - not threadsafe
  43. #endif
  44. #define _USE_RDTSC true
  45. #ifdef _USE_MALLOC_HOOK
  46. #define REPORT_LARGER_BLOCK_THAN (10*0x100000)
  47. static __int64 totalMem = 0;
  48. static __int64 hwmTotalMem = 0;
  49. #ifdef __linux__
  50. static unsigned memArea[32];
  51. #endif
  52. #endif
  53. #ifndef _WIN32
  54. #ifndef __64BIT__
  55. #define USE_OLD_PU
  56. #endif
  57. #endif
  58. /* LINUX SYS: log KEY
  59. ========================
  60. PU (%) is the percentage CPU in use (unchanged from previously).
  61. MU (%) is what percentage of total (all processes) memory is in use
  62. (ram + swap) or in 32 bit is the percentage of 3GB (address space)
  63. used (whichever larger).
  64. MAL is total memory in use (i.e malloced and not freed ) by this
  65. process (= MMP+SBK)
  66. MMP is the sum of memory mapped (large) blocks in use by this process
  67. (which will be returned to OS when freed).
  68. SBK is the sbrk'ed memory i.e. smaller blocks allocated from the
  69. arena. (note this memory is unlikely to be returned to OS while the
  70. process is still running).
  71. TOT (K) is an indication of the memory footprint of the process.
  72. This is the 'arena' size (which is how much reserved by sbrk) plus the
  73. mmap memory size (MMP).
  74. RAM (K) is how much real memory is in use by all processes - it is
  75. the same as what would be reported by the 'free' command after the
  76. caches/buffers have been subtracted.
  77. SWP (K) is the swap size in use for all processes.
  78. Extended stats
  79. DSK: disk statistics for each disk (e.g. [sda] and [sdb])
  80. r/s read i/o operations per sec (over last period)
  81. kr/s K bytes read per sec
  82. w/s write i/o operations per sec
  83. kw/s K bytes written per sec
  84. busy indication how busy the disk was during period (%)
  85. NIC: network (i.e. eth0) statistics
  86. rxp/s packets received per sec
  87. rxk/s K bytes received per sec
  88. txp/s packets transmitted per sec
  89. txk/s K bytes transmitted per sec
  90. CPU:
  91. usr % at user level
  92. sys % in kernel
  93. iow % waiting for i/o
  94. */
  95. inline void skipSp(const char *&s)
  96. {
  97. while (isspace(*s))
  98. s++;
  99. }
  100. inline offset_t readHexNum(const char *&s)
  101. {
  102. offset_t ret = 0;
  103. loop {
  104. switch (*s) {
  105. case '0':
  106. case '1':
  107. case '2':
  108. case '3':
  109. case '4':
  110. case '5':
  111. case '6':
  112. case '7':
  113. case '8':
  114. case '9': ret = ret*16+(*s-'0');
  115. break;
  116. case 'A':
  117. case 'B':
  118. case 'C':
  119. case 'D':
  120. case 'E':
  121. case 'F': ret = ret*16+(*s-'A'+10);
  122. break;
  123. case 'a':
  124. case 'b':
  125. case 'c':
  126. case 'd':
  127. case 'e':
  128. case 'f': ret = ret*16+(*s-'a'+10);
  129. break;
  130. default:
  131. return ret;
  132. }
  133. s++;
  134. }
  135. return 0;
  136. }
  137. inline offset_t readDecNum(const char *&s)
  138. {
  139. offset_t ret = 0;
  140. loop {
  141. switch (*s) {
  142. case '0':
  143. case '1':
  144. case '2':
  145. case '3':
  146. case '4':
  147. case '5':
  148. case '6':
  149. case '7':
  150. case '8':
  151. case '9': ret = ret*10+(*s-'0');
  152. break;
  153. default:
  154. return ret;
  155. }
  156. s++;
  157. }
  158. return 0;
  159. }
  160. #if defined(_WIN32)
  161. static __int64 numCyclesNTicks;
  162. static __int64 ticksPerSec;
  163. static __int64 numScaleTicks;
  164. static bool useRDTSC = _USE_RDTSC;
  165. static double cycleToNanoScale;
  166. static void calibrate_timing()
  167. {
  168. #ifndef _AMD64_
  169. if (useRDTSC)
  170. {
  171. unsigned long r;
  172. __asm {
  173. mov eax, 1 ;
  174. cpuid ;
  175. mov r, edx
  176. }
  177. if ((r&0x10)==0)
  178. useRDTSC = false;
  179. }
  180. #endif
  181. if (useRDTSC) {
  182. unsigned startu = usTick();
  183. cycle_t start = getTSC();
  184. unsigned s1 = msTick();
  185. unsigned s2;
  186. while (s1==(s2=msTick()));
  187. unsigned s3;
  188. while (s2==(s3=msTick()));
  189. unsigned elapsedu = usTick()-startu;
  190. if (elapsedu) {
  191. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  192. if (numPerUS>0)
  193. {
  194. cycleToNanoScale = 1000.0 / numPerUS;
  195. return;
  196. }
  197. }
  198. ERRLOG("calibrate_timing failed using RDTSC");
  199. useRDTSC = false;
  200. }
  201. static LARGE_INTEGER temp;
  202. QueryPerformanceFrequency(&temp);
  203. ticksPerSec = temp.QuadPart;
  204. numScaleTicks = ticksPerSec/100;
  205. LARGE_INTEGER t1;
  206. LARGE_INTEGER t2;
  207. QueryPerformanceCounter(&t1);
  208. t2.QuadPart=t1.QuadPart;
  209. while (t1.QuadPart==t2.QuadPart) QueryPerformanceCounter(&t1);
  210. cycle_t a1 = getTSC();
  211. t2.QuadPart = t1.QuadPart;
  212. while (t2.QuadPart-t1.QuadPart<numScaleTicks) QueryPerformanceCounter(&t2);
  213. cycle_t a2 = getTSC();
  214. numCyclesNTicks = (a2 - a1);
  215. cycleToNanoScale = ((double)numScaleTicks * 1000000000.0) / ((double)numCyclesNTicks * ticksPerSec);
  216. }
  217. __int64 cycle_to_nanosec(cycle_t cycles)
  218. {
  219. return (__int64)((double)cycles * cycleToNanoScale);
  220. }
  221. cycle_t nanosec_to_cycle(__int64 ns)
  222. {
  223. return (__int64)((double)ns / cycleToNanoScale);
  224. }
  225. cycle_t jlib_decl get_cycles_now()
  226. {
  227. if (useRDTSC)
  228. return getTSC();
  229. LARGE_INTEGER temp;
  230. QueryPerformanceCounter(&temp);
  231. return temp.QuadPart;
  232. }
  233. double getCycleToNanoScale()
  234. {
  235. return cycleToNanoScale;
  236. }
  237. #else
  238. static bool use_gettimeofday=false;
  239. static bool useRDTSC = _USE_RDTSC;
  240. static double cycleToNanoScale;
  241. void calibrate_timing()
  242. {
  243. if (useRDTSC) {
  244. unsigned long eax;
  245. unsigned long ebx;
  246. unsigned long ecx;
  247. unsigned long edx;
  248. #ifdef __64BIT__
  249. __asm__ ("cpuid\n\t" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "0" (1));
  250. #else
  251. // NB PIC code and ebx usage don't mix well
  252. asm volatile("pushl %%ebx \n\t"
  253. "cpuid \n\t"
  254. "movl %%ebx, %1 \n\t"
  255. "popl %%ebx \n\t"
  256. : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx)
  257. : "a"(1)
  258. : "cc");
  259. #endif
  260. if ((edx&0x10)==0)
  261. useRDTSC = false;
  262. }
  263. if (useRDTSC) {
  264. unsigned startu = usTick();
  265. cycle_t start = getTSC();
  266. unsigned s1 = msTick();
  267. unsigned s2;
  268. while (s1==(s2=msTick()));
  269. unsigned s3;
  270. while (s2==(s3=msTick()));
  271. unsigned elapsedu = usTick()-startu;
  272. if (elapsedu) {
  273. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  274. if (numPerUS>0)
  275. {
  276. cycleToNanoScale = 1000.0 / numPerUS;
  277. return;
  278. }
  279. }
  280. ERRLOG("calibrate_timing failed using RDTSC");
  281. useRDTSC = false;
  282. }
  283. cycleToNanoScale = 1.0;
  284. }
  285. cycle_t jlib_decl get_cycles_now()
  286. {
  287. if (useRDTSC)
  288. return getTSC();
  289. #ifndef __APPLE__
  290. if (!use_gettimeofday) {
  291. timespec tm;
  292. if (clock_gettime(CLOCK_MONOTONIC, &tm)>=0)
  293. return ((cycle_t)tm.tv_sec)*1000000000L+(tm.tv_nsec);
  294. use_gettimeofday = true;
  295. fprintf(stderr,"clock_gettime CLOCK_MONOTONIC returns %d",errno); // don't use PROGLOG
  296. }
  297. #endif
  298. struct timeval tm;
  299. gettimeofday(&tm,NULL);
  300. return ((cycle_t)tm.tv_sec)*1000000000L+(cycle_t)tm.tv_usec*1000L;
  301. }
  302. __int64 jlib_decl cycle_to_nanosec(cycle_t cycles)
  303. {
  304. if (useRDTSC)
  305. return (__int64)((double)cycles * cycleToNanoScale);
  306. return cycles;
  307. }
  308. cycle_t nanosec_to_cycle(__int64 ns)
  309. {
  310. if (useRDTSC)
  311. return (__int64)((double)ns / cycleToNanoScale);
  312. return ns;
  313. }
  314. double getCycleToNanoScale()
  315. {
  316. return cycleToNanoScale;
  317. }
  318. #endif
  319. void display_time(const char *title, cycle_t diff)
  320. {
  321. DBGLOG("Time taken for %s: %"I64F"d cycles (%"I64F"dM) = %"I64F"d msec\n", title, diff, diff/1000000, cycle_to_nanosec(diff)/1000000);
  322. }
  323. TimeSection::TimeSection(const char * _title) : title(_title)
  324. {
  325. start_time = get_cycles_now();
  326. }
  327. TimeSection::~TimeSection()
  328. {
  329. cycle_t end_time = get_cycles_now();
  330. if (title)
  331. display_time(title, end_time-start_time);
  332. }
  333. MTimeSection::MTimeSection(ITimeReporter *_master, const char * _title) : title(_title), master(_master)
  334. {
  335. start_time = get_cycles_now();
  336. }
  337. MTimeSection::~MTimeSection()
  338. {
  339. cycle_t end_time = get_cycles_now();
  340. if (master)
  341. master->addTiming(title, end_time-start_time);
  342. else
  343. display_time(title, end_time-start_time);
  344. }
  345. class TimeSectionInfo : public MappingBase
  346. {
  347. public:
  348. TimeSectionInfo(const char *_name, __int64 _time) : name(_name), totaltime(_time), count(1), maxtime(_time) {};
  349. TimeSectionInfo(const char *_name, __int64 _time, __int64 _maxtime, unsigned _count) : name(_name), totaltime(_time), count(_count), maxtime(_maxtime) {};
  350. TimeSectionInfo(MemoryBuffer &mb)
  351. {
  352. mb.read(name).read(totaltime).read(maxtime).read(count);
  353. }
  354. void serialize(MemoryBuffer &mb)
  355. {
  356. mb.append(name).append(totaltime).append(maxtime).append(count);
  357. }
  358. virtual const void * getKey() const { return name.get(); }
  359. StringAttr name;
  360. __int64 totaltime;
  361. __int64 maxtime;
  362. unsigned count;
  363. };
  364. class DefaultTimeReporter : public CInterface, implements ITimeReporter
  365. {
  366. StringMapOf<TimeSectionInfo> *sections;
  367. CriticalSection c;
  368. TimeSectionInfo &findSection(unsigned idx)
  369. {
  370. CriticalBlock b(c);
  371. HashIterator iter(*sections);
  372. for(iter.first(); iter.isValid(); iter.next())
  373. {
  374. if (!idx--)
  375. return (TimeSectionInfo &) iter.query();
  376. }
  377. throw MakeStringException(2, "Invalid index to DefaultTimeReporter");
  378. }
  379. public:
  380. IMPLEMENT_IINTERFACE
  381. DefaultTimeReporter()
  382. {
  383. sections = new StringMapOf<TimeSectionInfo>(true);
  384. }
  385. DefaultTimeReporter(MemoryBuffer &mb)
  386. {
  387. sections = new StringMapOf<TimeSectionInfo>(true);
  388. unsigned ns;
  389. mb.read(ns);
  390. while (ns--)
  391. {
  392. TimeSectionInfo &newinfo = * new TimeSectionInfo(mb);
  393. sections->replaceOwn(newinfo);
  394. }
  395. }
  396. ~DefaultTimeReporter()
  397. {
  398. // printTimings(); // Must explicitly call printTimings - no automatic print (too late here!)
  399. delete sections;
  400. }
  401. virtual void report(ITimeReportInfo &cb)
  402. {
  403. CriticalBlock b(c);
  404. HashIterator iter(*sections);
  405. for(iter.first(); iter.isValid(); iter.next())
  406. {
  407. TimeSectionInfo &ts = (TimeSectionInfo &)iter.query();
  408. cb.report(ts.name, ts.totaltime, ts.maxtime, ts.count);
  409. }
  410. }
  411. virtual void addTiming(const char *title, __int64 time)
  412. {
  413. CriticalBlock b(c);
  414. TimeSectionInfo *info = sections->find(title);
  415. if (info)
  416. {
  417. info->totaltime += time;
  418. if (time > info->maxtime) info->maxtime = time;
  419. info->count++;
  420. }
  421. else
  422. {
  423. TimeSectionInfo &newinfo = * new TimeSectionInfo(title, time);
  424. sections->replaceOwn(newinfo);
  425. }
  426. }
  427. virtual unsigned numSections()
  428. {
  429. CriticalBlock b(c);
  430. return sections->count();
  431. }
  432. virtual __int64 getTime(unsigned idx)
  433. {
  434. CriticalBlock b(c);
  435. return cycle_to_nanosec(findSection(idx).totaltime);
  436. }
  437. virtual __int64 getMaxTime(unsigned idx)
  438. {
  439. CriticalBlock b(c);
  440. return cycle_to_nanosec(findSection(idx).maxtime);
  441. }
  442. virtual unsigned getCount(unsigned idx)
  443. {
  444. CriticalBlock b(c);
  445. return findSection(idx).count;
  446. }
  447. virtual StringBuffer &getSection(unsigned idx, StringBuffer &s)
  448. {
  449. CriticalBlock b(c);
  450. return s.append(findSection(idx).name);
  451. }
  452. virtual void reset()
  453. {
  454. CriticalBlock b(c);
  455. delete sections;
  456. sections = new StringMapOf<TimeSectionInfo>(true);
  457. }
  458. virtual StringBuffer &getTimings(StringBuffer &str)
  459. {
  460. CriticalBlock b(c);
  461. if (numSections())
  462. {
  463. str.append("Timings:\n");
  464. for (unsigned i = 0; i < numSections(); i++)
  465. getSection(i, str.append(" ")).append(" total=")
  466. .append(getTime(i)/1000000)
  467. .append("ms max=")
  468. .append(getMaxTime(i)/1000)
  469. .append("us count=")
  470. .append(getCount(i))
  471. .append(" ave=")
  472. .append((getTime(i)/1000)/getCount(i))
  473. .append("us\n");
  474. }
  475. return str;
  476. }
  477. virtual void printTimings()
  478. {
  479. CriticalBlock b(c);
  480. if (numSections())
  481. {
  482. StringBuffer str;
  483. PrintLog(getTimings(str).str());
  484. }
  485. }
  486. virtual void addTiming(const char *name, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  487. {
  488. CriticalBlock b(c);
  489. TimeSectionInfo *info = sections->find(name);
  490. if (!info)
  491. {
  492. info = new TimeSectionInfo(name, totaltime, maxtime, count);
  493. sections->replaceOwn(*info);
  494. }
  495. else
  496. {
  497. info->totaltime += totaltime;
  498. if (maxtime > info->maxtime) info->maxtime = maxtime;
  499. info->count += count;
  500. }
  501. }
  502. virtual void mergeInto(ITimeReporter &other)
  503. {
  504. CriticalBlock b(c);
  505. HashIterator iter(*sections);
  506. for(iter.first(); iter.isValid(); iter.next())
  507. {
  508. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  509. other.addTiming(ts.name, ts.totaltime, ts.maxtime, ts.count);
  510. }
  511. }
  512. virtual void merge(ITimeReporter &other)
  513. {
  514. CriticalBlock b(c);
  515. other.mergeInto(*this);
  516. }
  517. virtual void serialize(MemoryBuffer &mb)
  518. {
  519. CriticalBlock b(c);
  520. mb.append(numSections());
  521. HashIterator iter(*sections);
  522. for(iter.first(); iter.isValid(); iter.next())
  523. {
  524. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  525. ts.serialize(mb);
  526. }
  527. }
  528. };
  529. ITimeReporter *defaultTimer;
  530. ITimeReporter *timer;
  531. ITimeReporter *createStdTimeReporter() { return new DefaultTimeReporter(); }
  532. ITimeReporter *createStdTimeReporter(MemoryBuffer &mb) { return new DefaultTimeReporter(mb); }
  533. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  534. {
  535. // perform v. early in process startup, ideally this would grab process exclusively for the 2 100ths of a sec it performs calc.
  536. calibrate_timing();
  537. return 1;
  538. }
  539. MODULE_INIT(INIT_PRIORITY_JDEBUG2)
  540. {
  541. timer = defaultTimer = new DefaultTimeReporter();
  542. return true;
  543. }
  544. MODULE_EXIT()
  545. {
  546. ::Release(defaultTimer);
  547. defaultTimer = NULL;
  548. }
  549. //===========================================================================
  550. // Performance Monitor
  551. #ifdef _WIN32
  552. #define SystemBasicInformation 0
  553. #define SystemPerformanceInformation 2
  554. #define SystemTimeInformation 3
  555. #define SystemProcessList 5
  556. typedef enum _PROCESSINFOCLASS {
  557. ProcessBasicInformation,
  558. ProcessQuotaLimits,
  559. ProcessIoCounters,
  560. ProcessVmCounters,
  561. ProcessTimes,
  562. ProcessBasePriority,
  563. ProcessRaisePriority,
  564. ProcessDebugPort,
  565. ProcessExceptionPort,
  566. ProcessAccessToken,
  567. ProcessLdtInformation,
  568. ProcessLdtSize,
  569. ProcessDefaultHardErrorMode,
  570. ProcessIoPortHandlers, // Note: this is kernel mode only
  571. ProcessPooledUsageAndLimits,
  572. ProcessWorkingSetWatch,
  573. ProcessUserModeIOPL,
  574. ProcessEnableAlignmentFaultFixup,
  575. ProcessPriorityClass,
  576. ProcessWx86Information,
  577. ProcessHandleCount,
  578. ProcessAffinityMask,
  579. ProcessPriorityBoost,
  580. ProcessDeviceMap,
  581. ProcessSessionInformation,
  582. ProcessForegroundInformation,
  583. ProcessWow64Information,
  584. MaxProcessInfoClass
  585. } PROCESSINFOCLASS;
  586. typedef LONG NTSTATUS;
  587. #define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
  588. typedef struct
  589. {
  590. DWORD dwUnknown1;
  591. ULONG uKeMaximumIncrement;
  592. ULONG uPageSize;
  593. ULONG uMmNumberOfPhysicalPages;
  594. ULONG uMmLowestPhysicalPage;
  595. ULONG uMmHighestPhysicalPage;
  596. ULONG uAllocationGranularity;
  597. PVOID pLowestUserAddress;
  598. PVOID pMmHighestUserAddress;
  599. ULONG uKeActiveProcessors;
  600. BYTE bKeNumberProcessors;
  601. BYTE bUnknown2;
  602. WORD wUnknown3;
  603. } SYSTEM_BASIC_INFORMATION;
  604. typedef struct
  605. {
  606. LARGE_INTEGER liIdleTime;
  607. DWORD dwSpare[76];
  608. } SYSTEM_PERFORMANCE_INFORMATION;
  609. typedef struct
  610. {
  611. LARGE_INTEGER liKeBootTime;
  612. LARGE_INTEGER liKeSystemTime;
  613. LARGE_INTEGER liExpTimeZoneBias;
  614. ULONG uCurrentTimeZoneId;
  615. DWORD dwReserved;
  616. } SYSTEM_TIME_INFORMATION;
  617. struct PROCESS_BASIC_INFORMATION {
  618. long ExitStatus;
  619. void * PebBaseAddress;
  620. unsigned long AffinityMask;
  621. long BasePriority;
  622. unsigned long UniqueProcessId;
  623. unsigned long InheritedFromUniqueProcessId;
  624. };
  625. // QUOTA_LIMITS
  626. struct __IO_COUNTERS { // defined in SDK
  627. ULONGLONG ReadOperationCount;
  628. ULONGLONG WriteOperationCount;
  629. ULONGLONG OtherOperationCount;
  630. ULONGLONG ReadTransferCount;
  631. ULONGLONG WriteTransferCount;
  632. ULONGLONG OtherTransferCount;
  633. };
  634. struct VM_COUNTERS {
  635. unsigned long PeakVirtualSize;
  636. unsigned long VirtualSize;
  637. unsigned long PageFaultCount;
  638. unsigned long PeakWorkingSetSize;
  639. unsigned long WorkingSetSize;
  640. unsigned long QuotaPeakPagedPoolUsage;
  641. unsigned long QuotaPagedPoolUsage;
  642. unsigned long QuotaPeakNonPagedPoolUsage;
  643. unsigned long QuotaNonPagedPoolUsage;
  644. unsigned long PagefileUsage;
  645. unsigned long PeakPagefileUsage;
  646. };
  647. struct POOLED_USAGE_AND_LIMITS {
  648. unsigned long PeakPagedPoolUsage;
  649. unsigned long PagedPoolUsage;
  650. unsigned long PagedPoolLimit;
  651. unsigned long PeakNonPagedPoolUsage;
  652. unsigned long NonPagedPoolUsage;
  653. unsigned long NonPagedPoolLimit;
  654. unsigned long PeakPagefileUsage;
  655. unsigned long PagefileUsage;
  656. unsigned long PagefileLimit;
  657. };
  658. struct KERNEL_USER_TIMES {
  659. __int64 CreateTime;
  660. __int64 ExitTime;
  661. __int64 KernelTime;
  662. __int64 UserTime;
  663. //__int64 EllapsedTime;
  664. };
  665. // ntdll!NtQuerySystemInformation (NT specific!)
  666. //
  667. // The function copies the system information of the
  668. // specified type into a buffer
  669. //
  670. // NTSYSAPI
  671. // NTSTATUS
  672. // NTAPI
  673. // NtQuerySystemInformation(
  674. // IN UINT SystemInformationClass, // information type
  675. // OUT PVOID SystemInformation, // pointer to buffer
  676. // IN ULONG SystemInformationLength, // buffer size in bytes
  677. // OUT PULONG ReturnLength OPTIONAL // pointer to a 32-bit
  678. // // variable that receives
  679. // // the number of bytes
  680. // // written to the buffer
  681. // );
  682. //
  683. //NTSYSCALLAPI
  684. //NTSTATUS
  685. //NTAPI
  686. //NtQueryInformationProcess(
  687. // IN HANDLE ProcessHandle,
  688. // IN PROCESSINFOCLASS ProcessInformationClass,
  689. // OUT PVOID ProcessInformation,
  690. // IN ULONG ProcessInformationLength,
  691. // OUT PULONG ReturnLength OPTIONAL
  692. // );
  693. typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
  694. typedef LONG (WINAPI *PROCNTQIP)(HANDLE,UINT,PVOID,ULONG,PULONG);
  695. typedef LONG (WINAPI *PROCNTGST)(LARGE_INTEGER*, LARGE_INTEGER*, LARGE_INTEGER*);
  696. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  697. {
  698. // MORE: Might be a better way to get CPU speed (actual) than the one stored in Registry
  699. LONG lRet;
  700. HKEY hKey;
  701. DWORD keyValue;
  702. DWORD valueLen = sizeof(keyValue);
  703. if ((lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0L, KEY_READ , &hKey)) != ERROR_SUCCESS)
  704. {
  705. DBGLOG("RegOpenKeyEx(HKEY_LOCAL_MACHINE, ...) failed to open CentralProcessor\\0 - SysErrorCode=%d", lRet);
  706. }
  707. else if ((lRet = RegQueryValueEx(hKey, TEXT("~MHz"), NULL, NULL, (LPBYTE) &keyValue, &valueLen)) != ERROR_SUCCESS)
  708. {
  709. DBGLOG("RegQueryValueEx() failed to get CPU speed - errorCode=%d", lRet);
  710. RegCloseKey(hKey);
  711. }
  712. else
  713. {
  714. CPUSpeed = keyValue;
  715. RegCloseKey(hKey);
  716. }
  717. SYSTEM_INFO sysInfo;
  718. GetSystemInfo(&sysInfo);
  719. numCPUs = sysInfo.dwNumberOfProcessors;
  720. }
  721. unsigned getAffinityCpus()
  722. {
  723. unsigned numCpus = 0;
  724. DWORD ProcessAffinityMask, SystemAffinityMask;
  725. if (GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask, &SystemAffinityMask))
  726. {
  727. unsigned i = 0;
  728. while (ProcessAffinityMask)
  729. {
  730. if (ProcessAffinityMask & 1)
  731. ++numCpus;
  732. ProcessAffinityMask >>=1;
  733. }
  734. }
  735. else // fall back to legacy num system cpus
  736. {
  737. Owned<IException> e = MakeOsException(GetLastError(), "Failed to get affinity");
  738. EXCLOG(e, NULL);
  739. unsigned cpuSpeed;
  740. getCpuInfo(numCpus, cpuSpeed);
  741. return numCpus;
  742. }
  743. return numCpus;
  744. }
  745. #else // linux
  746. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  747. {
  748. int cpufd = open("/proc/cpuinfo",O_RDONLY);
  749. if (cpufd==-1)
  750. return;
  751. MemoryAttr ma;
  752. char *buf = (char *)ma.allocate(0x10000);
  753. size32_t l=0;
  754. loop {
  755. size32_t rd = read(cpufd, buf+l, 0x10000-1-l);
  756. if ((int)rd<=0)
  757. break;
  758. l += rd;
  759. }
  760. buf[l] = 0;
  761. const char *bufptr = buf;
  762. char * tail;
  763. numCPUs = CPUSpeed = 0;
  764. // MORE: It is a shame that the info in this file (/proc/cpuinfo) are formatted (ie tabs .. etc)
  765. const char *cpuNumTag = "processor\t:";
  766. const char *cpuSpeedTag = "cpu MHz\t\t:";
  767. while (bufptr) {
  768. if (*bufptr =='\n')
  769. bufptr++;
  770. if (strncmp(cpuNumTag, bufptr, strlen(cpuNumTag))==0)
  771. numCPUs++;
  772. else if (strncmp(cpuSpeedTag, bufptr, strlen(cpuSpeedTag))==0)
  773. CPUSpeed = (unsigned)strtol(bufptr+strlen(cpuSpeedTag), &tail, 10);
  774. bufptr = strchr(bufptr, '\n');
  775. }
  776. close(cpufd);
  777. }
  778. unsigned getAffinityCpus()
  779. {
  780. cpu_set_t cpuset;
  781. int err = pthread_getaffinity_np(GetCurrentThreadId(), sizeof(cpu_set_t), &cpuset);
  782. if (0 == err)
  783. {
  784. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 6)
  785. return CPU_COUNT(&cpuset);
  786. #else
  787. unsigned numCpus = 0;
  788. unsigned setSize = CPU_SETSIZE;
  789. while (setSize--)
  790. {
  791. if (CPU_ISSET(setSize, &cpuset))
  792. ++numCpus;
  793. }
  794. return numCpus;
  795. #endif /* GLIBC */
  796. }
  797. }
  798. static void getMemUsage(unsigned &inuse,unsigned &active,unsigned &total,unsigned &swaptotal,unsigned &swapinuse)
  799. {
  800. unsigned free=0;
  801. unsigned swapfree=0;
  802. active = 0;
  803. inuse = 0;
  804. static int memfd = -1;
  805. if (memfd==-1)
  806. memfd = open("/proc/meminfo",O_RDONLY);
  807. if (memfd==-1)
  808. return;
  809. lseek(memfd, 0L, 0);
  810. char buf[1024];
  811. size32_t l = read(memfd, buf, sizeof(buf)-1);
  812. if ((int)l<=0)
  813. return;
  814. buf[l] = 0;
  815. const char *bufptr = buf;
  816. char * tail;
  817. unsigned i = 7; // supposed to match max number of items extract below
  818. total = swaptotal = free = active = swapfree = 0;
  819. unsigned swapcached = 0;
  820. unsigned cached = 0;
  821. while (bufptr&&i) {
  822. if (*bufptr =='\n')
  823. bufptr++;
  824. i--;
  825. if (strncmp("MemTotal:", bufptr, 9)==0)
  826. total = (unsigned)strtol(bufptr+9, &tail, 10);
  827. else if (strncmp("SwapTotal:", bufptr, 10)==0)
  828. swaptotal = (unsigned)strtol(bufptr+10, &tail, 10);
  829. else if (strncmp("MemFree:", bufptr, 8)==0)
  830. free = (unsigned)strtol(bufptr+8, &tail, 10);
  831. else if (strncmp("Active:", bufptr, 7)==0)
  832. active = (unsigned)strtol(bufptr+7, &tail, 10);
  833. else if (strncmp("SwapFree:", bufptr, 9)==0)
  834. swapfree = (unsigned)strtol(bufptr+9, &tail, 10);
  835. else if (strncmp("Cached:", bufptr, 7)==0)
  836. cached = (unsigned)strtol(bufptr+7, &tail, 10);
  837. else if (strncmp("SwapCached:", bufptr, 11)==0)
  838. swapcached = (unsigned)strtol(bufptr+11, &tail, 10);
  839. else
  840. i++;
  841. bufptr = strchr(bufptr, '\n');
  842. }
  843. inuse = total-free-cached;
  844. swapinuse = swaptotal-swapfree-swapcached;
  845. }
  846. class CInt64fix
  847. {
  848. __int64 val;
  849. public:
  850. CInt64fix()
  851. {
  852. val = 0;
  853. }
  854. void set(int v)
  855. {
  856. __int64 ret = (unsigned)v;
  857. while (val-ret>0x80000000LL)
  858. ret += 0x100000000LL;
  859. val = ret;
  860. }
  861. __int64 get()
  862. {
  863. return val;
  864. }
  865. };
  866. void getMemStats(StringBuffer &out, unsigned &memused, unsigned &memtot)
  867. {
  868. #ifdef __linux__
  869. struct mallinfo mi = mallinfo();
  870. static CInt64fix fixuordblks;
  871. fixuordblks.set(mi.uordblks);
  872. static CInt64fix fixusmblks;
  873. fixusmblks.set(mi.usmblks);
  874. static CInt64fix fixhblkhd;
  875. fixhblkhd.set(mi.hblkhd);
  876. static CInt64fix fixarena;
  877. fixarena.set(mi.arena);
  878. __int64 sbrkmem = fixuordblks.get()+fixusmblks.get();
  879. __int64 mmapmem = fixhblkhd.get();
  880. __int64 arena = fixarena.get();
  881. __int64 total = mmapmem+sbrkmem;
  882. unsigned mu;
  883. unsigned ma;
  884. unsigned mt;
  885. unsigned st;
  886. unsigned su;
  887. getMemUsage(mu,ma,mt,st,su);
  888. unsigned muval = (unsigned)(((__int64)mu+(__int64)su)*100/((__int64)mt+(__int64)st));
  889. __int64 proctot = arena+mmapmem;
  890. if (sizeof(memsize_t)==4) {
  891. unsigned muval2 = (proctot*100)/(3*(__int64)0x40000000);
  892. if (muval2>muval)
  893. muval = muval2;
  894. }
  895. if (muval>100)
  896. muval = 100; // !
  897. unsigned sum = (unsigned)((arena+mmapmem)/1024);
  898. out.appendf("MU=%3u%% MAL=%"I64F"d MMP=%"I64F"d SBK=%"I64F"d TOT=%uK RAM=%uK SWP=%uK",
  899. muval, total, mmapmem, sbrkmem, (unsigned)(proctot/1024), mu, su);
  900. #ifdef _USE_MALLOC_HOOK
  901. if (totalMem)
  902. out.appendf(" TM=%"I64F"d",totalMem);
  903. #endif
  904. memused = mu+su;
  905. memtot = mt+st;
  906. #endif
  907. #if defined (__FreeBSD__) || defined (__APPLE__)
  908. UNIMPLEMENTED;
  909. #endif
  910. }
  911. void getDiskUsage(char const * path, unsigned __int64 & total, unsigned __int64 & inUse)
  912. {
  913. #ifdef __linux__
  914. struct statfs stfs;
  915. if(statfs(path, &stfs) < 0)
  916. {
  917. //PrintLog("statfs error for filesystem '%s'", path);
  918. total = inUse = 0;
  919. }
  920. else
  921. {
  922. struct stat st;
  923. if(stat(path, &st) < 0)
  924. {
  925. //PrintLog("stat error for filesystem '%s'", path);
  926. total = inUse = 0;
  927. }
  928. else
  929. {
  930. total = (unsigned __int64)stfs.f_blocks * st.st_blksize;
  931. inUse = total - (unsigned __int64)stfs.f_bfree * st.st_blksize;
  932. }
  933. }
  934. #endif
  935. #if defined (__FreeBSD__) || defined (__APPLE__)
  936. UNIMPLEMENTED;
  937. #endif
  938. }
  939. #endif
  940. #define RXMAX 1000000 // can be 10x bigger but this produces reasonable amounts
  941. unsigned packetsLasttime;
  942. __int64 packetsLastrx = -1;
  943. __int64 packetsLasttx;
  944. bool getPacketStats(unsigned & tx, unsigned & rx)
  945. {
  946. unsigned thistime = msTick();
  947. JSocketStatistics jstats;
  948. getSocketStatistics(jstats);
  949. bool ret = true;
  950. if(packetsLastrx!=-1)
  951. {
  952. tx = (unsigned) ((jstats.writesize-packetsLasttx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  953. rx = (unsigned) ((jstats.readsize-packetsLastrx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  954. }
  955. else
  956. ret = false;
  957. packetsLastrx = jstats.readsize;
  958. packetsLasttx = jstats.writesize;
  959. packetsLasttime = thistime;
  960. return ret;
  961. }
  962. #ifndef _WIN32
  963. struct CProcInfo: extends CInterface
  964. {
  965. IMPLEMENT_IINTERFACE;
  966. int pid;
  967. char cmd[16];
  968. unsigned tot_utime;
  969. unsigned tot_stime;
  970. unsigned utime;
  971. unsigned stime;
  972. bool active;
  973. bool first;
  974. CProcInfo(int _pid)
  975. {
  976. pid = _pid;
  977. tot_utime = 0;
  978. tot_stime = 0;
  979. utime = 0;
  980. stime = 0;
  981. active = false;
  982. first = true;
  983. }
  984. char *skipnumfld(char *s, const char *&num)
  985. {
  986. while (*s&&isspace(*s))
  987. s++;
  988. num = s;
  989. if ((*s=='-')||(*s=='+'))
  990. s++;
  991. while (*s&&isdigit(*s))
  992. s++;
  993. if (*s==' ')
  994. *(s++)= 0; // terminate num
  995. while (*s&&isspace(*s))
  996. s++;
  997. return s;
  998. }
  999. bool load()
  1000. {
  1001. StringBuffer fn;
  1002. fn.appendf("/proc/%d/stat", pid);
  1003. char buf[800]; /* about 40 fields, 64-bit decimal is about 20 chars */
  1004. int fd = open(fn.str(), O_RDONLY, 0);
  1005. if (fd==-1)
  1006. return false;
  1007. int rd = read(fd, buf, sizeof(buf)-1);
  1008. close(fd);
  1009. if (rd<80)
  1010. return false;
  1011. buf[rd] = 0;
  1012. char *s = strchr(buf,'(');
  1013. if (!s)
  1014. return false;
  1015. s++;
  1016. unsigned i = 0;
  1017. while (*s&&(*s!=')')&&(i<15))
  1018. cmd[i++] = *(s++);
  1019. if (!*s)
  1020. return false;
  1021. cmd[i] = 0;
  1022. s+=2;
  1023. char state = *(s++);
  1024. //printf("**'%s'\n",s);
  1025. const char *num;
  1026. s = skipnumfld(s,num);
  1027. int ppid = atoi(num);
  1028. // skip pgrp, session, tty_num, tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt
  1029. for (i=0;i<9;i++)
  1030. s = skipnumfld(s,num);
  1031. unsigned prev_utime = tot_utime;
  1032. unsigned prev_stime = tot_stime;
  1033. s = skipnumfld(s,num);
  1034. //printf("**N'%s'\n",num);
  1035. tot_utime = (unsigned)atoi64_l(num,strlen(num));
  1036. s = skipnumfld(s,num);
  1037. //printf("**N'%s'\n",num);
  1038. tot_stime = (unsigned)atoi64_l(num,strlen(num));
  1039. if (first)
  1040. first = false;
  1041. else {
  1042. stime = tot_stime-prev_stime;
  1043. utime = tot_utime-prev_utime;
  1044. }
  1045. active = true;
  1046. return true;
  1047. }
  1048. };
  1049. class CProcessMonitor
  1050. {
  1051. CIArrayOf<CProcInfo> processes;
  1052. unsigned tot_time;
  1053. bool busy;
  1054. static int compare(CInterface **i1, CInterface **i2)
  1055. {
  1056. CProcInfo *pi1 = QUERYINTERFACE(*i1,CProcInfo);
  1057. CProcInfo *pi2 = QUERYINTERFACE(*i2,CProcInfo);
  1058. return pi2->stime+pi2->utime-pi1->stime-pi1->utime;
  1059. }
  1060. public:
  1061. CProcessMonitor()
  1062. {
  1063. busy = false;
  1064. }
  1065. void scan()
  1066. {
  1067. #ifdef __linux__
  1068. ForEachItemIn(i1,processes)
  1069. processes.item(i1).active = false;
  1070. DIR *dir = opendir("/proc");
  1071. loop {
  1072. struct dirent *ent;
  1073. struct dirent entryMem;
  1074. readdir_r(dir, &entryMem, &ent);
  1075. if (!ent)
  1076. break;
  1077. if ((ent->d_name[0]>='0')&&(ent->d_name[0]<='9')) {
  1078. int pid = atoi(ent->d_name);
  1079. if (pid) {
  1080. CProcInfo *pi = NULL;
  1081. ForEachItemIn(i2,processes) {
  1082. if (processes.item(i2).pid == pid) {
  1083. pi = &processes.item(i2);
  1084. break;
  1085. }
  1086. }
  1087. if (!pi) {
  1088. pi = new CProcInfo(pid);
  1089. processes.append(*pi);
  1090. }
  1091. pi->load();
  1092. }
  1093. }
  1094. }
  1095. closedir(dir);
  1096. tot_time = 0;
  1097. ForEachItemInRev(i3,processes) {
  1098. CProcInfo &pi = processes.item(i3);
  1099. if (pi.active)
  1100. tot_time += pi.stime+pi.utime;
  1101. else
  1102. processes.remove(i3);
  1103. }
  1104. #endif
  1105. #if defined (__FreeBSD__) || defined (__APPLE__)
  1106. UNIMPLEMENTED;
  1107. #endif
  1108. }
  1109. void print(unsigned n,StringBuffer &str)
  1110. {
  1111. if (!tot_time)
  1112. return;
  1113. assertex(n);
  1114. processes.sort(compare);
  1115. StringBuffer name;
  1116. ForEachItemIn(i1,processes) {
  1117. CProcInfo &pi = processes.item(i1);
  1118. if ((pi.stime==0)&&(pi.utime==0))
  1119. break;
  1120. getThreadName(pi.pid,0,name.clear());
  1121. str.appendf("\n TT: PI=%d PN=%s PC=%d ST=%d UT=%d%s%s",pi.pid,pi.cmd,(pi.stime+pi.utime)*100/tot_time,pi.stime,pi.utime,name.length()?" TN=":"",name.str());
  1122. if (--n==0)
  1123. break;
  1124. }
  1125. }
  1126. void printBusy(unsigned pc,StringBuffer &str)
  1127. {
  1128. if (pc>90) {
  1129. scan();
  1130. if (busy)
  1131. print(3,str); // print top 3
  1132. else
  1133. busy = true;
  1134. }
  1135. else {
  1136. busy = false;
  1137. processes.kill();
  1138. }
  1139. }
  1140. };
  1141. #ifndef HZ
  1142. #define HZ 100
  1143. #endif
  1144. #define IDE0_MAJOR 3
  1145. #define SCSI_DISK0_MAJOR 8
  1146. #define SCSI_DISK1_MAJOR 65
  1147. #define SCSI_DISK7_MAJOR 71
  1148. #define SCSI_DISK10_MAJOR 128
  1149. #define SCSI_DISK17_MAJOR 135
  1150. #define IDE1_MAJOR 22
  1151. #define IDE2_MAJOR 33
  1152. #define IDE3_MAJOR 34
  1153. #define IDE4_MAJOR 56
  1154. #define IDE5_MAJOR 57
  1155. #define IDE6_MAJOR 88
  1156. #define IDE7_MAJOR 89
  1157. #define IDE8_MAJOR 90
  1158. #define IDE9_MAJOR 91
  1159. #define COMPAQ_SMART2_MAJOR 72
  1160. #define IDE_DISK_MAJOR(M) ((M) == IDE0_MAJOR || (M) == IDE1_MAJOR || \
  1161. (M) == IDE2_MAJOR || (M) == IDE3_MAJOR || \
  1162. (M) == IDE4_MAJOR || (M) == IDE5_MAJOR || \
  1163. (M) == IDE6_MAJOR || (M) == IDE7_MAJOR || \
  1164. (M) == IDE8_MAJOR || (M) == IDE9_MAJOR)
  1165. #define SCSI_DISK_MAJOR(M) ((M) == SCSI_DISK0_MAJOR || \
  1166. ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) || \
  1167. ((M) >= SCSI_DISK10_MAJOR && (M) <= SCSI_DISK17_MAJOR))
  1168. #define OTHER_DISK_MAJOR(M) ((M) == COMPAQ_SMART2_MAJOR) // by investigation!
  1169. class CExtendedStats // Disk network and cpu stats
  1170. {
  1171. struct blkio_info
  1172. {
  1173. unsigned rd_ios; // Read I/O operations
  1174. unsigned rd_merges; // Reads merged
  1175. __uint64 rd_sectors; // Sectors read
  1176. unsigned rd_ticks; // Time in queue + service for read
  1177. unsigned wr_ios; // Write I/O operations
  1178. unsigned wr_merges; // Writes merged
  1179. __uint64 wr_sectors; // Sectors written
  1180. unsigned wr_ticks; // Time in queue + service for write
  1181. unsigned ticks; // Time of requests in queue
  1182. unsigned aveq; // Average queue length
  1183. };
  1184. struct cpu_info
  1185. {
  1186. __uint64 user;
  1187. __uint64 system;
  1188. __uint64 idle;
  1189. __uint64 iowait;
  1190. };
  1191. struct net_info
  1192. {
  1193. __uint64 rxbytes;
  1194. __uint64 rxpackets;
  1195. __uint64 rxerrors;
  1196. __uint64 rxdrops;
  1197. __uint64 txbytes;
  1198. __uint64 txpackets;
  1199. __uint64 txerrors;
  1200. __uint64 txdrops;
  1201. };
  1202. struct part_info
  1203. {
  1204. unsigned int major;
  1205. unsigned int minor;
  1206. char name[32];
  1207. };
  1208. part_info *partition;
  1209. unsigned nparts;
  1210. blkio_info *newblkio;
  1211. blkio_info *oldblkio;
  1212. cpu_info newcpu;
  1213. unsigned numcpu;
  1214. cpu_info oldcpu;
  1215. cpu_info cpu;
  1216. net_info oldnet;
  1217. net_info newnet;
  1218. unsigned ncpu;
  1219. bool first;
  1220. char *kbuf;
  1221. size32_t kbufsz;
  1222. size32_t kbufmax;
  1223. unsigned short kbufcrc;
  1224. __uint64 totalcpu;
  1225. unsigned ndisks;
  1226. int isdisk(unsigned int major, unsigned int minor)
  1227. {
  1228. if (IDE_DISK_MAJOR(major))
  1229. return ((minor&0x3F)==0);
  1230. if (SCSI_DISK_MAJOR(major))
  1231. return ((minor&0x0F)==0);
  1232. if (OTHER_DISK_MAJOR(major))
  1233. return ((minor&0x0F)==0);
  1234. return 0;
  1235. }
  1236. bool getNextCPU()
  1237. {
  1238. oldcpu = newcpu;
  1239. if (!ncpu) {
  1240. unsigned speed;
  1241. getCpuInfo(ncpu, speed);
  1242. if (!ncpu)
  1243. ncpu = 1;
  1244. }
  1245. FILE* cpufp = fopen("/proc/stat", "r");
  1246. if (!cpufp) {
  1247. memset(&cpu,0,sizeof(cpu));
  1248. totalcpu = 0;
  1249. return false;
  1250. }
  1251. char ln[256];
  1252. while (fgets(ln, sizeof(ln), cpufp)) {
  1253. if (strncmp(ln, "cpu ", 4)==0) {
  1254. int items;
  1255. __uint64 nice, irq, softirq;
  1256. items = sscanf(ln,
  1257. "cpu %llu %llu %llu %llu %llu %llu %llu",
  1258. &newcpu.user, &nice,
  1259. &newcpu.system,
  1260. &newcpu.idle,
  1261. &newcpu.iowait,
  1262. &irq, &softirq);
  1263. newcpu.user += nice;
  1264. if (items == 4)
  1265. newcpu.iowait = 0;
  1266. if (items == 7)
  1267. newcpu.system += irq + softirq;
  1268. break;
  1269. }
  1270. }
  1271. fclose(cpufp);
  1272. cpu.user = newcpu.user - oldcpu.user;
  1273. cpu.system = newcpu.system - oldcpu.system;
  1274. cpu.idle = newcpu.idle - oldcpu.idle;
  1275. cpu.iowait = newcpu.iowait - oldcpu.iowait;
  1276. totalcpu = (cpu.user + cpu.system + cpu.idle + cpu.iowait);
  1277. return true;
  1278. }
  1279. bool getDiskInfo()
  1280. {
  1281. char ln[256];
  1282. part_info pi;
  1283. FILE* diskfp = fopen("/proc/diskstats", "r");
  1284. if (!diskfp)
  1285. return false;
  1286. if (!newblkio) {
  1287. nparts = 0;
  1288. while (fgets(ln, sizeof(ln), diskfp)) {
  1289. unsigned reads = 0;
  1290. if (sscanf(ln, "%4d %4d %31s %u", &pi.major, &pi.minor, pi.name, &reads) == 4) {
  1291. unsigned p = 0;
  1292. while ((p<nparts) && (partition[p].major != pi.major || partition[p].minor != pi.minor))
  1293. p++;
  1294. if ((p==nparts) && reads && isdisk(pi.major,pi.minor)) {
  1295. nparts++;
  1296. partition = (part_info *)realloc(partition,nparts*sizeof(part_info));
  1297. partition[p] = pi;
  1298. }
  1299. }
  1300. }
  1301. free(newblkio);
  1302. free(oldblkio);
  1303. newblkio = (blkio_info *)calloc(sizeof(blkio_info),nparts);
  1304. oldblkio = (blkio_info* )calloc(sizeof(blkio_info),nparts);
  1305. }
  1306. rewind(diskfp);
  1307. // could skip lines we know aren't significant here
  1308. while (fgets(ln, sizeof(ln), diskfp)) {
  1309. blkio_info blkio;
  1310. unsigned items = sscanf(ln, "%4d %4d %*s %u %u %llu %u %u %u %llu %u %*u %u %u",
  1311. &pi.major, &pi.minor,
  1312. &blkio.rd_ios, &blkio.rd_merges,
  1313. &blkio.rd_sectors, &blkio.rd_ticks,
  1314. &blkio.wr_ios, &blkio.wr_merges,
  1315. &blkio.wr_sectors, &blkio.wr_ticks,
  1316. &blkio.ticks, &blkio.aveq);
  1317. if (items == 6) {
  1318. // hopefully not this branch!
  1319. blkio.rd_sectors = blkio.rd_merges;
  1320. blkio.wr_sectors = blkio.rd_ticks;
  1321. blkio.rd_ios = 0;
  1322. blkio.rd_merges = 0;
  1323. blkio.rd_ticks = 0;
  1324. blkio.wr_ios = 0;
  1325. blkio.wr_merges = 0;
  1326. blkio.wr_ticks = 0;
  1327. blkio.ticks = 0;
  1328. blkio.aveq = 0;
  1329. items = 12;
  1330. }
  1331. if (items == 12) {
  1332. for (unsigned p = 0; p < nparts; p++) {
  1333. if (partition[p].major == pi.major && partition[p].minor == pi.minor) {
  1334. newblkio[p] = blkio;
  1335. break;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. fclose(diskfp);
  1341. return true;
  1342. }
  1343. bool getNetInfo()
  1344. {
  1345. FILE *netfp = fopen("/proc/net/dev", "r");
  1346. if (!netfp)
  1347. return false;
  1348. char ln[512];
  1349. // Read two lines
  1350. if (!fgets(ln, sizeof(ln), netfp) || !fgets(ln, sizeof(ln), netfp)) {
  1351. fclose(netfp);
  1352. return false;
  1353. }
  1354. unsigned txskip = 2;
  1355. bool hasbyt = false;
  1356. if (strstr(ln,"compressed")) {
  1357. txskip = 4;
  1358. hasbyt = true;
  1359. }
  1360. else if (strstr(ln,"bytes"))
  1361. hasbyt = true;
  1362. while (fgets(ln, sizeof(ln), netfp)) {
  1363. const char *s = ln;
  1364. skipSp(s);
  1365. if (strncmp(s, "eth0:", 5)==0) { // may want eth1 at some point!
  1366. s+=5;
  1367. if (hasbyt) {
  1368. newnet.rxbytes = readDecNum(s);
  1369. skipSp(s);
  1370. }
  1371. else
  1372. newnet.rxbytes = 0;
  1373. newnet.rxpackets = readDecNum(s);
  1374. skipSp(s);
  1375. newnet.rxerrors = readDecNum(s);
  1376. skipSp(s);
  1377. newnet.rxdrops = readDecNum(s);
  1378. skipSp(s);
  1379. while (txskip--) {
  1380. readDecNum(s);
  1381. skipSp(s);
  1382. }
  1383. if (hasbyt) {
  1384. newnet.txbytes = readDecNum(s);
  1385. skipSp(s);
  1386. }
  1387. else
  1388. newnet.txbytes = 0;
  1389. newnet.txpackets = readDecNum(s);
  1390. skipSp(s);
  1391. newnet.txerrors = readDecNum(s);
  1392. skipSp(s);
  1393. newnet.txdrops = readDecNum(s);
  1394. break;
  1395. }
  1396. }
  1397. fclose(netfp);
  1398. return true;
  1399. }
  1400. size32_t getKLog(const char *&data)
  1401. {
  1402. #ifdef __linux__
  1403. if (kbufmax) {
  1404. loop {
  1405. char *newkbuf = (char *)malloc(kbufmax);
  1406. if (!newkbuf)
  1407. break; // OOM - abort logging
  1408. size32_t newkbufsz = klogctl(3,newkbuf,kbufmax);
  1409. if ((int)newkbufsz<0) {
  1410. ERRLOG("klogctl error %d",errno);
  1411. free(newkbuf);
  1412. data = NULL;
  1413. return 0;
  1414. }
  1415. if (newkbufsz<kbufmax) {
  1416. unsigned short crc = chksum16(newkbuf,newkbufsz);
  1417. if (kbuf) {
  1418. if (crc!=kbufcrc) {
  1419. unsigned ofs = 0;
  1420. if ((newkbufsz>=kbufsz)) {
  1421. for (unsigned i=0;i+3<kbufsz;i++) { // not very quick!
  1422. if (memcmp(kbuf+i,newkbuf,kbufsz-i)==0) {
  1423. ofs = kbufsz-i;
  1424. break;
  1425. }
  1426. }
  1427. }
  1428. size32_t ret = newkbufsz-ofs;
  1429. if (ret>3) {
  1430. kbufcrc = crc;
  1431. free(kbuf);
  1432. kbuf = newkbuf;
  1433. kbufsz = newkbufsz;
  1434. data = kbuf+ofs;
  1435. return ret;
  1436. }
  1437. }
  1438. }
  1439. else { // first time {
  1440. kbuf = newkbuf;
  1441. newkbuf = NULL;
  1442. kbufsz = newkbufsz;
  1443. }
  1444. free(newkbuf);
  1445. data = NULL;
  1446. return 0;
  1447. }
  1448. if (kbufmax>0x100000) {
  1449. // don't believe!
  1450. ERRLOG("klogctl buffer too big!");
  1451. free(newkbuf);
  1452. break;
  1453. }
  1454. kbufmax += 0x1000;
  1455. free(newkbuf);
  1456. }
  1457. kbufmax = 0;
  1458. kbufsz = 0;
  1459. free(kbuf);
  1460. kbuf = NULL;
  1461. }
  1462. #endif
  1463. #if defined (__FreeBSD__) || defined (__APPLE__)
  1464. UNIMPLEMENTED;
  1465. #endif
  1466. data = NULL;
  1467. return 0;
  1468. }
  1469. inline double perSec(double v,double deltams)
  1470. {
  1471. return 1000.0*v/deltams;
  1472. }
  1473. public:
  1474. unsigned getCPU()
  1475. {
  1476. if (!getNextCPU())
  1477. return (unsigned)-1;
  1478. if (totalcpu==0)
  1479. return 0;
  1480. unsigned ret = (unsigned)((totalcpu-cpu.idle)*100/totalcpu);
  1481. if (ret>100)
  1482. ret = 100;
  1483. return ret;
  1484. }
  1485. CExtendedStats(bool printklog)
  1486. {
  1487. partition = (part_info *)malloc(sizeof(part_info));
  1488. nparts = 0;
  1489. newblkio = NULL;
  1490. oldblkio = NULL;
  1491. first = true;
  1492. ncpu = 0;
  1493. kbuf = NULL;
  1494. kbufsz = 0;
  1495. kbufcrc = 0;
  1496. memset(&oldcpu, 0, sizeof(oldcpu));
  1497. memset(&newcpu, 0, sizeof(newcpu));
  1498. memset(&cpu, 0, sizeof(cpu));
  1499. totalcpu = 0;
  1500. numcpu = 0;
  1501. memset(&oldnet, 0, sizeof(oldnet));
  1502. memset(&newnet, 0, sizeof(newnet));
  1503. ndisks = 0;
  1504. if (printklog)
  1505. kbufmax = 0x1000;
  1506. else
  1507. kbufmax = 0;
  1508. }
  1509. ~CExtendedStats()
  1510. {
  1511. free(partition);
  1512. free(kbuf);
  1513. }
  1514. bool getLine(StringBuffer &out)
  1515. {
  1516. blkio_info *t = oldblkio;
  1517. oldblkio = newblkio;
  1518. newblkio = t;
  1519. oldnet = newnet;
  1520. #ifdef USE_OLD_PU
  1521. if (!getNextCPU())
  1522. return false; // required
  1523. #endif
  1524. bool gotdisk = getDiskInfo()&&nparts;
  1525. bool gotnet = getNetInfo();
  1526. if (first) {
  1527. first = false;
  1528. return false;
  1529. }
  1530. double deltams = ((double)totalcpu*1000) / ncpu / HZ;
  1531. if (deltams<10)
  1532. return false;
  1533. if (gotdisk) {
  1534. if (out.length()&&(out.charAt(out.length()-1)!=' '))
  1535. out.append(' ');
  1536. out.append("DSK: ");
  1537. for (unsigned p = 0; p < nparts; p++) {
  1538. unsigned rd_ios = newblkio[p].rd_ios - oldblkio[p].rd_ios;
  1539. __uint64 rd_sectors = newblkio[p].rd_sectors - oldblkio[p].rd_sectors;
  1540. unsigned wr_ios = newblkio[p].wr_ios - oldblkio[p].wr_ios;
  1541. __uint64 wr_sectors = newblkio[p].wr_sectors - oldblkio[p].wr_sectors;
  1542. unsigned ticks = newblkio[p].ticks - oldblkio[p].ticks;
  1543. unsigned busy = (unsigned)(100*ticks/deltams);
  1544. if (busy>100)
  1545. busy = 100;
  1546. out.appendf("[%s] r/s=%0.1f kr/s=%0.1f w/s=%0.1f kw/s=%0.1f bsy=%d",
  1547. partition[p].name,
  1548. perSec(rd_ios,deltams),
  1549. perSec(rd_sectors,deltams)/2.0,
  1550. perSec(wr_ios,deltams),
  1551. perSec(wr_sectors,deltams)/2.0,
  1552. busy);
  1553. out.append(' ');
  1554. }
  1555. }
  1556. if (gotnet) {
  1557. out.append("NIC: ");
  1558. __uint64 rxbytes = newnet.rxbytes-oldnet.rxbytes;
  1559. __uint64 rxpackets = newnet.rxpackets-oldnet.rxpackets;
  1560. __uint64 txbytes = newnet.txbytes-oldnet.txbytes;
  1561. __uint64 txpackets = newnet.txpackets-oldnet.txpackets;
  1562. out.appendf("rxp/s=%0.1f rxk/s=%0.1f txp/s=%0.1f txk/s=%0.1f",
  1563. perSec(rxpackets,deltams),
  1564. perSec(rxbytes/1024.0,deltams),
  1565. perSec(txpackets,deltams),
  1566. perSec(txbytes/1024.0,deltams));
  1567. out.append(' ');
  1568. }
  1569. if (totalcpu)
  1570. out.appendf("CPU: usr=%d sys=%d iow=%d idle=%d", (unsigned)(cpu.user*100/totalcpu), (unsigned)(cpu.system*100/totalcpu), (unsigned)(cpu.iowait*100/totalcpu), (unsigned)(cpu.idle*100/totalcpu));
  1571. return true;
  1572. }
  1573. #define KERN_EMERG "<0>" // system is unusable
  1574. #define KERN_ALERT "<1>" // action must be taken immediately
  1575. #define KERN_CRIT "<2>" // critical conditions
  1576. #define KERN_ERR "<3>" // error conditions
  1577. #define KERN_WARNING "<4>" // warning conditions
  1578. #define KERN_NOTICE "<5>" // normal but significant condition
  1579. #define KERN_INFO "<6>" // informational
  1580. #define KERN_DEBUG "<7>" // debug-level messages
  1581. #define KMSGTEST(S) if (memcmp(p,S,3)==0) ln.append(#S)
  1582. void printKLog()
  1583. {
  1584. const char *p;
  1585. size32_t sz = getKLog(p);
  1586. StringBuffer ln;
  1587. const char *e = p+sz;
  1588. while (p!=e) {
  1589. if (*p=='<') {
  1590. ln.clear();
  1591. KMSGTEST(KERN_EMERG);
  1592. else KMSGTEST(KERN_ALERT);
  1593. else KMSGTEST(KERN_CRIT);
  1594. else KMSGTEST(KERN_ERR);
  1595. else KMSGTEST(KERN_WARNING);
  1596. else KMSGTEST(KERN_NOTICE);
  1597. else KMSGTEST(KERN_INFO);
  1598. else KMSGTEST(KERN_DEBUG);
  1599. else {
  1600. ln.append("KERN_UNKNOWN");
  1601. p -= 3;
  1602. }
  1603. p += 3;
  1604. ln.append(": ");
  1605. while ((p!=e)&&(*p!='\n'))
  1606. ln.append(*(p++));
  1607. PROGLOG("%s",ln.str());
  1608. }
  1609. while ((p!=e)&&(*p!='\n'))
  1610. p++;
  1611. if (p!=e)
  1612. p++;
  1613. }
  1614. }
  1615. };
  1616. #endif
  1617. static class CMemoryUsageReporter: public Thread
  1618. {
  1619. bool term;
  1620. unsigned interval;
  1621. Semaphore sem;
  1622. PerfMonMode traceMode;
  1623. IPerfMonHook * hook;
  1624. unsigned latestCPU;
  1625. double dbIdleTime;
  1626. double dbSystemTime;
  1627. #ifdef _WIN32
  1628. PROCNTQSI NtQuerySystemInformation;
  1629. PROCNTQIP NtQueryInformationProcess;
  1630. PROCNTGST pGetSystemTimes;
  1631. SYSTEM_BASIC_INFORMATION SysBaseInfo;
  1632. LONG status;
  1633. LARGE_INTEGER liOldIdleTime;
  1634. LARGE_INTEGER liOldSystemTime;
  1635. #else
  1636. double OldIdleTime;
  1637. double OldSystemTime;
  1638. CProcessMonitor procmon;
  1639. CExtendedStats extstats;
  1640. #endif
  1641. StringBuffer primaryfs;
  1642. StringBuffer secondaryfs;
  1643. CriticalSection sect; // for getSystemTraceInfo
  1644. public:
  1645. CMemoryUsageReporter(unsigned _interval, PerfMonMode _traceMode, IPerfMonHook * _hook, bool printklog)
  1646. : Thread("CMemoryUsageReporter"), traceMode(_traceMode)
  1647. #ifndef _WIN32
  1648. , extstats(printklog)
  1649. #endif
  1650. {
  1651. interval = _interval;
  1652. hook = _hook;
  1653. term = false;
  1654. latestCPU = 0;
  1655. #ifdef _WIN32
  1656. memset(&liOldIdleTime,0,sizeof(liOldIdleTime));
  1657. memset(&liOldSystemTime,0,sizeof(liOldSystemTime));
  1658. NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
  1659. GetModuleHandle("ntdll"),
  1660. "NtQuerySystemInformation"
  1661. );
  1662. NtQueryInformationProcess = (PROCNTQIP)GetProcAddress(
  1663. GetModuleHandle("ntdll"),
  1664. "NtQueryInformationProcess"
  1665. );
  1666. // GetSystemTimes not available on earlier versions of Windows - NtQuerySystemInformation not consistent on later ones. So use GetSystemTimes if available
  1667. pGetSystemTimes = (PROCNTGST)GetProcAddress(
  1668. GetModuleHandle("kernel32"),
  1669. "GetSystemTimes"
  1670. );
  1671. NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
  1672. dbIdleTime = 0;
  1673. primaryfs.append("C:");
  1674. #else
  1675. FILE* procfp;
  1676. procfp = fopen("/proc/uptime", "r");
  1677. if (procfp) {
  1678. fscanf(procfp, "%lf %lf\n", &OldSystemTime, &OldIdleTime);
  1679. fclose(procfp);
  1680. }
  1681. else
  1682. OldSystemTime = 0;
  1683. primaryfs.append("/");
  1684. #endif
  1685. }
  1686. void setPrimaryFileSystem(char const * _primaryfs)
  1687. {
  1688. primaryfs.clear();
  1689. if(_primaryfs)
  1690. primaryfs.append(_primaryfs);
  1691. }
  1692. void setSecondaryFileSystem(char const * _secondaryfs)
  1693. {
  1694. secondaryfs.clear();
  1695. if(_secondaryfs)
  1696. secondaryfs.append(_secondaryfs);
  1697. }
  1698. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  1699. {
  1700. CriticalBlock block(sect);
  1701. #ifdef _WIN32
  1702. if (pGetSystemTimes) {
  1703. LARGE_INTEGER idle, kernel, user;
  1704. pGetSystemTimes(&idle, &kernel, &user);
  1705. // note - kernel time seems to include idle time
  1706. if(liOldIdleTime.QuadPart != 0) {
  1707. // CurrentValue = NewValue - OldValue
  1708. dbIdleTime = Li2Double(idle) - Li2Double(liOldIdleTime);
  1709. dbSystemTime = (Li2Double(kernel) + Li2Double(user)) - Li2Double(liOldSystemTime);
  1710. // CurrentCpuIdle = IdleTime / SystemTime
  1711. dbIdleTime = dbIdleTime / dbSystemTime;
  1712. // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
  1713. latestCPU = (unsigned) (100.0 - dbIdleTime * 100.0 + 0.5);
  1714. }
  1715. liOldIdleTime = idle;
  1716. liOldSystemTime.QuadPart = user.QuadPart + kernel.QuadPart;
  1717. } else {
  1718. SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
  1719. SYSTEM_TIME_INFORMATION SysTimeInfo;
  1720. NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
  1721. NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
  1722. if(liOldIdleTime.QuadPart != 0) {
  1723. // CurrentValue = NewValue - OldValue
  1724. dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
  1725. dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
  1726. // CurrentCpuIdle = IdleTime / SystemTime
  1727. dbIdleTime = dbIdleTime / dbSystemTime;
  1728. // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
  1729. latestCPU = (unsigned) (100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5);
  1730. }
  1731. liOldIdleTime = SysPerfInfo.liIdleTime;
  1732. liOldSystemTime = SysTimeInfo.liKeSystemTime;
  1733. }
  1734. MEMORYSTATUSEX memstatus;
  1735. memstatus.dwLength = sizeof(memstatus);
  1736. GlobalMemoryStatusEx(&memstatus);
  1737. DWORDLONG vmTotal = memstatus.ullTotalVirtual;
  1738. DWORDLONG vmAvail = memstatus.ullAvailVirtual;
  1739. DWORDLONG vmInUse = vmTotal - vmAvail;
  1740. DWORDLONG physTotal = memstatus.ullAvailPhys;
  1741. DWORDLONG physAvail = memstatus.ullTotalPhys;
  1742. DWORDLONG physInUse = physTotal - physAvail;
  1743. ULARGE_INTEGER diskAvailStruct;
  1744. ULARGE_INTEGER diskTotalStruct;
  1745. unsigned __int64 firstDriveTotal = 0;
  1746. unsigned __int64 firstDriveInUse = 0;
  1747. unsigned __int64 secondDriveTotal = 0;
  1748. unsigned __int64 secondDriveInUse = 0;
  1749. if(primaryfs.length())
  1750. {
  1751. diskAvailStruct.QuadPart = 0;
  1752. diskTotalStruct.QuadPart = 0;
  1753. GetDiskFreeSpaceEx(primaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  1754. firstDriveTotal = diskTotalStruct.QuadPart;
  1755. firstDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  1756. }
  1757. if(secondaryfs.length())
  1758. {
  1759. diskAvailStruct.QuadPart = 0;
  1760. diskTotalStruct.QuadPart = 0;
  1761. GetDiskFreeSpaceEx(secondaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  1762. secondDriveTotal = diskTotalStruct.QuadPart;
  1763. secondDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  1764. }
  1765. if(hook)
  1766. hook->processPerfStats(latestCPU, (unsigned)(vmInUse/1024), (unsigned)(vmTotal/1024), firstDriveInUse, firstDriveTotal, secondDriveInUse, secondDriveTotal, getThreadCount());
  1767. if(!mode)
  1768. return;
  1769. if(mode & PerfMonProcMem)
  1770. {
  1771. str.appendf("PU=%3d%%",latestCPU);
  1772. #if 0
  1773. VM_COUNTERS vmc;
  1774. DWORD dwSize = 0;
  1775. NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  1776. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmc.WorkingSetSize*100/(__int64)vmTotal));
  1777. #else
  1778. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmInUse*100/(__int64)vmTotal));
  1779. str.appendf(" PY=%3u%%",(unsigned)((__int64)physInUse*100/(__int64)physTotal));
  1780. if (hook)
  1781. hook->extraLogging(str);
  1782. #ifdef _USE_MALLOC_HOOK
  1783. if (totalMem)
  1784. str.appendf(" TM=%"I64F"d",totalMem);
  1785. #endif
  1786. #endif
  1787. }
  1788. if(mode & PerfMonPackets)
  1789. {
  1790. unsigned tx, rx;
  1791. if(getPacketStats(tx, rx))
  1792. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  1793. else
  1794. str.appendf(" ");
  1795. }
  1796. if(mode & PerfMonDiskUsage)
  1797. {
  1798. if(firstDriveTotal) str.appendf(" D1=%3u%%", (unsigned)(firstDriveInUse*100/firstDriveTotal));
  1799. if(secondDriveTotal) str.appendf(" D2=%3u%%", (unsigned)(secondDriveInUse*100/secondDriveTotal));
  1800. }
  1801. if(mode & PerfMonExtended)
  1802. {
  1803. __IO_COUNTERS ioc;
  1804. KERNEL_USER_TIMES kut;
  1805. POOLED_USAGE_AND_LIMITS put;
  1806. VM_COUNTERS vmc;
  1807. DWORD dwSize;
  1808. DWORD dwHandles;
  1809. dwSize = 0;
  1810. NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  1811. dwHandles = 0;
  1812. dwSize = 0;
  1813. NtQueryInformationProcess(GetCurrentProcess(), ProcessHandleCount, &dwHandles, sizeof(dwHandles), &dwSize);
  1814. dwSize = 0;
  1815. NtQueryInformationProcess(GetCurrentProcess(), ProcessIoCounters, &ioc, sizeof(ioc), &dwSize);
  1816. dwSize = 0;
  1817. NtQueryInformationProcess(GetCurrentProcess(), ProcessTimes, &kut, sizeof(kut), &dwSize);
  1818. dwSize = 0;
  1819. NtQueryInformationProcess(GetCurrentProcess(), ProcessPooledUsageAndLimits, &put, sizeof(put), &dwSize);
  1820. str.appendf(" WS=%10u ",vmc.WorkingSetSize);
  1821. str.appendf("PP=%10u ",put.PagedPoolUsage);
  1822. str.appendf("NP=%10u ",put.NonPagedPoolUsage);
  1823. str.appendf("HC=%5u ",dwHandles);
  1824. str.appendf("TC=%5u ",getThreadCount());
  1825. str.appendf("IR=%10u ",(unsigned)(ioc.ReadTransferCount/1024));
  1826. str.appendf("IW=%10u ",(unsigned)(ioc.WriteTransferCount/1024));
  1827. str.appendf("IO=%10u ",(unsigned)(ioc.OtherTransferCount/1024));
  1828. str.appendf("KT=%16"I64F"u ",kut.KernelTime);
  1829. str.appendf("UT=%16"I64F"u ",kut.UserTime);
  1830. }
  1831. #else
  1832. bool outofhandles = false;
  1833. #ifdef USE_OLD_PU
  1834. FILE* procfp = fopen("/proc/uptime", "r");
  1835. if (procfp) {
  1836. fscanf(procfp, "%lf %lf\n", &dbSystemTime, &dbIdleTime);
  1837. fclose(procfp);
  1838. outofhandles = false;
  1839. }
  1840. latestCPU = unsigned(100.0 - (dbIdleTime - OldIdleTime)*100.0/(dbSystemTime - OldSystemTime) + 0.5);
  1841. OldSystemTime = dbSystemTime;
  1842. OldIdleTime = dbIdleTime;
  1843. #else
  1844. latestCPU = extstats.getCPU();
  1845. if (latestCPU==(unsigned)-1) {
  1846. outofhandles = true;
  1847. latestCPU = 0;
  1848. }
  1849. #endif
  1850. unsigned __int64 primaryfsTotal = 0;
  1851. unsigned __int64 primaryfsInUse = 0;
  1852. unsigned __int64 secondaryfsTotal = 0;
  1853. unsigned __int64 secondaryfsInUse = 0;
  1854. if(primaryfs.length())
  1855. getDiskUsage(primaryfs.str(), primaryfsTotal, primaryfsInUse);
  1856. if(secondaryfs.length())
  1857. getDiskUsage(secondaryfs.str(), secondaryfsTotal, secondaryfsInUse);
  1858. if(!mode) return;
  1859. unsigned memused=0;
  1860. unsigned memtot=0;
  1861. if(mode & PerfMonProcMem)
  1862. {
  1863. if (!outofhandles)
  1864. str.appendf("PU=%3d%% ", latestCPU);
  1865. else
  1866. str.appendf("PU=OOH ");
  1867. getMemStats(str,memused,memtot);
  1868. if (hook)
  1869. hook->extraLogging(str);
  1870. procmon.printBusy(latestCPU,str);
  1871. }
  1872. if (hook) {
  1873. if (!memtot) {
  1874. unsigned mu;
  1875. unsigned ma;
  1876. unsigned mt;
  1877. unsigned st;
  1878. unsigned su;
  1879. getMemUsage(mu,ma,mt,st,su);
  1880. memused = mu+su;
  1881. memtot = mt+st;
  1882. }
  1883. hook->processPerfStats(latestCPU, memused, memtot, primaryfsInUse, primaryfsTotal, secondaryfsInUse, secondaryfsTotal, getThreadCount());
  1884. }
  1885. if(mode & PerfMonPackets)
  1886. {
  1887. unsigned tx, rx;
  1888. if(getPacketStats(tx, rx))
  1889. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  1890. else
  1891. str.appendf(" ");
  1892. }
  1893. if(mode & PerfMonDiskUsage)
  1894. {
  1895. if(primaryfsTotal) str.appendf(" D1=%3u%%", (unsigned)(primaryfsInUse*100/primaryfsTotal));
  1896. if(secondaryfsTotal) str.appendf(" D2=%3u%%", (unsigned)(secondaryfsInUse*100/secondaryfsTotal));
  1897. }
  1898. if(mode & PerfMonExtended)
  1899. {
  1900. extstats.getLine(str);
  1901. }
  1902. #endif
  1903. }
  1904. #define NAMEDCOUNTPERIOD 60*30
  1905. int run()
  1906. {
  1907. StringBuffer str;
  1908. getSystemTraceInfo(str, traceMode&~PerfMonExtended); // initializes the values so that first one we print is meaningful rather than always saying PU=0%
  1909. CTimeMon tm(NAMEDCOUNTPERIOD*1000);
  1910. while (!term) {
  1911. if (sem.wait(interval))
  1912. break;
  1913. str.clear();
  1914. getSystemTraceInfo(str, traceMode&~PerfMonExtended);
  1915. #ifdef NAMEDCOUNTS
  1916. if (tm.timedout())
  1917. {
  1918. dumpNamedCounts(str.newline());
  1919. tm.reset(NAMEDCOUNTPERIOD*1000);
  1920. }
  1921. #endif
  1922. if(traceMode&&str.length()) {
  1923. LOG(MCdebugInfo, unknownJob, "SYS: %s", str.str());
  1924. #ifndef _WIN32
  1925. if (traceMode&PerfMonExtended) {
  1926. if (extstats.getLine(str.clear()))
  1927. LOG(MCdebugInfo, unknownJob, "%s", str.str());
  1928. extstats.printKLog();
  1929. }
  1930. #endif
  1931. }
  1932. }
  1933. return 0;
  1934. }
  1935. void stop()
  1936. {
  1937. term = true;
  1938. sem.signal();
  1939. join();
  1940. }
  1941. unsigned queryLatestCPU() const
  1942. {
  1943. return latestCPU;
  1944. }
  1945. } *MemoryUsageReporter=NULL;
  1946. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  1947. {
  1948. if (!MemoryUsageReporter)
  1949. MemoryUsageReporter = new CMemoryUsageReporter(1000, mode, 0, false);
  1950. MemoryUsageReporter->getSystemTraceInfo(str, mode);
  1951. }
  1952. void startPerformanceMonitor(unsigned interval, PerfMonMode traceMode, IPerfMonHook * hook)
  1953. {
  1954. stopPerformanceMonitor();
  1955. if (!MemoryUsageReporter) {
  1956. MemoryUsageReporter = new CMemoryUsageReporter(interval, traceMode, hook, (traceMode&PerfMonExtended)!=0);
  1957. MemoryUsageReporter->start();
  1958. }
  1959. }
  1960. void stopPerformanceMonitor()
  1961. {
  1962. if (MemoryUsageReporter) {
  1963. MemoryUsageReporter->stop();
  1964. delete MemoryUsageReporter;
  1965. MemoryUsageReporter = NULL;
  1966. }
  1967. }
  1968. void setPerformanceMonitorPrimaryFileSystem(char const * fs)
  1969. {
  1970. if(MemoryUsageReporter)
  1971. MemoryUsageReporter->setPrimaryFileSystem(fs);
  1972. }
  1973. void setPerformanceMonitorSecondaryFileSystem(char const * fs)
  1974. {
  1975. if(MemoryUsageReporter)
  1976. MemoryUsageReporter->setSecondaryFileSystem(fs);
  1977. }
  1978. unsigned getLatestCPUUsage()
  1979. {
  1980. if (MemoryUsageReporter)
  1981. return MemoryUsageReporter->queryLatestCPU();
  1982. else
  1983. return 0;
  1984. }
  1985. void getHardwareInfo(HardwareInfo &hdwInfo, const char *primDiskPath, const char *secDiskPath)
  1986. {
  1987. memset(&hdwInfo, 0, sizeof(HardwareInfo));
  1988. getCpuInfo(hdwInfo.numCPUs, hdwInfo.CPUSpeed);
  1989. #ifdef _WIN32
  1990. MEMORYSTATUS memstatus;
  1991. GlobalMemoryStatus(&memstatus);
  1992. hdwInfo.totalMemory = memstatus.dwTotalPhys / (1024*1024); // in MB
  1993. ULARGE_INTEGER diskAvailStruct;
  1994. ULARGE_INTEGER diskTotalStruct;
  1995. diskTotalStruct.QuadPart = 0;
  1996. GetDiskFreeSpaceEx(primDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  1997. hdwInfo.primDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  1998. hdwInfo.primFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  1999. if (secDiskPath)
  2000. {
  2001. diskTotalStruct.QuadPart = 0;
  2002. GetDiskFreeSpaceEx(secDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  2003. hdwInfo.secDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  2004. hdwInfo.secFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  2005. }
  2006. // MORE: Find win32 call for NIC speed
  2007. #else // linux
  2008. unsigned memUsed, memActive, memSwap, memSwapUsed;
  2009. unsigned __int64 diskSize;
  2010. unsigned __int64 diskUsed;
  2011. getMemUsage(memUsed, memActive, hdwInfo.totalMemory, memSwap, memSwapUsed);
  2012. hdwInfo.totalMemory /= 1024; // in MB
  2013. getDiskUsage(primDiskPath, diskSize, diskUsed);
  2014. hdwInfo.primDiskSize = diskSize / (1024*1024*1024); // in GB
  2015. hdwInfo.primFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  2016. if (secDiskPath)
  2017. {
  2018. getDiskUsage(secDiskPath, diskSize, diskUsed);
  2019. hdwInfo.secDiskSize = diskSize / (1024*1024*1024); // in GB
  2020. hdwInfo.secFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  2021. }
  2022. // MORE: Find linux call for NIC speed -- mii-tool does not seem to work on our roxie clusters?
  2023. #endif
  2024. }
  2025. //===========================================================================
  2026. enum SegTypes {
  2027. segtype_free, //
  2028. segtype_heap, // rw-p named [heap]
  2029. segtype_data, // rw-p unnamed
  2030. segtype_guard, // ---p unnamed/named
  2031. segtype_stack, // rwxp
  2032. segtype_qlibcode, // r-xp named */lib200
  2033. segtype_qlibdata, // rw-p named */lib200
  2034. segtype_libcode, // r-xp named *
  2035. segtype_libdata, // rw-p named *
  2036. segtype_pstack, // rwxp named [stack]
  2037. segtype_const, // r--p
  2038. segtype_null // must be last
  2039. };
  2040. struct SegTypeRec
  2041. {
  2042. offset_t total;
  2043. unsigned n;
  2044. offset_t largest;
  2045. };
  2046. const char *PROCMAPHEADER =
  2047. "FREE,NFREE,MAXFREE,HEAP,STACK,NSTACKS,DATA,NDATA,MAXDATA,LIBDATA,QUERYDATA,MAXQUERYDATA,LIBCODE,QUERYCODE,MAXQLIBCODE";
  2048. class CProcReader
  2049. {
  2050. // Cant use JFile for /proc filesystem as seek doesn't work
  2051. public:
  2052. char ln [512];
  2053. FILE *file;
  2054. const char *buf;
  2055. size32_t bufsize;
  2056. CProcReader(const char *filename,const void *_buf,size32_t _buflen)
  2057. {
  2058. buf = (const char *)_buf;
  2059. bufsize = buf?_buflen:0;
  2060. file = buf?NULL:fopen(filename,"r");
  2061. }
  2062. ~CProcReader()
  2063. {
  2064. if (file)
  2065. fclose(file);
  2066. }
  2067. bool nextln()
  2068. {
  2069. if (buf) {
  2070. if (bufsize&&*buf) {
  2071. unsigned i = 0;
  2072. while (bufsize&&(i<sizeof(ln)-1)&&*buf&&(*buf!=10)&&(*buf!=13)) {
  2073. ln[i++] = *(buf++);
  2074. bufsize--;
  2075. }
  2076. ln[i] = 0;
  2077. while (bufsize&&*buf&&((*buf==10)||(*buf==13))) {
  2078. buf++;
  2079. bufsize--;
  2080. }
  2081. return true;
  2082. }
  2083. }
  2084. else if (file&&fgets (ln, sizeof(ln), file)) {
  2085. unsigned i = strlen(ln);
  2086. while (i&&((ln[i-1]==10)||(ln[i-1]==13)))
  2087. i--;
  2088. ln[i] = 0;
  2089. return true;
  2090. }
  2091. if (file) {
  2092. fclose(file);
  2093. file = NULL;
  2094. }
  2095. return false;
  2096. }
  2097. void dump(bool useprintf)
  2098. {
  2099. while (nextln()) {
  2100. if (useprintf)
  2101. printf("%s\n",ln);
  2102. else
  2103. PROGLOG("%s",ln);
  2104. }
  2105. }
  2106. };
  2107. void printProcMap(const char *fn, bool printbody, bool printsummary, StringBuffer *lnout, MemoryBuffer *mb, bool useprintf)
  2108. {
  2109. CProcReader reader(fn,mb?mb->toByteArray():NULL,mb?mb->length():0);
  2110. unsigned i;
  2111. SegTypeRec recs[segtype_null];
  2112. memset(&recs,0,sizeof(recs));
  2113. offset_t last=0;
  2114. if (printbody) {
  2115. if (useprintf)
  2116. printf("START,END,SIZE,OFFSET,PERMS,PATH\n");
  2117. else
  2118. PROGLOG("START,END,SIZE,OFFSET,PERMS,PATH");
  2119. }
  2120. while (reader.nextln()) {
  2121. const char *ln = reader.ln;
  2122. unsigned n=0;
  2123. if (*ln) {
  2124. offset_t start = readHexNum(ln);
  2125. if (last&&(last!=start)) {
  2126. recs[segtype_free].n++;
  2127. offset_t ssz = start-last;
  2128. recs[segtype_free].total += ssz;
  2129. if (ssz>recs[segtype_free].largest)
  2130. recs[segtype_free].largest = ssz;
  2131. }
  2132. if (*ln=='-') {
  2133. ln++;
  2134. offset_t end = readHexNum(ln);
  2135. char perms[5];
  2136. skipSp(ln);
  2137. for (i=0;i<4;)
  2138. if (*ln)
  2139. perms[i++] = *(ln++);
  2140. perms[i] = 0;
  2141. skipSp(ln);
  2142. offset_t offset = readHexNum(ln);
  2143. skipSp(ln);
  2144. char dev[6];
  2145. for (i=0;i<5;)
  2146. if (*ln)
  2147. dev[i++] = *(ln++);
  2148. dev[i] = 0;
  2149. skipSp(ln);
  2150. unsigned inode = (unsigned)readDecNum(ln);
  2151. skipSp(ln);
  2152. const char *path = ln;
  2153. if (printbody) {
  2154. if (useprintf)
  2155. printf("%08"I64F"x,%08"I64F"x,%"I64F"d,%08"I64F"x,%s,%s\n",start,end,(offset_t)(end-start),offset,perms,path);
  2156. else
  2157. PROGLOG("%08"I64F"x,%08"I64F"x,%"I64F"d,%08"I64F"x,%s,%s",start,end,(offset_t)(end-start),offset,perms,path);
  2158. }
  2159. SegTypes t;
  2160. if (strcmp(perms,"---p")==0)
  2161. t = segtype_guard;
  2162. else if (strcmp(perms,"rwxp")==0) {
  2163. if (memicmp(ln,"[stack]",7)==0)
  2164. t = segtype_pstack;
  2165. else
  2166. t = segtype_stack;
  2167. }
  2168. else if (strcmp(perms,"rw-p")==0) {
  2169. if (memicmp(ln,"[heap]",6)==0)
  2170. t = segtype_heap;
  2171. else if (strstr(ln,"/libW200"))
  2172. t = segtype_qlibdata;
  2173. else if (*ln)
  2174. t = segtype_libdata;
  2175. else
  2176. t = segtype_data;
  2177. }
  2178. else if (strcmp(perms,"r-xp")==0) {
  2179. if (strstr(ln,"/libW200"))
  2180. t = segtype_qlibcode;
  2181. else if (*ln)
  2182. t = segtype_libcode;
  2183. }
  2184. else if (strcmp(perms,"r--p")==0)
  2185. t = segtype_const;
  2186. else {
  2187. ERRLOG("%s - unknown perms",perms);
  2188. continue;
  2189. }
  2190. recs[t].n++;
  2191. offset_t ssz = end-start;
  2192. recs[t].total += ssz;
  2193. if (ssz>recs[t].largest)
  2194. recs[t].largest = ssz;
  2195. n++;
  2196. last = end;
  2197. #ifndef __64BIT__
  2198. if ((end<0xffffffff)&&(end>=0xc0000000)) // rest is OS (32-bit only)
  2199. break;
  2200. #endif
  2201. }
  2202. }
  2203. }
  2204. if (printsummary||lnout) {
  2205. StringBuffer tln;
  2206. if (lnout==NULL)
  2207. lnout = &tln;
  2208. lnout->appendf("%"I64F"u," // total
  2209. "%u," // n
  2210. "%"I64F"u," // largest
  2211. "%"I64F"u," // total
  2212. "%"I64F"u," // total
  2213. "%u," // n
  2214. "%"I64F"u," // total
  2215. "%u," // n
  2216. "%"I64F"u," // largest
  2217. "%"I64F"u," // total
  2218. "%"I64F"u," // total
  2219. "%"I64F"u," // largest
  2220. "%"I64F"u," // total
  2221. "%"I64F"u," // total
  2222. "%"I64F"u" // largest
  2223. ,
  2224. recs[segtype_free].total,
  2225. recs[segtype_free].n,
  2226. recs[segtype_free].largest,
  2227. recs[segtype_heap].total,
  2228. recs[segtype_stack].total,
  2229. recs[segtype_stack].n,
  2230. recs[segtype_data].total,
  2231. recs[segtype_data].n,
  2232. recs[segtype_data].largest,
  2233. recs[segtype_libdata].total,
  2234. recs[segtype_qlibdata].total,
  2235. recs[segtype_qlibdata].largest,
  2236. recs[segtype_libcode].total,
  2237. recs[segtype_qlibcode].total,
  2238. recs[segtype_qlibcode].largest
  2239. );
  2240. if (printsummary) {
  2241. if (useprintf)
  2242. printf("%s\n%s\n",PROCMAPHEADER,tln.str());
  2243. else {
  2244. PROGLOG("%s",PROCMAPHEADER);
  2245. PROGLOG("%s",tln.str());
  2246. }
  2247. }
  2248. }
  2249. }
  2250. #ifdef _WIN32
  2251. // stubs
  2252. void PrintMemoryReport(bool full)
  2253. {
  2254. StringBuffer s;
  2255. getSystemTraceInfo(s,PerfMonProcMem);
  2256. PROGLOG("%s",s.str());
  2257. }
  2258. #else
  2259. void PrintMemoryReport(bool full)
  2260. {
  2261. // may be very close to oom so protect against re-entry
  2262. static int recurse=0;
  2263. if (recurse++==0) {
  2264. try {
  2265. printProcMap("/proc/self/maps",full,true,NULL,NULL,false);
  2266. }
  2267. catch (IException *e) {
  2268. e->Release();
  2269. }
  2270. catch (...) {
  2271. }
  2272. try {
  2273. PROGLOG("/proc/meminfo:");
  2274. CProcReader reader("/proc/meminfo",NULL,0);
  2275. reader.dump(false);
  2276. }
  2277. catch (IException *e) {
  2278. e->Release();
  2279. }
  2280. catch (...) {
  2281. }
  2282. try {
  2283. PROGLOG("/proc/self/status:");
  2284. CProcReader reader("/proc/self/status",NULL,0);
  2285. reader.dump(false);
  2286. }
  2287. catch (IException *e) {
  2288. e->Release();
  2289. }
  2290. catch (...) {
  2291. }
  2292. try {
  2293. StringBuffer s;
  2294. getSystemTraceInfo(s,PerfMonProcMem);
  2295. PROGLOG("%s",s.str());
  2296. PROGLOG("===============================================================");
  2297. }
  2298. catch (IException *e) {
  2299. e->Release();
  2300. }
  2301. catch (...) {
  2302. }
  2303. }
  2304. recurse--;
  2305. }
  2306. #endif
  2307. //===========================================================================
  2308. #ifdef LEAK_CHECK
  2309. #ifdef _WIN32
  2310. LeakChecker::LeakChecker(const char * _title) : title(_title)
  2311. {
  2312. _CrtMemCheckpoint(&oldMemState);
  2313. }
  2314. LeakChecker::~LeakChecker()
  2315. {
  2316. _CrtMemState newMemState, diffMemState;
  2317. _CrtMemCheckpoint(&newMemState);
  2318. if(_CrtMemDifference(&diffMemState, &oldMemState, &newMemState))
  2319. {
  2320. _RPT1(_CRT_WARN, "----- Memory leaks in '%s' -----\n", title);
  2321. _CrtMemDumpStatistics(&diffMemState);
  2322. _CrtMemDumpAllObjectsSince(&oldMemState);
  2323. _RPT0(_CRT_WARN, "----- End of leaks -----\n");
  2324. }
  2325. }
  2326. static char _logFile[255]; // used to hold last file name of log file for memory leak logging
  2327. static FILE *_logHandle = NULL;
  2328. _CRT_REPORT_HOOK oldReport;
  2329. static int MemoryLeakReportHook(int nRptType,char *szMsg,int *retVal)
  2330. {
  2331. if (szMsg && *szMsg)
  2332. {
  2333. if (_logHandle)
  2334. fprintf(_logHandle, szMsg);
  2335. if (*_logFile)
  2336. {
  2337. #if 1
  2338. // this works better in VS 2008 libraries (which fault in fopen)
  2339. int handle = _open(_logFile, O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);
  2340. _lseek(handle,0,SEEK_END);
  2341. _write(handle,szMsg,strlen(szMsg));
  2342. _close(handle);
  2343. #else
  2344. FILE *handle = fopen(_logFile, "a");
  2345. fprintf(handle, szMsg);
  2346. fclose(handle);
  2347. #endif
  2348. }
  2349. }
  2350. if (oldReport)
  2351. return oldReport(nRptType,szMsg,retVal);
  2352. else
  2353. return false;
  2354. }
  2355. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  2356. {
  2357. oldReport = _CrtSetReportHook(MemoryLeakReportHook);
  2358. return 1;
  2359. }
  2360. void logLeaks (const char *logFile)
  2361. {
  2362. if (logFile)
  2363. strncpy(_logFile, logFile, sizeof(_logFile));
  2364. else
  2365. _logFile[0] = 0;
  2366. }
  2367. void logLeaks (FILE *logHandle)
  2368. {
  2369. _logHandle = logHandle;
  2370. }
  2371. #else
  2372. #endif
  2373. #endif
  2374. #if !defined(USING_MPATROL) && defined(WIN32) && defined(_DEBUG)
  2375. void jlib_decl enableMemLeakChecking(bool enable)
  2376. {
  2377. int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  2378. if (enable)
  2379. tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
  2380. else
  2381. tmpFlag &= ~_CRTDBG_LEAK_CHECK_DF;
  2382. _CrtSetDbgFlag( tmpFlag );
  2383. }
  2384. #endif
  2385. #if defined(_WIN32) && defined(_DEBUG)
  2386. //#include <dbgint.h>
  2387. const unsigned maxUnique = 10000;
  2388. typedef struct _CrtMemBlockHeader
  2389. {
  2390. // Pointer to the block allocated just before this one:
  2391. struct _CrtMemBlockHeader *pBlockHeaderNext;
  2392. // Pointer to the block allocated just after this one:
  2393. struct _CrtMemBlockHeader *pBlockHeaderPrev;
  2394. char *szFileName; // File name
  2395. int nLine; // Line number
  2396. size_t nDataSize; // Size of user block
  2397. int nBlockUse; // Type of block
  2398. long lRequest; // Allocation number
  2399. } _CrtMemBlockHeader;
  2400. int compareFile(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2401. {
  2402. int compare;
  2403. if (left->szFileName && right->szFileName)
  2404. compare = strcmp(left->szFileName, right->szFileName);
  2405. else if (left->szFileName)
  2406. compare = -1;
  2407. else if (right->szFileName)
  2408. compare = +1;
  2409. else
  2410. compare = 0;
  2411. return compare;
  2412. }
  2413. int compareLocation(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2414. {
  2415. int compare = compareFile(left, right);
  2416. if (compare != 0)
  2417. return compare;
  2418. return left->nLine - right->nLine;
  2419. }
  2420. int compareBlocks(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2421. {
  2422. int compare = compareLocation(left, right);
  2423. if (compare != 0)
  2424. return compare;
  2425. return (int)(right->nDataSize - left->nDataSize);
  2426. }
  2427. void addLocation(unsigned & numUnique, _CrtMemBlockHeader * * locations, unsigned * counts, _CrtMemBlockHeader * search)
  2428. {
  2429. int left = 0;
  2430. int right = numUnique;
  2431. while (left < right)
  2432. {
  2433. int mid = (left + right) >> 1;
  2434. int cmp = compareBlocks(search, locations[mid]);
  2435. if (cmp < 0)
  2436. right = mid;
  2437. else if (cmp > 0)
  2438. left = mid+1;
  2439. else
  2440. {
  2441. //Save the lowest allocation number (so quicker to set a subsequent breakpoint)
  2442. if (search->lRequest < locations[mid]->lRequest)
  2443. locations[mid] = search;
  2444. counts[mid]++;
  2445. return;
  2446. }
  2447. }
  2448. if (numUnique != maxUnique)
  2449. {
  2450. assertex(left == right);
  2451. memmove(locations + left+1, locations + left, (numUnique-left)*sizeof(*locations));
  2452. memmove(counts + left+1, counts + left, (numUnique-left)*sizeof(*counts));
  2453. locations[left] = search;
  2454. counts[left] = 1;
  2455. numUnique++;
  2456. }
  2457. else
  2458. counts[maxUnique]++;
  2459. }
  2460. unsigned dumpMemory(unsigned lenTarget, char * target, unsigned lenSrc, const void * ptr)
  2461. {
  2462. if (lenSrc > lenTarget)
  2463. lenSrc = lenTarget;
  2464. const char * src = (const char *)ptr;
  2465. for (unsigned i=0; i < lenSrc; i++)
  2466. {
  2467. byte next = src[i];
  2468. target[i] = (next >= 0x20 && next <= 0x7e) ? next : '.';
  2469. }
  2470. return lenSrc;
  2471. }
  2472. void printAllocationSummary()
  2473. {
  2474. _CrtMemState state;
  2475. _CrtMemCheckpoint(&state);
  2476. unsigned numUnique = 0;
  2477. _CrtMemBlockHeader * locations[maxUnique+1];
  2478. unsigned counts[maxUnique+1];
  2479. _clear(counts);
  2480. unsigned __int64 totalFree = 0;
  2481. unsigned __int64 totalAllocated = 0;
  2482. //Walk the heap, keeping a tally of (filename, line, size)->count
  2483. _CrtMemBlockHeader * cur;
  2484. for (cur = state.pBlockHeader; cur; cur=cur->pBlockHeaderNext)
  2485. {
  2486. switch (cur->nBlockUse)
  2487. {
  2488. case _NORMAL_BLOCK:
  2489. {
  2490. addLocation(numUnique, locations, counts, cur);
  2491. totalAllocated += cur->nDataSize;
  2492. break;
  2493. }
  2494. case _FREE_BLOCK:
  2495. totalFree += cur->nDataSize;
  2496. break;
  2497. }
  2498. }
  2499. PROGLOG("%d Unique allocations by <filename>(line)@size", numUnique);
  2500. for (unsigned i2 = 0; i2 < numUnique; i2++)
  2501. {
  2502. _CrtMemBlockHeader * display = locations[i2];
  2503. //char tempBuffer[16];
  2504. //unsigned len = dumpMemory(sizeof(tempBuffer), tempBuffer, display->nDataSize,
  2505. PROGLOG("%s(%d) %d:%d {%ld} = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, display->nDataSize, counts[i2], display->lRequest, display->nDataSize * counts[i2]);
  2506. }
  2507. PROGLOG("Ungrouped: %d Total %"I64F"d", counts[maxUnique], totalAllocated);
  2508. PROGLOG("Summary by location");
  2509. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  2510. {
  2511. _CrtMemBlockHeader * display = locations[iSummary2];
  2512. unsigned count = counts[iSummary2];
  2513. unsigned __int64 size = count * display->nDataSize;
  2514. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  2515. {
  2516. _CrtMemBlockHeader * next = locations[iSummary2];
  2517. if (compareLocation(display, next) != 0)
  2518. break;
  2519. count += counts[iSummary2];
  2520. size += (counts[iSummary2] * next->nDataSize);
  2521. }
  2522. PROGLOG("%s(%d) %d = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, count, size);
  2523. }
  2524. PROGLOG("Summary by source");
  2525. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  2526. {
  2527. _CrtMemBlockHeader * display = locations[iSummary2];
  2528. unsigned count = counts[iSummary2];
  2529. unsigned __int64 size = count * display->nDataSize;
  2530. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  2531. {
  2532. _CrtMemBlockHeader * next = locations[iSummary2];
  2533. if (compareFile(display, next) != 0)
  2534. break;
  2535. count += counts[iSummary2];
  2536. size += (counts[iSummary2] * next->nDataSize);
  2537. }
  2538. PROGLOG("%s %d = %d", display->szFileName ? display->szFileName : "<unknown>", count, size);
  2539. }
  2540. }
  2541. #else
  2542. void printAllocationSummary()
  2543. {
  2544. }
  2545. #endif
  2546. #ifdef _USE_MALLOC_HOOK
  2547. // Note memory hooks should not be enabled for release (as not re-entrant in linux)
  2548. static CriticalSection hookSect;
  2549. #ifdef __linux__
  2550. static void *(*old_malloc_hook)(size_t, const void *);
  2551. static void (*old_free_hook)(void *, const void *);
  2552. static void *(*old_realloc_hook)(void *, size_t, const void *);
  2553. static void * jlib_malloc_hook (size_t size, const void *caller) ;
  2554. static void jlib_free_hook (void *ptr, const void *caller);
  2555. static void *jlib_realloc_hook (void *ptr, size_t size, const void *caller);
  2556. static int jlib_hooknest = 0; // this *shouldn't* really be needed
  2557. inline void restore_malloc_hooks()
  2558. {
  2559. if (--jlib_hooknest==0) {
  2560. __malloc_hook = old_malloc_hook;
  2561. __realloc_hook = old_realloc_hook;
  2562. __free_hook = old_free_hook;
  2563. }
  2564. }
  2565. inline void set_malloc_hooks()
  2566. {
  2567. assertex(jlib_hooknest==0);
  2568. old_malloc_hook = __malloc_hook;
  2569. old_free_hook = __free_hook;
  2570. old_realloc_hook = __realloc_hook;
  2571. __malloc_hook = jlib_malloc_hook;
  2572. __free_hook = jlib_free_hook;
  2573. __realloc_hook = jlib_realloc_hook;
  2574. jlib_hooknest = 1;
  2575. }
  2576. inline void reset_malloc_hooks()
  2577. {
  2578. if (jlib_hooknest++==0) {
  2579. __malloc_hook = jlib_malloc_hook;
  2580. __free_hook = jlib_free_hook;
  2581. __realloc_hook = jlib_realloc_hook;
  2582. }
  2583. }
  2584. inline void incCount(unsigned sz,bool inc)
  2585. {
  2586. int i=0;
  2587. size32_t s=sz;
  2588. while (s) {
  2589. s /= 2;
  2590. i++;
  2591. }
  2592. if (inc)
  2593. memArea[i] += sz;
  2594. else
  2595. memArea[i] -= sz;
  2596. }
  2597. void * jlib_malloc_hook (size_t size, const void *caller)
  2598. {
  2599. CriticalBlock block(hookSect);
  2600. void *res;
  2601. restore_malloc_hooks();
  2602. res = malloc (size);
  2603. if (res) {
  2604. size = malloc_usable_size(res);
  2605. totalMem+=size;
  2606. if (totalMem>hwmTotalMem) {
  2607. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  2608. PrintStackReport();
  2609. PROGLOG("TOTALMEM(%"I64F"d): malloc %u",totalMem,(unsigned)size);
  2610. }
  2611. hwmTotalMem = totalMem;
  2612. }
  2613. }
  2614. else
  2615. size = 0;
  2616. incCount(size,true);
  2617. if (size>REPORT_LARGER_BLOCK_THAN) {
  2618. PrintStackReport();
  2619. PROGLOG("LARGEALLOC(%u): %p",(unsigned)size,res);
  2620. }
  2621. reset_malloc_hooks();
  2622. return res;
  2623. }
  2624. void jlib_free_hook (void *ptr, const void *caller)
  2625. {
  2626. if (!ptr)
  2627. return;
  2628. CriticalBlock block(hookSect);
  2629. restore_malloc_hooks();
  2630. size32_t sz = malloc_usable_size(ptr);
  2631. free (ptr);
  2632. totalMem -= sz;
  2633. incCount(sz,false);
  2634. if (sz>REPORT_LARGER_BLOCK_THAN) {
  2635. PROGLOG("LARGEFREE(%u): %p",(unsigned)sz,ptr);
  2636. }
  2637. reset_malloc_hooks();
  2638. }
  2639. void *jlib_realloc_hook (void *ptr, size_t size, const void *caller)
  2640. {
  2641. CriticalBlock block(hookSect);
  2642. restore_malloc_hooks();
  2643. size32_t oldsz = ptr?malloc_usable_size(ptr):0;
  2644. void *res = realloc (ptr,size);
  2645. if (res) {
  2646. size = malloc_usable_size(res);
  2647. totalMem += size;
  2648. }
  2649. else
  2650. size = 0;
  2651. totalMem -= oldsz;
  2652. if (totalMem>hwmTotalMem) {
  2653. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  2654. PrintStackReport();
  2655. PROGLOG("TOTALMEM(%"I64F"d): realloc %u %u",totalMem,(unsigned)oldsz,(unsigned)size);
  2656. }
  2657. hwmTotalMem = totalMem;
  2658. }
  2659. incCount(size,true);
  2660. incCount(oldsz,false);
  2661. if ((size>REPORT_LARGER_BLOCK_THAN)||(oldsz>REPORT_LARGER_BLOCK_THAN)) {
  2662. if (size>oldsz) {
  2663. PrintStackReport();
  2664. PROGLOG("LARGEREALLOC_UP(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  2665. }
  2666. else {
  2667. PROGLOG("LARGEREALLOC_DN(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  2668. }
  2669. }
  2670. reset_malloc_hooks();
  2671. return res;
  2672. }
  2673. void jlib_decl jlib_init_hook()
  2674. {
  2675. set_malloc_hooks();
  2676. }
  2677. __int64 jlib_decl setAllocHook(bool on,bool clear)
  2678. {
  2679. CriticalBlock block(hookSect);
  2680. __int64 ret = totalMem;
  2681. if (clear) {
  2682. totalMem = 0;
  2683. hwmTotalMem = 0;
  2684. }
  2685. if (on) {
  2686. if (jlib_hooknest==0)
  2687. set_malloc_hooks();
  2688. }
  2689. else {
  2690. while (jlib_hooknest) {
  2691. restore_malloc_hooks();
  2692. //printf("Total = %d bytes\n",totalMem);
  2693. }
  2694. }
  2695. return ret;
  2696. }
  2697. unsigned jlib_decl setAllocHook(bool on)
  2698. {
  2699. // bwd compatible - should use above version in preference
  2700. CriticalBlock block(hookSect);
  2701. if (on) {
  2702. if (jlib_hooknest==0) {
  2703. set_malloc_hooks();
  2704. totalMem = 0;
  2705. hwmTotalMem = 0;
  2706. }
  2707. }
  2708. else {
  2709. while (jlib_hooknest) {
  2710. restore_malloc_hooks();
  2711. //printf("Total = %d bytes\n",totalMem);
  2712. }
  2713. }
  2714. return (unsigned)totalMem;
  2715. }
  2716. #else // windows
  2717. static _CRT_ALLOC_HOOK oldHook = NULL;
  2718. static int allocHook( int allocType, void *userData, size_t size, int nBlockUse,
  2719. long requestNumber, const unsigned char *filename, int lineNumber)
  2720. {
  2721. CriticalBlock block(hookSect);
  2722. if ( nBlockUse == _CRT_BLOCK ) // Ignore internal C runtime library allocations
  2723. return TRUE;
  2724. static bool recurse = false;
  2725. if (recurse)
  2726. return TRUE;
  2727. recurse = true;
  2728. char *operation[] = { "", "allocating", "re-allocating", "freeing" };
  2729. char *blockType[] = { "Free", "Normal", "CRT", "Ignore", "Client" };
  2730. switch (allocType) {
  2731. case _HOOK_REALLOC:
  2732. if (userData==NULL)
  2733. printf("no data on realloc\n");
  2734. else
  2735. totalMem-=_msize(userData);
  2736. // fall through
  2737. case _HOOK_ALLOC:
  2738. totalMem+=size;
  2739. break;
  2740. case _HOOK_FREE:
  2741. if (userData)
  2742. totalMem-=_msize(userData);
  2743. break;
  2744. }
  2745. // printf( "Memory operation in %s, line %d: %s a %d-byte '%s' block (#%ld)\n",
  2746. // filename, lineNumber, operation[allocType], size,
  2747. // blockType[nBlockUse], requestNumber );
  2748. recurse = false;
  2749. return TRUE; // Allow the memory operation to proceed
  2750. }
  2751. unsigned jlib_decl setAllocHook(bool on)
  2752. {
  2753. CriticalBlock block(hookSect);
  2754. if (on) {
  2755. if (oldHook==NULL) {
  2756. oldHook = _CrtSetAllocHook( allocHook );
  2757. totalMem = 0;
  2758. }
  2759. }
  2760. else {
  2761. if (oldHook!=NULL)
  2762. _CrtSetAllocHook( oldHook );
  2763. oldHook = NULL;
  2764. //printf("Total = %d bytes\n",totalMem);
  2765. }
  2766. return (unsigned)totalMem; // return unsigned for bwd compat
  2767. }
  2768. #endif
  2769. __int64 getTotalMem()
  2770. {
  2771. return totalMem;
  2772. }
  2773. #else // release
  2774. unsigned jlib_decl setAllocHook(bool on)
  2775. {
  2776. return 0;
  2777. }
  2778. __int64 jlib_decl setAllocHook(bool on,bool clear)
  2779. {
  2780. return 0;
  2781. }
  2782. __int64 jlib_decl getTotalMem()
  2783. {
  2784. return 0;
  2785. }
  2786. void jlib_decl jlib_init_hook()
  2787. {
  2788. }
  2789. #endif
  2790. class UserMetricMsgHandler : public CInterface, implements ILogMsgHandler, implements IUserMetric
  2791. {
  2792. mutable unsigned __int64 counter;
  2793. StringAttr metricName;
  2794. StringAttr regex;
  2795. Owned<ILogMsgFilter> regexFilter;
  2796. public:
  2797. virtual void Link(void) const { CInterface::Link(); }
  2798. virtual bool Release(void) const
  2799. {
  2800. if (CInterface::Release())
  2801. return true;
  2802. if (!IsShared())
  2803. {
  2804. queryLogMsgManager()->removeMonitor(const_cast<UserMetricMsgHandler *>(this)); // removeMonitor should take a const param really
  2805. }
  2806. return false;
  2807. }
  2808. UserMetricMsgHandler(const char *_name, const char *_regex) : metricName(_name), regex(_regex)
  2809. {
  2810. counter = 0;
  2811. regexFilter.setown(getRegexLogMsgFilter(regex, true));
  2812. queryLogMsgManager()->addMonitor(this, regexFilter);
  2813. }
  2814. // interface ILogMsgHandler
  2815. virtual void handleMessage(const LogMsg & msg) const { counter++; }
  2816. virtual bool needsPrep() const { return false; }
  2817. virtual void prep() {}
  2818. virtual unsigned queryMessageFields() const { return MSGFIELD_detail; }
  2819. virtual void setMessageFields(unsigned _fields = MSGFIELD_all) {}
  2820. virtual void addToPTree(IPropertyTree * parent) const {}
  2821. virtual int flush() { return 0; }
  2822. virtual char const *disable() { return 0; }
  2823. virtual void enable() {}
  2824. virtual bool getLogName(StringBuffer &name) const { return false; }
  2825. // interface IUserMetric
  2826. virtual unsigned __int64 queryCount() const { return counter; }
  2827. virtual const char *queryName() const { return metricName; }
  2828. virtual const char *queryMatchString() const { return regex; }
  2829. virtual void inc() { counter++; }
  2830. virtual void reset() { counter = 0; }
  2831. };
  2832. jlib_decl IUserMetric *createUserMetric(const char *name, const char *matchString)
  2833. {
  2834. return new UserMetricMsgHandler(name, matchString);
  2835. }