jdebug.cpp 95 KB

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