jdebug.cpp 102 KB

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