jdebug.cpp 101 KB

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