jdebug.cpp 99 KB

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