jdebug.cpp 93 KB

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