jdebug.cpp 110 KB

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