jdebug.cpp 98 KB

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