jdebug.cpp 97 KB

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