jdebug.cpp 99 KB

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