jdebug.cpp 98 KB

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