jdebug.cpp 98 KB

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