jdebug.cpp 101 KB

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