jdebug.cpp 108 KB

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