SystemInformation.cxx 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489
  1. /*============================================================================
  2. KWSys - Kitware System Library
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #if defined(_WIN32)
  11. # define NOMINMAX // use our min,max
  12. # if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
  13. # define _WIN32_WINNT 0x0501
  14. # endif
  15. # include <winsock.h> // WSADATA, include before sys/types.h
  16. #endif
  17. #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
  18. # define _GNU_SOURCE
  19. #endif
  20. // TODO:
  21. // We need an alternative implementation for many functions in this file
  22. // when USE_ASM_INSTRUCTIONS gets defined as 0.
  23. //
  24. // Consider using these on Win32/Win64 for some of them:
  25. //
  26. // IsProcessorFeaturePresent
  27. // http://msdn.microsoft.com/en-us/library/ms724482(VS.85).aspx
  28. //
  29. // GetProcessMemoryInfo
  30. // http://msdn.microsoft.com/en-us/library/ms683219(VS.85).aspx
  31. #include "kwsysPrivate.h"
  32. #include KWSYS_HEADER(SystemInformation.hxx)
  33. #include KWSYS_HEADER(Process.h)
  34. // Work-around CMake dependency scanning limitation. This must
  35. // duplicate the above list of headers.
  36. #if 0
  37. # include "SystemInformation.hxx.in"
  38. # include "Process.h.in"
  39. #endif
  40. #include <iostream>
  41. #include <sstream>
  42. #include <fstream>
  43. #include <string>
  44. #include <vector>
  45. #if defined(_WIN32)
  46. # include <windows.h>
  47. # if defined(_MSC_VER) && _MSC_VER >= 1800
  48. # define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  49. # endif
  50. # include <errno.h>
  51. # if defined(KWSYS_SYS_HAS_PSAPI)
  52. # include <psapi.h>
  53. # endif
  54. # if !defined(siginfo_t)
  55. typedef int siginfo_t;
  56. # endif
  57. #else
  58. # include <sys/types.h>
  59. # include <sys/time.h>
  60. # include <sys/utsname.h> // int uname(struct utsname *buf);
  61. # include <sys/resource.h> // getrlimit
  62. # include <unistd.h>
  63. # include <signal.h>
  64. # include <fcntl.h>
  65. # include <errno.h> // extern int errno;
  66. #endif
  67. #if defined (__CYGWIN__) && !defined(_WIN32)
  68. # include <windows.h>
  69. # undef _WIN32
  70. #endif
  71. #ifdef __FreeBSD__
  72. # include <sys/sysctl.h>
  73. # include <fenv.h>
  74. # include <sys/socket.h>
  75. # include <netdb.h>
  76. # include <netinet/in.h>
  77. # if defined(KWSYS_SYS_HAS_IFADDRS_H)
  78. # include <ifaddrs.h>
  79. # define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
  80. # endif
  81. #endif
  82. #if defined(__OpenBSD__) || defined(__NetBSD__)
  83. # include <sys/param.h>
  84. # include <sys/sysctl.h>
  85. #endif
  86. #if defined(KWSYS_SYS_HAS_MACHINE_CPU_H)
  87. # include <machine/cpu.h>
  88. #endif
  89. #if defined(__DragonFly__)
  90. # include <sys/sysctl.h>
  91. #endif
  92. #ifdef __APPLE__
  93. # include <sys/sysctl.h>
  94. # include <mach/vm_statistics.h>
  95. # include <mach/host_info.h>
  96. # include <mach/mach.h>
  97. # include <mach/mach_types.h>
  98. # include <fenv.h>
  99. # include <sys/socket.h>
  100. # include <netdb.h>
  101. # include <netinet/in.h>
  102. # if defined(KWSYS_SYS_HAS_IFADDRS_H)
  103. # include <ifaddrs.h>
  104. # define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
  105. # endif
  106. # if !(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0 >= 1050)
  107. # undef KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE
  108. # endif
  109. #endif
  110. #ifdef __linux
  111. # include <fenv.h>
  112. # include <sys/socket.h>
  113. # include <netdb.h>
  114. # include <netinet/in.h>
  115. # if defined(KWSYS_SYS_HAS_IFADDRS_H)
  116. # include <ifaddrs.h>
  117. # if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
  118. # define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
  119. # endif
  120. # endif
  121. # if defined(KWSYS_CXX_HAS_RLIMIT64)
  122. typedef struct rlimit64 ResourceLimitType;
  123. # define GetResourceLimit getrlimit64
  124. # else
  125. typedef struct rlimit ResourceLimitType;
  126. # define GetResourceLimit getrlimit
  127. # endif
  128. #elif defined( __hpux )
  129. # include <sys/param.h>
  130. # include <sys/pstat.h>
  131. # if defined(KWSYS_SYS_HAS_MPCTL_H)
  132. # include <sys/mpctl.h>
  133. # endif
  134. #endif
  135. #ifdef __HAIKU__
  136. # include <OS.h>
  137. #endif
  138. #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  139. # include <execinfo.h>
  140. # if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
  141. # include <cxxabi.h>
  142. # endif
  143. # if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  144. # include <dlfcn.h>
  145. # endif
  146. #else
  147. # undef KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE
  148. # undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
  149. #endif
  150. #include <memory.h>
  151. #include <stdlib.h>
  152. #include <stdio.h>
  153. #include <string.h>
  154. #include <ctype.h> // int isdigit(int c);
  155. #if defined(KWSYS_USE_LONG_LONG)
  156. # if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
  157. # define iostreamLongLong(x) (x)
  158. # else
  159. # define iostreamLongLong(x) ((long)x)
  160. # endif
  161. #elif defined(KWSYS_USE___INT64)
  162. # if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
  163. # define iostreamLongLong(x) (x)
  164. # else
  165. # define iostreamLongLong(x) ((long)x)
  166. # endif
  167. #else
  168. # error "No Long Long"
  169. #endif
  170. #if defined(KWSYS_CXX_HAS_ATOLL)
  171. # define atoLongLong atoll
  172. #else
  173. # if defined(KWSYS_CXX_HAS__ATOI64)
  174. # define atoLongLong _atoi64
  175. # elif defined(KWSYS_CXX_HAS_ATOL)
  176. # define atoLongLong atol
  177. # else
  178. # define atoLongLong atoi
  179. # endif
  180. #endif
  181. #if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64)
  182. #define USE_ASM_INSTRUCTIONS 1
  183. #else
  184. #define USE_ASM_INSTRUCTIONS 0
  185. #endif
  186. #if defined(_MSC_VER) && (_MSC_VER >= 1400)
  187. #include <intrin.h>
  188. #define USE_CPUID_INTRINSICS 1
  189. #else
  190. #define USE_CPUID_INTRINSICS 0
  191. #endif
  192. #if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
  193. # define USE_CPUID 1
  194. #else
  195. # define USE_CPUID 0
  196. #endif
  197. #if USE_CPUID
  198. #define CPUID_AWARE_COMPILER
  199. /**
  200. * call CPUID instruction
  201. *
  202. * Will return false if the instruction failed.
  203. */
  204. static bool call_cpuid(int select, int result[4])
  205. {
  206. #if USE_CPUID_INTRINSICS
  207. __cpuid(result, select);
  208. return true;
  209. #else
  210. int tmp[4];
  211. #if defined(_MSC_VER)
  212. // Use SEH to determine CPUID presence
  213. __try {
  214. _asm {
  215. #ifdef CPUID_AWARE_COMPILER
  216. ; we must push/pop the registers <<CPUID>> writes to, as the
  217. ; optimiser does not know about <<CPUID>>, and so does not expect
  218. ; these registers to change.
  219. push eax
  220. push ebx
  221. push ecx
  222. push edx
  223. #endif
  224. ; <<CPUID>>
  225. mov eax, select
  226. #ifdef CPUID_AWARE_COMPILER
  227. cpuid
  228. #else
  229. _asm _emit 0x0f
  230. _asm _emit 0xa2
  231. #endif
  232. mov tmp[0 * TYPE int], eax
  233. mov tmp[1 * TYPE int], ebx
  234. mov tmp[2 * TYPE int], ecx
  235. mov tmp[3 * TYPE int], edx
  236. #ifdef CPUID_AWARE_COMPILER
  237. pop edx
  238. pop ecx
  239. pop ebx
  240. pop eax
  241. #endif
  242. }
  243. }
  244. __except(1)
  245. {
  246. return false;
  247. }
  248. memcpy(result, tmp, sizeof(tmp));
  249. #elif defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
  250. unsigned int a, b, c, d;
  251. __asm {
  252. mov EAX, select;
  253. cpuid
  254. mov a, EAX;
  255. mov b, EBX;
  256. mov c, ECX;
  257. mov d, EDX;
  258. }
  259. result[0] = a;
  260. result[1] = b;
  261. result[2] = c;
  262. result[3] = d;
  263. #endif
  264. // The cpuid instruction succeeded.
  265. return true;
  266. #endif
  267. }
  268. #endif
  269. namespace KWSYS_NAMESPACE
  270. {
  271. template<typename T>
  272. T min(T a, T b){ return a<b ? a : b; }
  273. extern "C" { typedef void (*SigAction)(int,siginfo_t*,void*); }
  274. // Define SystemInformationImplementation class
  275. typedef void (*DELAY_FUNC)(unsigned int uiMS);
  276. class SystemInformationImplementation
  277. {
  278. public:
  279. typedef SystemInformation::LongLong LongLong;
  280. SystemInformationImplementation ();
  281. ~SystemInformationImplementation ();
  282. const char * GetVendorString();
  283. const char * GetVendorID();
  284. std::string GetTypeID();
  285. std::string GetFamilyID();
  286. std::string GetModelID();
  287. std::string GetModelName();
  288. std::string GetSteppingCode();
  289. const char * GetExtendedProcessorName();
  290. const char * GetProcessorSerialNumber();
  291. int GetProcessorCacheSize();
  292. unsigned int GetLogicalProcessorsPerPhysical();
  293. float GetProcessorClockFrequency();
  294. int GetProcessorAPICID();
  295. int GetProcessorCacheXSize(long int);
  296. bool DoesCPUSupportFeature(long int);
  297. const char * GetOSName();
  298. const char * GetHostname();
  299. int GetFullyQualifiedDomainName(std::string &fqdn);
  300. const char * GetOSRelease();
  301. const char * GetOSVersion();
  302. const char * GetOSPlatform();
  303. bool Is64Bits();
  304. unsigned int GetNumberOfLogicalCPU(); // per physical cpu
  305. unsigned int GetNumberOfPhysicalCPU();
  306. bool DoesCPUSupportCPUID();
  307. // Retrieve memory information in megabyte.
  308. size_t GetTotalVirtualMemory();
  309. size_t GetAvailableVirtualMemory();
  310. size_t GetTotalPhysicalMemory();
  311. size_t GetAvailablePhysicalMemory();
  312. LongLong GetProcessId();
  313. // Retrieve memory information in kib
  314. LongLong GetHostMemoryTotal();
  315. LongLong GetHostMemoryAvailable(const char *envVarName);
  316. LongLong GetHostMemoryUsed();
  317. LongLong GetProcMemoryAvailable(
  318. const char *hostLimitEnvVarName,
  319. const char *procLimitEnvVarName);
  320. LongLong GetProcMemoryUsed();
  321. double GetLoadAverage();
  322. // enable/disable stack trace signal handler.
  323. static
  324. void SetStackTraceOnError(int enable);
  325. // get current stack
  326. static
  327. std::string GetProgramStack(int firstFrame, int wholePath);
  328. /** Run the different checks */
  329. void RunCPUCheck();
  330. void RunOSCheck();
  331. void RunMemoryCheck();
  332. public:
  333. typedef struct tagID
  334. {
  335. int Type;
  336. int Family;
  337. int Model;
  338. int Revision;
  339. int ExtendedFamily;
  340. int ExtendedModel;
  341. std::string ProcessorName;
  342. std::string Vendor;
  343. std::string SerialNumber;
  344. std::string ModelName;
  345. } ID;
  346. typedef struct tagCPUPowerManagement
  347. {
  348. bool HasVoltageID;
  349. bool HasFrequencyID;
  350. bool HasTempSenseDiode;
  351. } CPUPowerManagement;
  352. typedef struct tagCPUExtendedFeatures
  353. {
  354. bool Has3DNow;
  355. bool Has3DNowPlus;
  356. bool SupportsMP;
  357. bool HasMMXPlus;
  358. bool HasSSEMMX;
  359. bool SupportsHyperthreading;
  360. unsigned int LogicalProcessorsPerPhysical;
  361. int APIC_ID;
  362. CPUPowerManagement PowerManagement;
  363. } CPUExtendedFeatures;
  364. typedef struct CPUtagFeatures
  365. {
  366. bool HasFPU;
  367. bool HasTSC;
  368. bool HasMMX;
  369. bool HasSSE;
  370. bool HasSSEFP;
  371. bool HasSSE2;
  372. bool HasIA64;
  373. bool HasAPIC;
  374. bool HasCMOV;
  375. bool HasMTRR;
  376. bool HasACPI;
  377. bool HasSerial;
  378. bool HasThermal;
  379. int CPUSpeed;
  380. int L1CacheSize;
  381. int L2CacheSize;
  382. int L3CacheSize;
  383. CPUExtendedFeatures ExtendedFeatures;
  384. } CPUFeatures;
  385. enum Manufacturer
  386. {
  387. AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, IBM,
  388. Motorola, HP, UnknownManufacturer
  389. };
  390. protected:
  391. // For windows
  392. bool RetrieveCPUFeatures();
  393. bool RetrieveCPUIdentity();
  394. bool RetrieveCPUCacheDetails();
  395. bool RetrieveClassicalCPUCacheDetails();
  396. bool RetrieveCPUClockSpeed();
  397. bool RetrieveClassicalCPUClockSpeed();
  398. bool RetrieveCPUExtendedLevelSupport(int);
  399. bool RetrieveExtendedCPUFeatures();
  400. bool RetrieveProcessorSerialNumber();
  401. bool RetrieveCPUPowerManagement();
  402. bool RetrieveClassicalCPUIdentity();
  403. bool RetrieveExtendedCPUIdentity();
  404. // Processor information
  405. Manufacturer ChipManufacturer;
  406. CPUFeatures Features;
  407. ID ChipID;
  408. float CPUSpeedInMHz;
  409. unsigned int NumberOfLogicalCPU;
  410. unsigned int NumberOfPhysicalCPU;
  411. int CPUCount(); // For windows
  412. unsigned char LogicalCPUPerPhysicalCPU();
  413. unsigned char GetAPICId(); // For windows
  414. bool IsHyperThreadingSupported();
  415. static LongLong GetCyclesDifference(DELAY_FUNC, unsigned int); // For windows
  416. // For Linux and Cygwin, /proc/cpuinfo formats are slightly different
  417. bool RetreiveInformationFromCpuInfoFile();
  418. std::string ExtractValueFromCpuInfoFile(std::string buffer,
  419. const char* word, size_t init=0);
  420. bool QueryLinuxMemory();
  421. bool QueryCygwinMemory();
  422. static void Delay (unsigned int);
  423. static void DelayOverhead (unsigned int);
  424. void FindManufacturer(const std::string &family = "");
  425. // For Mac
  426. bool ParseSysCtl();
  427. int CallSwVers(const char *arg, std::string &ver);
  428. void TrimNewline(std::string&);
  429. std::string ExtractValueFromSysCtl(const char* word);
  430. std::string SysCtlBuffer;
  431. // For Solaris
  432. bool QuerySolarisMemory();
  433. bool QuerySolarisProcessor();
  434. std::string ParseValueFromKStat(const char* arguments);
  435. std::string RunProcess(std::vector<const char*> args);
  436. //For Haiku OS
  437. bool QueryHaikuInfo();
  438. //For QNX
  439. bool QueryQNXMemory();
  440. bool QueryQNXProcessor();
  441. //For OpenBSD, FreeBSD, NetBSD, DragonFly
  442. bool QueryBSDMemory();
  443. bool QueryBSDProcessor();
  444. //For HP-UX
  445. bool QueryHPUXMemory();
  446. bool QueryHPUXProcessor();
  447. //For Microsoft Windows
  448. bool QueryWindowsMemory();
  449. //For AIX
  450. bool QueryAIXMemory();
  451. bool QueryProcessorBySysconf();
  452. bool QueryProcessor();
  453. // Evaluate the memory information.
  454. bool QueryMemoryBySysconf();
  455. bool QueryMemory();
  456. size_t TotalVirtualMemory;
  457. size_t AvailableVirtualMemory;
  458. size_t TotalPhysicalMemory;
  459. size_t AvailablePhysicalMemory;
  460. size_t CurrentPositionInFile;
  461. // Operating System information
  462. bool QueryOSInformation();
  463. std::string OSName;
  464. std::string Hostname;
  465. std::string OSRelease;
  466. std::string OSVersion;
  467. std::string OSPlatform;
  468. };
  469. SystemInformation::SystemInformation()
  470. {
  471. this->Implementation = new SystemInformationImplementation;
  472. }
  473. SystemInformation::~SystemInformation()
  474. {
  475. delete this->Implementation;
  476. }
  477. const char * SystemInformation::GetVendorString()
  478. {
  479. return this->Implementation->GetVendorString();
  480. }
  481. const char * SystemInformation::GetVendorID()
  482. {
  483. return this->Implementation->GetVendorID();
  484. }
  485. std::string SystemInformation::GetTypeID()
  486. {
  487. return this->Implementation->GetTypeID();
  488. }
  489. std::string SystemInformation::GetFamilyID()
  490. {
  491. return this->Implementation->GetFamilyID();
  492. }
  493. std::string SystemInformation::GetModelID()
  494. {
  495. return this->Implementation->GetModelID();
  496. }
  497. std::string SystemInformation::GetModelName()
  498. {
  499. return this->Implementation->GetModelName();
  500. }
  501. std::string SystemInformation::GetSteppingCode()
  502. {
  503. return this->Implementation->GetSteppingCode();
  504. }
  505. const char * SystemInformation::GetExtendedProcessorName()
  506. {
  507. return this->Implementation->GetExtendedProcessorName();
  508. }
  509. const char * SystemInformation::GetProcessorSerialNumber()
  510. {
  511. return this->Implementation->GetProcessorSerialNumber();
  512. }
  513. int SystemInformation::GetProcessorCacheSize()
  514. {
  515. return this->Implementation->GetProcessorCacheSize();
  516. }
  517. unsigned int SystemInformation::GetLogicalProcessorsPerPhysical()
  518. {
  519. return this->Implementation->GetLogicalProcessorsPerPhysical();
  520. }
  521. float SystemInformation::GetProcessorClockFrequency()
  522. {
  523. return this->Implementation->GetProcessorClockFrequency();
  524. }
  525. int SystemInformation::GetProcessorAPICID()
  526. {
  527. return this->Implementation->GetProcessorAPICID();
  528. }
  529. int SystemInformation::GetProcessorCacheXSize(long int l)
  530. {
  531. return this->Implementation->GetProcessorCacheXSize(l);
  532. }
  533. bool SystemInformation::DoesCPUSupportFeature(long int i)
  534. {
  535. return this->Implementation->DoesCPUSupportFeature(i);
  536. }
  537. std::string SystemInformation::GetCPUDescription()
  538. {
  539. std::ostringstream oss;
  540. oss
  541. << this->GetNumberOfPhysicalCPU()
  542. << " core ";
  543. if (this->GetModelName().empty())
  544. {
  545. oss
  546. << this->GetProcessorClockFrequency()
  547. << " MHz "
  548. << this->GetVendorString()
  549. << " "
  550. << this->GetExtendedProcessorName();
  551. }
  552. else
  553. {
  554. oss << this->GetModelName();
  555. }
  556. // remove extra spaces
  557. std::string tmp=oss.str();
  558. size_t pos;
  559. while( (pos=tmp.find(" "))!=std::string::npos)
  560. {
  561. tmp.replace(pos,2," ");
  562. }
  563. return tmp;
  564. }
  565. const char * SystemInformation::GetOSName()
  566. {
  567. return this->Implementation->GetOSName();
  568. }
  569. const char * SystemInformation::GetHostname()
  570. {
  571. return this->Implementation->GetHostname();
  572. }
  573. std::string SystemInformation::GetFullyQualifiedDomainName()
  574. {
  575. std::string fqdn;
  576. this->Implementation->GetFullyQualifiedDomainName(fqdn);
  577. return fqdn;
  578. }
  579. const char * SystemInformation::GetOSRelease()
  580. {
  581. return this->Implementation->GetOSRelease();
  582. }
  583. const char * SystemInformation::GetOSVersion()
  584. {
  585. return this->Implementation->GetOSVersion();
  586. }
  587. const char * SystemInformation::GetOSPlatform()
  588. {
  589. return this->Implementation->GetOSPlatform();
  590. }
  591. int SystemInformation::GetOSIsWindows()
  592. {
  593. #if defined(_WIN32)
  594. return 1;
  595. #else
  596. return 0;
  597. #endif
  598. }
  599. int SystemInformation::GetOSIsLinux()
  600. {
  601. #if defined(__linux)
  602. return 1;
  603. #else
  604. return 0;
  605. #endif
  606. }
  607. int SystemInformation::GetOSIsApple()
  608. {
  609. #if defined(__APPLE__)
  610. return 1;
  611. #else
  612. return 0;
  613. #endif
  614. }
  615. std::string SystemInformation::GetOSDescription()
  616. {
  617. std::ostringstream oss;
  618. oss
  619. << this->GetOSName()
  620. << " "
  621. << this->GetOSRelease()
  622. << " "
  623. << this->GetOSVersion();
  624. return oss.str();
  625. }
  626. bool SystemInformation::Is64Bits()
  627. {
  628. return this->Implementation->Is64Bits();
  629. }
  630. unsigned int SystemInformation::GetNumberOfLogicalCPU() // per physical cpu
  631. {
  632. return this->Implementation->GetNumberOfLogicalCPU();
  633. }
  634. unsigned int SystemInformation::GetNumberOfPhysicalCPU()
  635. {
  636. return this->Implementation->GetNumberOfPhysicalCPU();
  637. }
  638. bool SystemInformation::DoesCPUSupportCPUID()
  639. {
  640. return this->Implementation->DoesCPUSupportCPUID();
  641. }
  642. // Retrieve memory information in megabyte.
  643. size_t SystemInformation::GetTotalVirtualMemory()
  644. {
  645. return this->Implementation->GetTotalVirtualMemory();
  646. }
  647. size_t SystemInformation::GetAvailableVirtualMemory()
  648. {
  649. return this->Implementation->GetAvailableVirtualMemory();
  650. }
  651. size_t SystemInformation::GetTotalPhysicalMemory()
  652. {
  653. return this->Implementation->GetTotalPhysicalMemory();
  654. }
  655. size_t SystemInformation::GetAvailablePhysicalMemory()
  656. {
  657. return this->Implementation->GetAvailablePhysicalMemory();
  658. }
  659. std::string SystemInformation::GetMemoryDescription(
  660. const char *hostLimitEnvVarName,
  661. const char *procLimitEnvVarName)
  662. {
  663. std::ostringstream oss;
  664. oss
  665. << "Host Total: "
  666. << iostreamLongLong(this->GetHostMemoryTotal())
  667. << " KiB, Host Available: "
  668. << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
  669. << " KiB, Process Available: "
  670. << iostreamLongLong(
  671. this->GetProcMemoryAvailable(hostLimitEnvVarName,procLimitEnvVarName))
  672. << " KiB";
  673. return oss.str();
  674. }
  675. // host memory info in units of KiB.
  676. SystemInformation::LongLong SystemInformation::GetHostMemoryTotal()
  677. {
  678. return this->Implementation->GetHostMemoryTotal();
  679. }
  680. SystemInformation::LongLong
  681. SystemInformation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
  682. {
  683. return this->Implementation->GetHostMemoryAvailable(hostLimitEnvVarName);
  684. }
  685. SystemInformation::LongLong SystemInformation::GetHostMemoryUsed()
  686. {
  687. return this->Implementation->GetHostMemoryUsed();
  688. }
  689. // process memory info in units of KiB.
  690. SystemInformation::LongLong
  691. SystemInformation::GetProcMemoryAvailable(
  692. const char *hostLimitEnvVarName,
  693. const char *procLimitEnvVarName)
  694. {
  695. return this->Implementation->GetProcMemoryAvailable(
  696. hostLimitEnvVarName,
  697. procLimitEnvVarName);
  698. }
  699. SystemInformation::LongLong SystemInformation::GetProcMemoryUsed()
  700. {
  701. return this->Implementation->GetProcMemoryUsed();
  702. }
  703. double SystemInformation::GetLoadAverage()
  704. {
  705. return this->Implementation->GetLoadAverage();
  706. }
  707. SystemInformation::LongLong SystemInformation::GetProcessId()
  708. {
  709. return this->Implementation->GetProcessId();
  710. }
  711. void SystemInformation::SetStackTraceOnError(int enable)
  712. {
  713. SystemInformationImplementation::SetStackTraceOnError(enable);
  714. }
  715. std::string SystemInformation::GetProgramStack(int firstFrame, int wholePath)
  716. {
  717. return SystemInformationImplementation::GetProgramStack(firstFrame, wholePath);
  718. }
  719. /** Run the different checks */
  720. void SystemInformation::RunCPUCheck()
  721. {
  722. this->Implementation->RunCPUCheck();
  723. }
  724. void SystemInformation::RunOSCheck()
  725. {
  726. this->Implementation->RunOSCheck();
  727. }
  728. void SystemInformation::RunMemoryCheck()
  729. {
  730. this->Implementation->RunMemoryCheck();
  731. }
  732. // --------------------------------------------------------------
  733. // SystemInformationImplementation starts here
  734. #define STORE_TLBCACHE_INFO(x,y) x = (x < y) ? y : x
  735. #define TLBCACHE_INFO_UNITS (15)
  736. #define CLASSICAL_CPU_FREQ_LOOP 10000000
  737. #define RDTSC_INSTRUCTION _asm _emit 0x0f _asm _emit 0x31
  738. #define MMX_FEATURE 0x00000001
  739. #define MMX_PLUS_FEATURE 0x00000002
  740. #define SSE_FEATURE 0x00000004
  741. #define SSE2_FEATURE 0x00000008
  742. #define AMD_3DNOW_FEATURE 0x00000010
  743. #define AMD_3DNOW_PLUS_FEATURE 0x00000020
  744. #define IA64_FEATURE 0x00000040
  745. #define MP_CAPABLE 0x00000080
  746. #define HYPERTHREAD_FEATURE 0x00000100
  747. #define SERIALNUMBER_FEATURE 0x00000200
  748. #define APIC_FEATURE 0x00000400
  749. #define SSE_FP_FEATURE 0x00000800
  750. #define SSE_MMX_FEATURE 0x00001000
  751. #define CMOV_FEATURE 0x00002000
  752. #define MTRR_FEATURE 0x00004000
  753. #define L1CACHE_FEATURE 0x00008000
  754. #define L2CACHE_FEATURE 0x00010000
  755. #define L3CACHE_FEATURE 0x00020000
  756. #define ACPI_FEATURE 0x00040000
  757. #define THERMALMONITOR_FEATURE 0x00080000
  758. #define TEMPSENSEDIODE_FEATURE 0x00100000
  759. #define FREQUENCYID_FEATURE 0x00200000
  760. #define VOLTAGEID_FREQUENCY 0x00400000
  761. // Status Flag
  762. #define HT_NOT_CAPABLE 0
  763. #define HT_ENABLED 1
  764. #define HT_DISABLED 2
  765. #define HT_SUPPORTED_NOT_ENABLED 3
  766. #define HT_CANNOT_DETECT 4
  767. // EDX[28] Bit 28 is set if HT is supported
  768. #define HT_BIT 0x10000000
  769. // EAX[11:8] Bit 8-11 contains family processor ID.
  770. #define FAMILY_ID 0x0F00
  771. #define PENTIUM4_ID 0x0F00
  772. // EAX[23:20] Bit 20-23 contains extended family processor ID
  773. #define EXT_FAMILY_ID 0x0F00000
  774. // EBX[23:16] Bit 16-23 in ebx contains the number of logical
  775. #define NUM_LOGICAL_BITS 0x00FF0000
  776. // processors per physical processor when execute cpuid with
  777. // eax set to 1
  778. // EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
  779. #define INITIAL_APIC_ID_BITS 0xFF000000
  780. // initial APIC ID for the processor this code is running on.
  781. // Default value = 0xff if HT is not supported
  782. // Hide implementation details in an anonymous namespace.
  783. namespace {
  784. // *****************************************************************************
  785. #if defined(__linux) || defined(__APPLE__)
  786. int LoadLines(
  787. FILE *file,
  788. std::vector<std::string> &lines)
  789. {
  790. // Load each line in the given file into a the vector.
  791. int nRead=0;
  792. const int bufSize=1024;
  793. char buf[bufSize]={'\0'};
  794. while (!feof(file) && !ferror(file))
  795. {
  796. errno=0;
  797. if (fgets(buf,bufSize,file) == 0)
  798. {
  799. if (ferror(file) && (errno==EINTR))
  800. {
  801. clearerr(file);
  802. }
  803. continue;
  804. }
  805. char *pBuf=buf;
  806. while(*pBuf)
  807. {
  808. if (*pBuf=='\n') *pBuf='\0';
  809. pBuf+=1;
  810. }
  811. lines.push_back(buf);
  812. ++nRead;
  813. }
  814. if (ferror(file))
  815. {
  816. return 0;
  817. }
  818. return nRead;
  819. }
  820. # if defined(__linux)
  821. // *****************************************************************************
  822. int LoadLines(
  823. const char *fileName,
  824. std::vector<std::string> &lines)
  825. {
  826. FILE *file=fopen(fileName,"r");
  827. if (file==0)
  828. {
  829. return 0;
  830. }
  831. int nRead=LoadLines(file,lines);
  832. fclose(file);
  833. return nRead;
  834. }
  835. # endif
  836. // ****************************************************************************
  837. template<typename T>
  838. int NameValue(
  839. std::vector<std::string> &lines,
  840. std::string name, T &value)
  841. {
  842. size_t nLines=lines.size();
  843. for (size_t i=0; i<nLines; ++i)
  844. {
  845. size_t at=lines[i].find(name);
  846. if (at==std::string::npos)
  847. {
  848. continue;
  849. }
  850. std::istringstream is(lines[i].substr(at+name.size()));
  851. is >> value;
  852. return 0;
  853. }
  854. return -1;
  855. }
  856. #endif
  857. #if defined(__linux)
  858. // ****************************************************************************
  859. template<typename T>
  860. int GetFieldsFromFile(
  861. const char *fileName,
  862. const char **fieldNames,
  863. T *values)
  864. {
  865. std::vector<std::string> fields;
  866. if (!LoadLines(fileName,fields))
  867. {
  868. return -1;
  869. }
  870. int i=0;
  871. while (fieldNames[i]!=NULL)
  872. {
  873. int ierr=NameValue(fields,fieldNames[i],values[i]);
  874. if (ierr)
  875. {
  876. return -(i+2);
  877. }
  878. i+=1;
  879. }
  880. return 0;
  881. }
  882. // ****************************************************************************
  883. template<typename T>
  884. int GetFieldFromFile(
  885. const char *fileName,
  886. const char *fieldName,
  887. T &value)
  888. {
  889. const char *fieldNames[2]={fieldName,NULL};
  890. T values[1]={T(0)};
  891. int ierr=GetFieldsFromFile(fileName,fieldNames,values);
  892. if (ierr)
  893. {
  894. return ierr;
  895. }
  896. value=values[0];
  897. return 0;
  898. }
  899. #endif
  900. // ****************************************************************************
  901. #if defined(__APPLE__)
  902. template<typename T>
  903. int GetFieldsFromCommand(
  904. const char *command,
  905. const char **fieldNames,
  906. T *values)
  907. {
  908. FILE *file=popen(command,"r");
  909. if (file==0)
  910. {
  911. return -1;
  912. }
  913. std::vector<std::string> fields;
  914. int nl=LoadLines(file,fields);
  915. pclose(file);
  916. if (nl==0)
  917. {
  918. return -1;
  919. }
  920. int i=0;
  921. while (fieldNames[i]!=NULL)
  922. {
  923. int ierr=NameValue(fields,fieldNames[i],values[i]);
  924. if (ierr)
  925. {
  926. return -(i+2);
  927. }
  928. i+=1;
  929. }
  930. return 0;
  931. }
  932. #endif
  933. // ****************************************************************************
  934. #if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
  935. void StacktraceSignalHandler(
  936. int sigNo,
  937. siginfo_t *sigInfo,
  938. void * /*sigContext*/)
  939. {
  940. #if defined(__linux) || defined(__APPLE__)
  941. std::ostringstream oss;
  942. oss
  943. << std::endl
  944. << "=========================================================" << std::endl
  945. << "Process id " << getpid() << " ";
  946. switch (sigNo)
  947. {
  948. case SIGINT:
  949. oss << "Caught SIGINT";
  950. break;
  951. case SIGTERM:
  952. oss << "Caught SIGTERM";
  953. break;
  954. case SIGABRT:
  955. oss << "Caught SIGABRT";
  956. break;
  957. case SIGFPE:
  958. oss
  959. << "Caught SIGFPE at "
  960. << (sigInfo->si_addr==0?"0x":"")
  961. << sigInfo->si_addr
  962. << " ";
  963. switch (sigInfo->si_code)
  964. {
  965. # if defined(FPE_INTDIV)
  966. case FPE_INTDIV:
  967. oss << "integer division by zero";
  968. break;
  969. # endif
  970. # if defined(FPE_INTOVF)
  971. case FPE_INTOVF:
  972. oss << "integer overflow";
  973. break;
  974. # endif
  975. case FPE_FLTDIV:
  976. oss << "floating point divide by zero";
  977. break;
  978. case FPE_FLTOVF:
  979. oss << "floating point overflow";
  980. break;
  981. case FPE_FLTUND:
  982. oss << "floating point underflow";
  983. break;
  984. case FPE_FLTRES:
  985. oss << "floating point inexact result";
  986. break;
  987. case FPE_FLTINV:
  988. oss << "floating point invalid operation";
  989. break;
  990. #if defined(FPE_FLTSUB)
  991. case FPE_FLTSUB:
  992. oss << "floating point subscript out of range";
  993. break;
  994. #endif
  995. default:
  996. oss << "code " << sigInfo->si_code;
  997. break;
  998. }
  999. break;
  1000. case SIGSEGV:
  1001. oss
  1002. << "Caught SIGSEGV at "
  1003. << (sigInfo->si_addr==0?"0x":"")
  1004. << sigInfo->si_addr
  1005. << " ";
  1006. switch (sigInfo->si_code)
  1007. {
  1008. case SEGV_MAPERR:
  1009. oss << "address not mapped to object";
  1010. break;
  1011. case SEGV_ACCERR:
  1012. oss << "invalid permission for mapped object";
  1013. break;
  1014. default:
  1015. oss << "code " << sigInfo->si_code;
  1016. break;
  1017. }
  1018. break;
  1019. case SIGBUS:
  1020. oss
  1021. << "Caught SIGBUS at "
  1022. << (sigInfo->si_addr==0?"0x":"")
  1023. << sigInfo->si_addr
  1024. << " ";
  1025. switch (sigInfo->si_code)
  1026. {
  1027. case BUS_ADRALN:
  1028. oss << "invalid address alignment";
  1029. break;
  1030. # if defined(BUS_ADRERR)
  1031. case BUS_ADRERR:
  1032. oss << "nonexistent physical address";
  1033. break;
  1034. # endif
  1035. # if defined(BUS_OBJERR)
  1036. case BUS_OBJERR:
  1037. oss << "object-specific hardware error";
  1038. break;
  1039. # endif
  1040. # if defined(BUS_MCEERR_AR)
  1041. case BUS_MCEERR_AR:
  1042. oss << "Hardware memory error consumed on a machine check; action required.";
  1043. break;
  1044. # endif
  1045. # if defined(BUS_MCEERR_AO)
  1046. case BUS_MCEERR_AO:
  1047. oss << "Hardware memory error detected in process but not consumed; action optional.";
  1048. break;
  1049. # endif
  1050. default:
  1051. oss << "code " << sigInfo->si_code;
  1052. break;
  1053. }
  1054. break;
  1055. case SIGILL:
  1056. oss
  1057. << "Caught SIGILL at "
  1058. << (sigInfo->si_addr==0?"0x":"")
  1059. << sigInfo->si_addr
  1060. << " ";
  1061. switch (sigInfo->si_code)
  1062. {
  1063. case ILL_ILLOPC:
  1064. oss << "illegal opcode";
  1065. break;
  1066. # if defined(ILL_ILLOPN)
  1067. case ILL_ILLOPN:
  1068. oss << "illegal operand";
  1069. break;
  1070. # endif
  1071. # if defined(ILL_ILLADR)
  1072. case ILL_ILLADR:
  1073. oss << "illegal addressing mode.";
  1074. break;
  1075. # endif
  1076. case ILL_ILLTRP:
  1077. oss << "illegal trap";
  1078. break;
  1079. case ILL_PRVOPC:
  1080. oss << "privileged opcode";
  1081. break;
  1082. # if defined(ILL_PRVREG)
  1083. case ILL_PRVREG:
  1084. oss << "privileged register";
  1085. break;
  1086. # endif
  1087. # if defined(ILL_COPROC)
  1088. case ILL_COPROC:
  1089. oss << "co-processor error";
  1090. break;
  1091. # endif
  1092. # if defined(ILL_BADSTK)
  1093. case ILL_BADSTK:
  1094. oss << "internal stack error";
  1095. break;
  1096. # endif
  1097. default:
  1098. oss << "code " << sigInfo->si_code;
  1099. break;
  1100. }
  1101. break;
  1102. default:
  1103. oss << "Caught " << sigNo << " code " << sigInfo->si_code;
  1104. break;
  1105. }
  1106. oss
  1107. << std::endl
  1108. << "Program Stack:" << std::endl
  1109. << SystemInformationImplementation::GetProgramStack(2,0)
  1110. << "=========================================================" << std::endl;
  1111. std::cerr << oss.str() << std::endl;
  1112. // restore the previously registered handlers
  1113. // and abort
  1114. SystemInformationImplementation::SetStackTraceOnError(0);
  1115. abort();
  1116. #else
  1117. // avoid warning C4100
  1118. (void)sigNo;
  1119. (void)sigInfo;
  1120. #endif
  1121. }
  1122. #endif
  1123. #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  1124. #define safes(_arg)((_arg)?(_arg):"???")
  1125. // Description:
  1126. // A container for symbol properties. Each instance
  1127. // must be Initialized.
  1128. class SymbolProperties
  1129. {
  1130. public:
  1131. SymbolProperties();
  1132. // Description:
  1133. // The SymbolProperties instance must be initialized by
  1134. // passing a stack address.
  1135. void Initialize(void *address);
  1136. // Description:
  1137. // Get the symbol's stack address.
  1138. void *GetAddress() const { return this->Address; }
  1139. // Description:
  1140. // If not set paths will be removed. eg, from a binary
  1141. // or source file.
  1142. void SetReportPath(int rp){ this->ReportPath=rp; }
  1143. // Description:
  1144. // Set/Get the name of the binary file that the symbol
  1145. // is found in.
  1146. void SetBinary(const char *binary)
  1147. { this->Binary=safes(binary); }
  1148. std::string GetBinary() const;
  1149. // Description:
  1150. // Set the name of the function that the symbol is found in.
  1151. // If c++ demangling is supported it will be demangled.
  1152. void SetFunction(const char *function)
  1153. { this->Function=this->Demangle(function); }
  1154. std::string GetFunction() const
  1155. { return this->Function; }
  1156. // Description:
  1157. // Set/Get the name of the source file where the symbol
  1158. // is defined.
  1159. void SetSourceFile(const char *sourcefile)
  1160. { this->SourceFile=safes(sourcefile); }
  1161. std::string GetSourceFile() const
  1162. { return this->GetFileName(this->SourceFile); }
  1163. // Description:
  1164. // Set/Get the line number where the symbol is defined
  1165. void SetLineNumber(long linenumber){ this->LineNumber=linenumber; }
  1166. long GetLineNumber() const { return this->LineNumber; }
  1167. // Description:
  1168. // Set the address where the biinary image is mapped
  1169. // into memory.
  1170. void SetBinaryBaseAddress(void *address)
  1171. { this->BinaryBaseAddress=address; }
  1172. private:
  1173. void *GetRealAddress() const
  1174. { return (void*)((char*)this->Address-(char*)this->BinaryBaseAddress); }
  1175. std::string GetFileName(const std::string &path) const;
  1176. std::string Demangle(const char *symbol) const;
  1177. private:
  1178. std::string Binary;
  1179. void *BinaryBaseAddress;
  1180. void *Address;
  1181. std::string SourceFile;
  1182. std::string Function;
  1183. long LineNumber;
  1184. int ReportPath;
  1185. };
  1186. // --------------------------------------------------------------------------
  1187. std::ostream &operator<<(
  1188. std::ostream &os,
  1189. const SymbolProperties &sp)
  1190. {
  1191. #if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  1192. os
  1193. << std::hex << sp.GetAddress() << " : "
  1194. << sp.GetFunction()
  1195. << " [(" << sp.GetBinary() << ") "
  1196. << sp.GetSourceFile() << ":"
  1197. << std::dec << sp.GetLineNumber() << "]";
  1198. #elif defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  1199. void *addr = sp.GetAddress();
  1200. char **syminfo = backtrace_symbols(&addr,1);
  1201. os << safes(syminfo[0]);
  1202. free(syminfo);
  1203. #else
  1204. (void)os;
  1205. (void)sp;
  1206. #endif
  1207. return os;
  1208. }
  1209. // --------------------------------------------------------------------------
  1210. SymbolProperties::SymbolProperties()
  1211. {
  1212. // not using an initializer list
  1213. // to avoid some PGI compiler warnings
  1214. this->SetBinary("???");
  1215. this->SetBinaryBaseAddress(NULL);
  1216. this->Address = NULL;
  1217. this->SetSourceFile("???");
  1218. this->SetFunction("???");
  1219. this->SetLineNumber(-1);
  1220. this->SetReportPath(0);
  1221. // avoid PGI compiler warnings
  1222. this->GetRealAddress();
  1223. this->GetFunction();
  1224. this->GetSourceFile();
  1225. this->GetLineNumber();
  1226. }
  1227. // --------------------------------------------------------------------------
  1228. std::string SymbolProperties::GetFileName(const std::string &path) const
  1229. {
  1230. std::string file(path);
  1231. if (!this->ReportPath)
  1232. {
  1233. size_t at = file.rfind("/");
  1234. if (at!=std::string::npos)
  1235. {
  1236. file = file.substr(at+1,std::string::npos);
  1237. }
  1238. }
  1239. return file;
  1240. }
  1241. // --------------------------------------------------------------------------
  1242. std::string SymbolProperties::GetBinary() const
  1243. {
  1244. // only linux has proc fs
  1245. #if defined(__linux__)
  1246. if (this->Binary=="/proc/self/exe")
  1247. {
  1248. std::string binary;
  1249. char buf[1024]={'\0'};
  1250. ssize_t ll=0;
  1251. if ((ll=readlink("/proc/self/exe",buf,1024))>0)
  1252. {
  1253. buf[ll]='\0';
  1254. binary=buf;
  1255. }
  1256. else
  1257. {
  1258. binary="/proc/self/exe";
  1259. }
  1260. return this->GetFileName(binary);
  1261. }
  1262. #endif
  1263. return this->GetFileName(this->Binary);
  1264. }
  1265. // --------------------------------------------------------------------------
  1266. std::string SymbolProperties::Demangle(const char *symbol) const
  1267. {
  1268. std::string result = safes(symbol);
  1269. #if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
  1270. int status = 0;
  1271. size_t bufferLen = 1024;
  1272. char *buffer = (char*)malloc(1024);
  1273. char *demangledSymbol =
  1274. abi::__cxa_demangle(symbol, buffer, &bufferLen, &status);
  1275. if (!status)
  1276. {
  1277. result = demangledSymbol;
  1278. }
  1279. free(buffer);
  1280. #else
  1281. (void)symbol;
  1282. #endif
  1283. return result;
  1284. }
  1285. // --------------------------------------------------------------------------
  1286. void SymbolProperties::Initialize(void *address)
  1287. {
  1288. this->Address = address;
  1289. #if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  1290. // first fallback option can demangle c++ functions
  1291. Dl_info info;
  1292. int ierr=dladdr(this->Address,&info);
  1293. if (ierr && info.dli_sname && info.dli_saddr)
  1294. {
  1295. this->SetBinary(info.dli_fname);
  1296. this->SetFunction(info.dli_sname);
  1297. }
  1298. #else
  1299. // second fallback use builtin backtrace_symbols
  1300. // to decode the bactrace.
  1301. #endif
  1302. }
  1303. #endif // don't define this class if we're not using it
  1304. // --------------------------------------------------------------------------
  1305. #if defined(_WIN32) || defined(__CYGWIN__)
  1306. # define KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
  1307. #endif
  1308. #if defined(_MSC_VER) && _MSC_VER < 1310
  1309. # undef KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
  1310. #endif
  1311. #if defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
  1312. double calculateCPULoad(unsigned __int64 idleTicks,
  1313. unsigned __int64 totalTicks)
  1314. {
  1315. static double previousLoad = -0.0;
  1316. static unsigned __int64 previousIdleTicks = 0;
  1317. static unsigned __int64 previousTotalTicks = 0;
  1318. unsigned __int64 const idleTicksSinceLastTime =
  1319. idleTicks - previousIdleTicks;
  1320. unsigned __int64 const totalTicksSinceLastTime =
  1321. totalTicks - previousTotalTicks;
  1322. double load;
  1323. if (previousTotalTicks == 0 || totalTicksSinceLastTime == 0)
  1324. {
  1325. // No new information. Use previous result.
  1326. load = previousLoad;
  1327. }
  1328. else
  1329. {
  1330. // Calculate load since last time.
  1331. load = 1.0 - double(idleTicksSinceLastTime) / totalTicksSinceLastTime;
  1332. // Smooth if possible.
  1333. if (previousLoad > 0)
  1334. {
  1335. load = 0.25 * load + 0.75 * previousLoad;
  1336. }
  1337. }
  1338. previousLoad = load;
  1339. previousIdleTicks = idleTicks;
  1340. previousTotalTicks = totalTicks;
  1341. return load;
  1342. }
  1343. unsigned __int64 fileTimeToUInt64(FILETIME const& ft)
  1344. {
  1345. LARGE_INTEGER out;
  1346. out.HighPart = ft.dwHighDateTime;
  1347. out.LowPart = ft.dwLowDateTime;
  1348. return out.QuadPart;
  1349. }
  1350. #endif
  1351. } // anonymous namespace
  1352. SystemInformationImplementation::SystemInformationImplementation()
  1353. {
  1354. this->TotalVirtualMemory = 0;
  1355. this->AvailableVirtualMemory = 0;
  1356. this->TotalPhysicalMemory = 0;
  1357. this->AvailablePhysicalMemory = 0;
  1358. this->CurrentPositionInFile = 0;
  1359. this->ChipManufacturer = UnknownManufacturer;
  1360. memset(&this->Features, 0, sizeof(CPUFeatures));
  1361. this->ChipID.Type = 0;
  1362. this->ChipID.Family = 0;
  1363. this->ChipID.Model = 0;
  1364. this->ChipID.Revision = 0;
  1365. this->ChipID.ExtendedFamily = 0;
  1366. this->ChipID.ExtendedModel = 0;
  1367. this->CPUSpeedInMHz = 0;
  1368. this->NumberOfLogicalCPU = 0;
  1369. this->NumberOfPhysicalCPU = 0;
  1370. this->OSName = "";
  1371. this->Hostname = "";
  1372. this->OSRelease = "";
  1373. this->OSVersion = "";
  1374. this->OSPlatform = "";
  1375. }
  1376. SystemInformationImplementation::~SystemInformationImplementation()
  1377. {
  1378. }
  1379. void SystemInformationImplementation::RunCPUCheck()
  1380. {
  1381. #ifdef WIN32
  1382. // Check to see if this processor supports CPUID.
  1383. bool supportsCPUID = DoesCPUSupportCPUID();
  1384. if (supportsCPUID)
  1385. {
  1386. // Retrieve the CPU details.
  1387. RetrieveCPUIdentity();
  1388. this->FindManufacturer();
  1389. RetrieveCPUFeatures();
  1390. }
  1391. // These two may be called without support for the CPUID instruction.
  1392. // (But if the instruction is there, they should be called *after*
  1393. // the above call to RetrieveCPUIdentity... that's why the two if
  1394. // blocks exist with the same "if (supportsCPUID)" logic...
  1395. //
  1396. if (!RetrieveCPUClockSpeed())
  1397. {
  1398. RetrieveClassicalCPUClockSpeed();
  1399. }
  1400. if (supportsCPUID)
  1401. {
  1402. // Retrieve cache information.
  1403. if (!RetrieveCPUCacheDetails())
  1404. {
  1405. RetrieveClassicalCPUCacheDetails();
  1406. }
  1407. // Retrieve the extended CPU details.
  1408. if (!RetrieveExtendedCPUIdentity())
  1409. {
  1410. RetrieveClassicalCPUIdentity();
  1411. }
  1412. RetrieveExtendedCPUFeatures();
  1413. RetrieveCPUPowerManagement();
  1414. // Now attempt to retrieve the serial number (if possible).
  1415. RetrieveProcessorSerialNumber();
  1416. }
  1417. this->CPUCount();
  1418. #elif defined(__APPLE__)
  1419. this->ParseSysCtl();
  1420. #elif defined (__SVR4) && defined (__sun)
  1421. this->QuerySolarisProcessor();
  1422. #elif defined(__HAIKU__)
  1423. this->QueryHaikuInfo();
  1424. #elif defined(__QNX__)
  1425. this->QueryQNXProcessor();
  1426. #elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  1427. this->QueryBSDProcessor();
  1428. #elif defined(__hpux)
  1429. this->QueryHPUXProcessor();
  1430. #elif defined(__linux) || defined(__CYGWIN__)
  1431. this->RetreiveInformationFromCpuInfoFile();
  1432. #else
  1433. this->QueryProcessor();
  1434. #endif
  1435. }
  1436. void SystemInformationImplementation::RunOSCheck()
  1437. {
  1438. this->QueryOSInformation();
  1439. }
  1440. void SystemInformationImplementation::RunMemoryCheck()
  1441. {
  1442. #if defined(__APPLE__)
  1443. this->ParseSysCtl();
  1444. #elif defined (__SVR4) && defined (__sun)
  1445. this->QuerySolarisMemory();
  1446. #elif defined(__HAIKU__)
  1447. this->QueryHaikuInfo();
  1448. #elif defined(__QNX__)
  1449. this->QueryQNXMemory();
  1450. #elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  1451. this->QueryBSDMemory();
  1452. #elif defined(__CYGWIN__)
  1453. this->QueryCygwinMemory();
  1454. #elif defined(_WIN32)
  1455. this->QueryWindowsMemory();
  1456. #elif defined(__hpux)
  1457. this->QueryHPUXMemory();
  1458. #elif defined(__linux)
  1459. this->QueryLinuxMemory();
  1460. #elif defined(_AIX)
  1461. this->QueryAIXMemory();
  1462. #else
  1463. this->QueryMemory();
  1464. #endif
  1465. }
  1466. /** Get the vendor string */
  1467. const char * SystemInformationImplementation::GetVendorString()
  1468. {
  1469. return this->ChipID.Vendor.c_str();
  1470. }
  1471. /** Get the OS Name */
  1472. const char * SystemInformationImplementation::GetOSName()
  1473. {
  1474. return this->OSName.c_str();
  1475. }
  1476. /** Get the hostname */
  1477. const char* SystemInformationImplementation::GetHostname()
  1478. {
  1479. if (this->Hostname.empty())
  1480. {
  1481. this->Hostname="localhost";
  1482. #if defined(_WIN32)
  1483. WORD wVersionRequested;
  1484. WSADATA wsaData;
  1485. char name[255];
  1486. wVersionRequested = MAKEWORD(2,0);
  1487. if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
  1488. {
  1489. gethostname(name,sizeof(name));
  1490. WSACleanup( );
  1491. }
  1492. this->Hostname = name;
  1493. #else
  1494. struct utsname unameInfo;
  1495. int errorFlag = uname(&unameInfo);
  1496. if(errorFlag == 0)
  1497. {
  1498. this->Hostname = unameInfo.nodename;
  1499. }
  1500. #endif
  1501. }
  1502. return this->Hostname.c_str();
  1503. }
  1504. /** Get the FQDN */
  1505. int SystemInformationImplementation::GetFullyQualifiedDomainName(
  1506. std::string &fqdn)
  1507. {
  1508. // in the event of absolute failure return localhost.
  1509. fqdn="localhost";
  1510. #if defined(_WIN32)
  1511. int ierr;
  1512. // TODO - a more robust implementation for windows, see comments
  1513. // in unix implementation.
  1514. WSADATA wsaData;
  1515. WORD ver=MAKEWORD(2,0);
  1516. ierr=WSAStartup(ver,&wsaData);
  1517. if (ierr)
  1518. {
  1519. return -1;
  1520. }
  1521. char base[256]={'\0'};
  1522. ierr=gethostname(base,256);
  1523. if (ierr)
  1524. {
  1525. WSACleanup();
  1526. return -2;
  1527. }
  1528. fqdn=base;
  1529. HOSTENT *hent=gethostbyname(base);
  1530. if (hent)
  1531. {
  1532. fqdn=hent->h_name;
  1533. }
  1534. WSACleanup();
  1535. return 0;
  1536. #elif defined(KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN)
  1537. // gethostname typical returns an alias for loopback interface
  1538. // we want the fully qualified domain name. Because there are
  1539. // any number of interfaces on this system we look for the
  1540. // first of these that contains the name returned by gethostname
  1541. // and is longer. failing that we return gethostname and indicate
  1542. // with a failure code. Return of a failure code is not necessarilly
  1543. // an indication of an error. for instance gethostname may return
  1544. // the fully qualified domain name, or there may not be one if the
  1545. // system lives on a private network such as in the case of a cluster
  1546. // node.
  1547. int ierr=0;
  1548. char base[NI_MAXHOST];
  1549. ierr=gethostname(base,NI_MAXHOST);
  1550. if (ierr)
  1551. {
  1552. return -1;
  1553. }
  1554. size_t baseSize=strlen(base);
  1555. fqdn=base;
  1556. struct ifaddrs *ifas;
  1557. struct ifaddrs *ifa;
  1558. ierr=getifaddrs(&ifas);
  1559. if (ierr)
  1560. {
  1561. return -2;
  1562. }
  1563. for (ifa=ifas; ifa!=NULL; ifa=ifa->ifa_next)
  1564. {
  1565. int fam = ifa->ifa_addr? ifa->ifa_addr->sa_family : -1;
  1566. if ((fam==AF_INET) || (fam==AF_INET6))
  1567. {
  1568. char host[NI_MAXHOST]={'\0'};
  1569. const size_t addrlen
  1570. = (fam==AF_INET?sizeof(struct sockaddr_in):sizeof(struct sockaddr_in6));
  1571. ierr=getnameinfo(
  1572. ifa->ifa_addr,
  1573. static_cast<socklen_t>(addrlen),
  1574. host,
  1575. NI_MAXHOST,
  1576. NULL,
  1577. 0,
  1578. NI_NAMEREQD);
  1579. if (ierr)
  1580. {
  1581. // don't report the failure now since we may succeed on another
  1582. // interface. If all attempts fail then return the failure code.
  1583. ierr=-3;
  1584. continue;
  1585. }
  1586. std::string candidate=host;
  1587. if ((candidate.find(base)!=std::string::npos) && baseSize<candidate.size())
  1588. {
  1589. // success, stop now.
  1590. ierr=0;
  1591. fqdn=candidate;
  1592. break;
  1593. }
  1594. }
  1595. }
  1596. freeifaddrs(ifas);
  1597. return ierr;
  1598. #else
  1599. /* TODO: Implement on more platforms. */
  1600. fqdn=this->GetHostname();
  1601. return -1;
  1602. #endif
  1603. }
  1604. /** Get the OS release */
  1605. const char* SystemInformationImplementation::GetOSRelease()
  1606. {
  1607. return this->OSRelease.c_str();
  1608. }
  1609. /** Get the OS version */
  1610. const char* SystemInformationImplementation::GetOSVersion()
  1611. {
  1612. return this->OSVersion.c_str();
  1613. }
  1614. /** Get the OS platform */
  1615. const char* SystemInformationImplementation::GetOSPlatform()
  1616. {
  1617. return this->OSPlatform.c_str();
  1618. }
  1619. /** Get the vendor ID */
  1620. const char * SystemInformationImplementation::GetVendorID()
  1621. {
  1622. // Return the vendor ID.
  1623. switch (this->ChipManufacturer)
  1624. {
  1625. case Intel:
  1626. return "Intel Corporation";
  1627. case AMD:
  1628. return "Advanced Micro Devices";
  1629. case NSC:
  1630. return "National Semiconductor";
  1631. case Cyrix:
  1632. return "Cyrix Corp., VIA Inc.";
  1633. case NexGen:
  1634. return "NexGen Inc., Advanced Micro Devices";
  1635. case IDT:
  1636. return "IDT\\Centaur, Via Inc.";
  1637. case UMC:
  1638. return "United Microelectronics Corp.";
  1639. case Rise:
  1640. return "Rise";
  1641. case Transmeta:
  1642. return "Transmeta";
  1643. case Sun:
  1644. return "Sun Microelectronics";
  1645. case IBM:
  1646. return "IBM";
  1647. case Motorola:
  1648. return "Motorola";
  1649. case HP:
  1650. return "Hewlett-Packard";
  1651. case UnknownManufacturer:
  1652. default:
  1653. return "Unknown Manufacturer";
  1654. }
  1655. }
  1656. /** Return the type ID of the CPU */
  1657. std::string SystemInformationImplementation::GetTypeID()
  1658. {
  1659. std::ostringstream str;
  1660. str << this->ChipID.Type;
  1661. return str.str();
  1662. }
  1663. /** Return the family of the CPU present */
  1664. std::string SystemInformationImplementation::GetFamilyID()
  1665. {
  1666. std::ostringstream str;
  1667. str << this->ChipID.Family;
  1668. return str.str();
  1669. }
  1670. // Return the model of CPU present */
  1671. std::string SystemInformationImplementation::GetModelID()
  1672. {
  1673. std::ostringstream str;
  1674. str << this->ChipID.Model;
  1675. return str.str();
  1676. }
  1677. // Return the model name of CPU present */
  1678. std::string SystemInformationImplementation::GetModelName()
  1679. {
  1680. return this->ChipID.ModelName;
  1681. }
  1682. /** Return the stepping code of the CPU present. */
  1683. std::string SystemInformationImplementation::GetSteppingCode()
  1684. {
  1685. std::ostringstream str;
  1686. str << this->ChipID.Revision;
  1687. return str.str();
  1688. }
  1689. /** Return the stepping code of the CPU present. */
  1690. const char * SystemInformationImplementation::GetExtendedProcessorName()
  1691. {
  1692. return this->ChipID.ProcessorName.c_str();
  1693. }
  1694. /** Return the serial number of the processor
  1695. * in hexadecimal: xxxx-xxxx-xxxx-xxxx-xxxx-xxxx. */
  1696. const char * SystemInformationImplementation::GetProcessorSerialNumber()
  1697. {
  1698. return this->ChipID.SerialNumber.c_str();
  1699. }
  1700. /** Return the logical processors per physical */
  1701. unsigned int SystemInformationImplementation::GetLogicalProcessorsPerPhysical()
  1702. {
  1703. return this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical;
  1704. }
  1705. /** Return the processor clock frequency. */
  1706. float SystemInformationImplementation::GetProcessorClockFrequency()
  1707. {
  1708. return this->CPUSpeedInMHz;
  1709. }
  1710. /** Return the APIC ID. */
  1711. int SystemInformationImplementation::GetProcessorAPICID()
  1712. {
  1713. return this->Features.ExtendedFeatures.APIC_ID;
  1714. }
  1715. /** Return the L1 cache size. */
  1716. int SystemInformationImplementation::GetProcessorCacheSize()
  1717. {
  1718. return this->Features.L1CacheSize;
  1719. }
  1720. /** Return the chosen cache size. */
  1721. int SystemInformationImplementation::GetProcessorCacheXSize(long int dwCacheID)
  1722. {
  1723. switch (dwCacheID)
  1724. {
  1725. case L1CACHE_FEATURE:
  1726. return this->Features.L1CacheSize;
  1727. case L2CACHE_FEATURE:
  1728. return this->Features.L2CacheSize;
  1729. case L3CACHE_FEATURE:
  1730. return this->Features.L3CacheSize;
  1731. }
  1732. return -1;
  1733. }
  1734. bool SystemInformationImplementation::DoesCPUSupportFeature(long int dwFeature)
  1735. {
  1736. bool bHasFeature = false;
  1737. // Check for MMX instructions.
  1738. if (((dwFeature & MMX_FEATURE) != 0) && this->Features.HasMMX) bHasFeature = true;
  1739. // Check for MMX+ instructions.
  1740. if (((dwFeature & MMX_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.HasMMXPlus) bHasFeature = true;
  1741. // Check for SSE FP instructions.
  1742. if (((dwFeature & SSE_FEATURE) != 0) && this->Features.HasSSE) bHasFeature = true;
  1743. // Check for SSE FP instructions.
  1744. if (((dwFeature & SSE_FP_FEATURE) != 0) && this->Features.HasSSEFP) bHasFeature = true;
  1745. // Check for SSE MMX instructions.
  1746. if (((dwFeature & SSE_MMX_FEATURE) != 0) && this->Features.ExtendedFeatures.HasSSEMMX) bHasFeature = true;
  1747. // Check for SSE2 instructions.
  1748. if (((dwFeature & SSE2_FEATURE) != 0) && this->Features.HasSSE2) bHasFeature = true;
  1749. // Check for 3DNow! instructions.
  1750. if (((dwFeature & AMD_3DNOW_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNow) bHasFeature = true;
  1751. // Check for 3DNow+ instructions.
  1752. if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNowPlus) bHasFeature = true;
  1753. // Check for IA64 instructions.
  1754. if (((dwFeature & IA64_FEATURE) != 0) && this->Features.HasIA64) bHasFeature = true;
  1755. // Check for MP capable.
  1756. if (((dwFeature & MP_CAPABLE) != 0) && this->Features.ExtendedFeatures.SupportsMP) bHasFeature = true;
  1757. // Check for a serial number for the processor.
  1758. if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && this->Features.HasSerial) bHasFeature = true;
  1759. // Check for a local APIC in the processor.
  1760. if (((dwFeature & APIC_FEATURE) != 0) && this->Features.HasAPIC) bHasFeature = true;
  1761. // Check for CMOV instructions.
  1762. if (((dwFeature & CMOV_FEATURE) != 0) && this->Features.HasCMOV) bHasFeature = true;
  1763. // Check for MTRR instructions.
  1764. if (((dwFeature & MTRR_FEATURE) != 0) && this->Features.HasMTRR) bHasFeature = true;
  1765. // Check for L1 cache size.
  1766. if (((dwFeature & L1CACHE_FEATURE) != 0) && (this->Features.L1CacheSize != -1)) bHasFeature = true;
  1767. // Check for L2 cache size.
  1768. if (((dwFeature & L2CACHE_FEATURE) != 0) && (this->Features.L2CacheSize != -1)) bHasFeature = true;
  1769. // Check for L3 cache size.
  1770. if (((dwFeature & L3CACHE_FEATURE) != 0) && (this->Features.L3CacheSize != -1)) bHasFeature = true;
  1771. // Check for ACPI capability.
  1772. if (((dwFeature & ACPI_FEATURE) != 0) && this->Features.HasACPI) bHasFeature = true;
  1773. // Check for thermal monitor support.
  1774. if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && this->Features.HasThermal) bHasFeature = true;
  1775. // Check for temperature sensing diode support.
  1776. if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode) bHasFeature = true;
  1777. // Check for frequency ID support.
  1778. if (((dwFeature & FREQUENCYID_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID) bHasFeature = true;
  1779. // Check for voltage ID support.
  1780. if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasVoltageID) bHasFeature = true;
  1781. return bHasFeature;
  1782. }
  1783. void SystemInformationImplementation::Delay(unsigned int uiMS)
  1784. {
  1785. #ifdef WIN32
  1786. LARGE_INTEGER Frequency, StartCounter, EndCounter;
  1787. __int64 x;
  1788. // Get the frequency of the high performance counter.
  1789. if (!QueryPerformanceFrequency (&Frequency)) return;
  1790. x = Frequency.QuadPart / 1000 * uiMS;
  1791. // Get the starting position of the counter.
  1792. QueryPerformanceCounter (&StartCounter);
  1793. do {
  1794. // Get the ending position of the counter.
  1795. QueryPerformanceCounter (&EndCounter);
  1796. } while (EndCounter.QuadPart - StartCounter.QuadPart < x);
  1797. #endif
  1798. (void)uiMS;
  1799. }
  1800. bool SystemInformationImplementation::DoesCPUSupportCPUID()
  1801. {
  1802. #if USE_CPUID
  1803. int dummy[4] = { 0, 0, 0, 0 };
  1804. #if USE_ASM_INSTRUCTIONS
  1805. return call_cpuid(0, dummy);
  1806. #else
  1807. call_cpuid(0, dummy);
  1808. return dummy[0] || dummy[1] || dummy[2] || dummy[3];
  1809. #endif
  1810. #else
  1811. // Assume no cpuid instruction.
  1812. return false;
  1813. #endif
  1814. }
  1815. bool SystemInformationImplementation::RetrieveCPUFeatures()
  1816. {
  1817. #if USE_CPUID
  1818. int cpuinfo[4] = { 0, 0, 0, 0 };
  1819. if (!call_cpuid(1, cpuinfo))
  1820. {
  1821. return false;
  1822. }
  1823. // Retrieve the features of CPU present.
  1824. this->Features.HasFPU = ((cpuinfo[3] & 0x00000001) != 0); // FPU Present --> Bit 0
  1825. this->Features.HasTSC = ((cpuinfo[3] & 0x00000010) != 0); // TSC Present --> Bit 4
  1826. this->Features.HasAPIC = ((cpuinfo[3] & 0x00000200) != 0); // APIC Present --> Bit 9
  1827. this->Features.HasMTRR = ((cpuinfo[3] & 0x00001000) != 0); // MTRR Present --> Bit 12
  1828. this->Features.HasCMOV = ((cpuinfo[3] & 0x00008000) != 0); // CMOV Present --> Bit 15
  1829. this->Features.HasSerial = ((cpuinfo[3] & 0x00040000) != 0); // Serial Present --> Bit 18
  1830. this->Features.HasACPI = ((cpuinfo[3] & 0x00400000) != 0); // ACPI Capable --> Bit 22
  1831. this->Features.HasMMX = ((cpuinfo[3] & 0x00800000) != 0); // MMX Present --> Bit 23
  1832. this->Features.HasSSE = ((cpuinfo[3] & 0x02000000) != 0); // SSE Present --> Bit 25
  1833. this->Features.HasSSE2 = ((cpuinfo[3] & 0x04000000) != 0); // SSE2 Present --> Bit 26
  1834. this->Features.HasThermal = ((cpuinfo[3] & 0x20000000) != 0); // Thermal Monitor Present --> Bit 29
  1835. this->Features.HasIA64 = ((cpuinfo[3] & 0x40000000) != 0); // IA64 Present --> Bit 30
  1836. #if USE_ASM_INSTRUCTIONS
  1837. // Retrieve extended SSE capabilities if SSE is available.
  1838. if (this->Features.HasSSE) {
  1839. // Attempt to __try some SSE FP instructions.
  1840. __try
  1841. {
  1842. // Perform: orps xmm0, xmm0
  1843. _asm
  1844. {
  1845. _emit 0x0f
  1846. _emit 0x56
  1847. _emit 0xc0
  1848. }
  1849. // SSE FP capable processor.
  1850. this->Features.HasSSEFP = true;
  1851. }
  1852. __except(1)
  1853. {
  1854. // bad instruction - processor or OS cannot handle SSE FP.
  1855. this->Features.HasSSEFP = false;
  1856. }
  1857. }
  1858. else
  1859. {
  1860. // Set the advanced SSE capabilities to not available.
  1861. this->Features.HasSSEFP = false;
  1862. }
  1863. #else
  1864. this->Features.HasSSEFP = false;
  1865. #endif
  1866. // Retrieve Intel specific extended features.
  1867. if (this->ChipManufacturer == Intel)
  1868. {
  1869. this->Features.ExtendedFeatures.SupportsHyperthreading = ((cpuinfo[3] & 0x10000000) != 0); // Intel specific: Hyperthreading --> Bit 28
  1870. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = (this->Features.ExtendedFeatures.SupportsHyperthreading) ? ((cpuinfo[1] & 0x00FF0000) >> 16) : 1;
  1871. if ((this->Features.ExtendedFeatures.SupportsHyperthreading) && (this->Features.HasAPIC))
  1872. {
  1873. // Retrieve APIC information if there is one present.
  1874. this->Features.ExtendedFeatures.APIC_ID = ((cpuinfo[1] & 0xFF000000) >> 24);
  1875. }
  1876. }
  1877. return true;
  1878. #else
  1879. return false;
  1880. #endif
  1881. }
  1882. /** Find the manufacturer given the vendor id */
  1883. void SystemInformationImplementation::FindManufacturer(const std::string& family)
  1884. {
  1885. if (this->ChipID.Vendor == "GenuineIntel") this->ChipManufacturer = Intel; // Intel Corp.
  1886. else if (this->ChipID.Vendor == "UMC UMC UMC ") this->ChipManufacturer = UMC; // United Microelectronics Corp.
  1887. else if (this->ChipID.Vendor == "AuthenticAMD") this->ChipManufacturer = AMD; // Advanced Micro Devices
  1888. else if (this->ChipID.Vendor == "AMD ISBETTER") this->ChipManufacturer = AMD; // Advanced Micro Devices (1994)
  1889. else if (this->ChipID.Vendor == "CyrixInstead") this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc.
  1890. else if (this->ChipID.Vendor == "NexGenDriven") this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
  1891. else if (this->ChipID.Vendor == "CentaurHauls") this->ChipManufacturer = IDT; // IDT/Centaur (now VIA)
  1892. else if (this->ChipID.Vendor == "RiseRiseRise") this->ChipManufacturer = Rise; // Rise
  1893. else if (this->ChipID.Vendor == "GenuineTMx86") this->ChipManufacturer = Transmeta; // Transmeta
  1894. else if (this->ChipID.Vendor == "TransmetaCPU") this->ChipManufacturer = Transmeta; // Transmeta
  1895. else if (this->ChipID.Vendor == "Geode By NSC") this->ChipManufacturer = NSC; // National Semiconductor
  1896. else if (this->ChipID.Vendor == "Sun") this->ChipManufacturer = Sun; // Sun Microelectronics
  1897. else if (this->ChipID.Vendor == "IBM") this->ChipManufacturer = IBM; // IBM Microelectronics
  1898. else if (this->ChipID.Vendor == "Hewlett-Packard") this->ChipManufacturer = HP; // Hewlett-Packard
  1899. else if (this->ChipID.Vendor == "Motorola") this->ChipManufacturer = Motorola; // Motorola Microelectronics
  1900. else if (family.substr(0, 7) == "PA-RISC") this->ChipManufacturer = HP; // Hewlett-Packard
  1901. else this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
  1902. }
  1903. /** */
  1904. bool SystemInformationImplementation::RetrieveCPUIdentity()
  1905. {
  1906. #if USE_CPUID
  1907. int localCPUVendor[4];
  1908. int localCPUSignature[4];
  1909. if (!call_cpuid(0, localCPUVendor))
  1910. {
  1911. return false;
  1912. }
  1913. if (!call_cpuid(1, localCPUSignature))
  1914. {
  1915. return false;
  1916. }
  1917. // Process the returned information.
  1918. // ; eax = 0 --> eax: maximum value of CPUID instruction.
  1919. // ; ebx: part 1 of 3; CPU signature.
  1920. // ; edx: part 2 of 3; CPU signature.
  1921. // ; ecx: part 3 of 3; CPU signature.
  1922. char vbuf[13];
  1923. memcpy (&(vbuf[0]), &(localCPUVendor[1]), sizeof (int));
  1924. memcpy (&(vbuf[4]), &(localCPUVendor[3]), sizeof (int));
  1925. memcpy (&(vbuf[8]), &(localCPUVendor[2]), sizeof (int));
  1926. vbuf[12] = '\0';
  1927. this->ChipID.Vendor = vbuf;
  1928. // Retrieve the family of CPU present.
  1929. // ; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
  1930. // ; ebx: 31..24 - default APIC ID, 23..16 - logical processor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
  1931. // ; edx: CPU feature flags
  1932. this->ChipID.ExtendedFamily = ((localCPUSignature[0] & 0x0FF00000) >> 20); // Bits 27..20 Used
  1933. this->ChipID.ExtendedModel = ((localCPUSignature[0] & 0x000F0000) >> 16); // Bits 19..16 Used
  1934. this->ChipID.Type = ((localCPUSignature[0] & 0x0000F000) >> 12); // Bits 15..12 Used
  1935. this->ChipID.Family = ((localCPUSignature[0] & 0x00000F00) >> 8); // Bits 11..8 Used
  1936. this->ChipID.Model = ((localCPUSignature[0] & 0x000000F0) >> 4); // Bits 7..4 Used
  1937. this->ChipID.Revision = ((localCPUSignature[0] & 0x0000000F) >> 0); // Bits 3..0 Used
  1938. return true;
  1939. #else
  1940. return false;
  1941. #endif
  1942. }
  1943. /** */
  1944. bool SystemInformationImplementation::RetrieveCPUCacheDetails()
  1945. {
  1946. #if USE_CPUID
  1947. int L1Cache[4] = { 0, 0, 0, 0 };
  1948. int L2Cache[4] = { 0, 0, 0, 0 };
  1949. // Check to see if what we are about to do is supported...
  1950. if (RetrieveCPUExtendedLevelSupport (0x80000005))
  1951. {
  1952. if (!call_cpuid(0x80000005, L1Cache))
  1953. {
  1954. return false;
  1955. }
  1956. // Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as data cache size from edx: bits 31..24.
  1957. this->Features.L1CacheSize = ((L1Cache[2] & 0xFF000000) >> 24);
  1958. this->Features.L1CacheSize += ((L1Cache[3] & 0xFF000000) >> 24);
  1959. }
  1960. else
  1961. {
  1962. // Store -1 to indicate the cache could not be queried.
  1963. this->Features.L1CacheSize = -1;
  1964. }
  1965. // Check to see if what we are about to do is supported...
  1966. if (RetrieveCPUExtendedLevelSupport (0x80000006))
  1967. {
  1968. if (!call_cpuid(0x80000006, L2Cache))
  1969. {
  1970. return false;
  1971. }
  1972. // Save the L2 unified cache size (in KB) from ecx: bits 31..16.
  1973. this->Features.L2CacheSize = ((L2Cache[2] & 0xFFFF0000) >> 16);
  1974. }
  1975. else
  1976. {
  1977. // Store -1 to indicate the cache could not be queried.
  1978. this->Features.L2CacheSize = -1;
  1979. }
  1980. // Define L3 as being not present as we cannot test for it.
  1981. this->Features.L3CacheSize = -1;
  1982. #endif
  1983. // Return failure if we cannot detect either cache with this method.
  1984. return ((this->Features.L1CacheSize == -1) && (this->Features.L2CacheSize == -1)) ? false : true;
  1985. }
  1986. /** */
  1987. bool SystemInformationImplementation::RetrieveClassicalCPUCacheDetails()
  1988. {
  1989. #if USE_CPUID
  1990. int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1, L2Unified = -1, L3Unified = -1;
  1991. int TLBCacheData[4] = { 0, 0, 0, 0 };
  1992. int TLBPassCounter = 0;
  1993. int TLBCacheUnit = 0;
  1994. do {
  1995. if (!call_cpuid(2, TLBCacheData))
  1996. {
  1997. return false;
  1998. }
  1999. int bob = ((TLBCacheData[0] & 0x00FF0000) >> 16);
  2000. (void)bob;
  2001. // Process the returned TLB and cache information.
  2002. for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter ++)
  2003. {
  2004. // First of all - decide which unit we are dealing with.
  2005. switch (nCounter)
  2006. {
  2007. // eax: bits 8..15 : bits 16..23 : bits 24..31
  2008. case 0: TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8); break;
  2009. case 1: TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16); break;
  2010. case 2: TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24); break;
  2011. // ebx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
  2012. case 3: TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0); break;
  2013. case 4: TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8); break;
  2014. case 5: TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16); break;
  2015. case 6: TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24); break;
  2016. // ecx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
  2017. case 7: TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0); break;
  2018. case 8: TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8); break;
  2019. case 9: TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16); break;
  2020. case 10: TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24); break;
  2021. // edx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
  2022. case 11: TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0); break;
  2023. case 12: TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8); break;
  2024. case 13: TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16); break;
  2025. case 14: TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24); break;
  2026. // Default case - an error has occured.
  2027. default: return false;
  2028. }
  2029. // Now process the resulting unit to see what it means....
  2030. switch (TLBCacheUnit)
  2031. {
  2032. case 0x00: break;
  2033. case 0x01: STORE_TLBCACHE_INFO (TLBCode, 4); break;
  2034. case 0x02: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2035. case 0x03: STORE_TLBCACHE_INFO (TLBData, 4); break;
  2036. case 0x04: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2037. case 0x06: STORE_TLBCACHE_INFO (L1Code, 8); break;
  2038. case 0x08: STORE_TLBCACHE_INFO (L1Code, 16); break;
  2039. case 0x0a: STORE_TLBCACHE_INFO (L1Data, 8); break;
  2040. case 0x0c: STORE_TLBCACHE_INFO (L1Data, 16); break;
  2041. case 0x10: STORE_TLBCACHE_INFO (L1Data, 16); break; // <-- FIXME: IA-64 Only
  2042. case 0x15: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
  2043. case 0x1a: STORE_TLBCACHE_INFO (L2Unified, 96); break; // <-- FIXME: IA-64 Only
  2044. case 0x22: STORE_TLBCACHE_INFO (L3Unified, 512); break;
  2045. case 0x23: STORE_TLBCACHE_INFO (L3Unified, 1024); break;
  2046. case 0x25: STORE_TLBCACHE_INFO (L3Unified, 2048); break;
  2047. case 0x29: STORE_TLBCACHE_INFO (L3Unified, 4096); break;
  2048. case 0x39: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2049. case 0x3c: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2050. case 0x40: STORE_TLBCACHE_INFO (L2Unified, 0); break; // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4 core).
  2051. case 0x41: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2052. case 0x42: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2053. case 0x43: STORE_TLBCACHE_INFO (L2Unified, 512); break;
  2054. case 0x44: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
  2055. case 0x45: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
  2056. case 0x50: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2057. case 0x51: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2058. case 0x52: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2059. case 0x5b: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2060. case 0x5c: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2061. case 0x5d: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2062. case 0x66: STORE_TLBCACHE_INFO (L1Data, 8); break;
  2063. case 0x67: STORE_TLBCACHE_INFO (L1Data, 16); break;
  2064. case 0x68: STORE_TLBCACHE_INFO (L1Data, 32); break;
  2065. case 0x70: STORE_TLBCACHE_INFO (L1Trace, 12); break;
  2066. case 0x71: STORE_TLBCACHE_INFO (L1Trace, 16); break;
  2067. case 0x72: STORE_TLBCACHE_INFO (L1Trace, 32); break;
  2068. case 0x77: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
  2069. case 0x79: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2070. case 0x7a: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2071. case 0x7b: STORE_TLBCACHE_INFO (L2Unified, 512); break;
  2072. case 0x7c: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
  2073. case 0x7e: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2074. case 0x81: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2075. case 0x82: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2076. case 0x83: STORE_TLBCACHE_INFO (L2Unified, 512); break;
  2077. case 0x84: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
  2078. case 0x85: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
  2079. case 0x88: STORE_TLBCACHE_INFO (L3Unified, 2048); break; // <-- FIXME: IA-64 Only
  2080. case 0x89: STORE_TLBCACHE_INFO (L3Unified, 4096); break; // <-- FIXME: IA-64 Only
  2081. case 0x8a: STORE_TLBCACHE_INFO (L3Unified, 8192); break; // <-- FIXME: IA-64 Only
  2082. case 0x8d: STORE_TLBCACHE_INFO (L3Unified, 3096); break; // <-- FIXME: IA-64 Only
  2083. case 0x90: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
  2084. case 0x96: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
  2085. case 0x9b: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
  2086. // Default case - an error has occured.
  2087. default: return false;
  2088. }
  2089. }
  2090. // Increment the TLB pass counter.
  2091. TLBPassCounter ++;
  2092. } while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
  2093. // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
  2094. if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1))
  2095. {
  2096. this->Features.L1CacheSize = -1;
  2097. }
  2098. else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1))
  2099. {
  2100. this->Features.L1CacheSize = L1Trace;
  2101. }
  2102. else if ((L1Code != -1) && (L1Data == -1))
  2103. {
  2104. this->Features.L1CacheSize = L1Code;
  2105. }
  2106. else if ((L1Code == -1) && (L1Data != -1))
  2107. {
  2108. this->Features.L1CacheSize = L1Data;
  2109. }
  2110. else if ((L1Code != -1) && (L1Data != -1))
  2111. {
  2112. this->Features.L1CacheSize = L1Code + L1Data;
  2113. }
  2114. else
  2115. {
  2116. this->Features.L1CacheSize = -1;
  2117. }
  2118. // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
  2119. if (L2Unified == -1)
  2120. {
  2121. this->Features.L2CacheSize = -1;
  2122. }
  2123. else
  2124. {
  2125. this->Features.L2CacheSize = L2Unified;
  2126. }
  2127. // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
  2128. if (L3Unified == -1)
  2129. {
  2130. this->Features.L3CacheSize = -1;
  2131. }
  2132. else
  2133. {
  2134. this->Features.L3CacheSize = L3Unified;
  2135. }
  2136. return true;
  2137. #else
  2138. return false;
  2139. #endif
  2140. }
  2141. /** */
  2142. bool SystemInformationImplementation::RetrieveCPUClockSpeed()
  2143. {
  2144. bool retrieved = false;
  2145. #if defined(_WIN32)
  2146. unsigned int uiRepetitions = 1;
  2147. unsigned int uiMSecPerRepetition = 50;
  2148. __int64 i64Total = 0;
  2149. __int64 i64Overhead = 0;
  2150. // Check if the TSC implementation works at all
  2151. if (this->Features.HasTSC &&
  2152. GetCyclesDifference(SystemInformationImplementation::Delay,
  2153. uiMSecPerRepetition) > 0)
  2154. {
  2155. for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter ++)
  2156. {
  2157. i64Total += GetCyclesDifference (SystemInformationImplementation::Delay,
  2158. uiMSecPerRepetition);
  2159. i64Overhead +=
  2160. GetCyclesDifference (SystemInformationImplementation::DelayOverhead,
  2161. uiMSecPerRepetition);
  2162. }
  2163. // Calculate the MHz speed.
  2164. i64Total -= i64Overhead;
  2165. i64Total /= uiRepetitions;
  2166. i64Total /= uiMSecPerRepetition;
  2167. i64Total /= 1000;
  2168. // Save the CPU speed.
  2169. this->CPUSpeedInMHz = (float) i64Total;
  2170. retrieved = true;
  2171. }
  2172. // If RDTSC is not supported, we fallback to trying to read this value
  2173. // from the registry:
  2174. if (!retrieved)
  2175. {
  2176. HKEY hKey = NULL;
  2177. LONG err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
  2178. L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
  2179. KEY_READ, &hKey);
  2180. if (ERROR_SUCCESS == err)
  2181. {
  2182. DWORD dwType = 0;
  2183. DWORD data = 0;
  2184. DWORD dwSize = sizeof(DWORD);
  2185. err = RegQueryValueExW(hKey, L"~MHz", 0,
  2186. &dwType, (LPBYTE) &data, &dwSize);
  2187. if (ERROR_SUCCESS == err)
  2188. {
  2189. this->CPUSpeedInMHz = (float) data;
  2190. retrieved = true;
  2191. }
  2192. RegCloseKey(hKey);
  2193. hKey = NULL;
  2194. }
  2195. }
  2196. #endif
  2197. return retrieved;
  2198. }
  2199. /** */
  2200. bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
  2201. {
  2202. #if USE_ASM_INSTRUCTIONS
  2203. LARGE_INTEGER liStart, liEnd, liCountsPerSecond;
  2204. double dFrequency, dDifference;
  2205. // Attempt to get a starting tick count.
  2206. QueryPerformanceCounter (&liStart);
  2207. __try
  2208. {
  2209. _asm
  2210. {
  2211. mov eax, 0x80000000
  2212. mov ebx, CLASSICAL_CPU_FREQ_LOOP
  2213. Timer_Loop:
  2214. bsf ecx,eax
  2215. dec ebx
  2216. jnz Timer_Loop
  2217. }
  2218. }
  2219. __except(1)
  2220. {
  2221. return false;
  2222. }
  2223. // Attempt to get a starting tick count.
  2224. QueryPerformanceCounter (&liEnd);
  2225. // Get the difference... NB: This is in seconds....
  2226. QueryPerformanceFrequency (&liCountsPerSecond);
  2227. dDifference = (((double) liEnd.QuadPart - (double) liStart.QuadPart) / (double) liCountsPerSecond.QuadPart);
  2228. // Calculate the clock speed.
  2229. if (this->ChipID.Family == 3)
  2230. {
  2231. // 80386 processors.... Loop time is 115 cycles!
  2232. dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1000000);
  2233. }
  2234. else if (this->ChipID.Family == 4)
  2235. {
  2236. // 80486 processors.... Loop time is 47 cycles!
  2237. dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1000000);
  2238. }
  2239. else if (this->ChipID.Family == 5)
  2240. {
  2241. // Pentium processors.... Loop time is 43 cycles!
  2242. dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1000000);
  2243. }
  2244. // Save the clock speed.
  2245. this->Features.CPUSpeed = (int) dFrequency;
  2246. return true;
  2247. #else
  2248. return false;
  2249. #endif
  2250. }
  2251. /** */
  2252. bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULevelToCheck)
  2253. {
  2254. int cpuinfo[4] = { 0, 0, 0, 0 };
  2255. // The extended CPUID is supported by various vendors starting with the following CPU models:
  2256. //
  2257. // Manufacturer & Chip Name | Family Model Revision
  2258. //
  2259. // AMD K6, K6-2 | 5 6 x
  2260. // Cyrix GXm, Cyrix III "Joshua" | 5 4 x
  2261. // IDT C6-2 | 5 8 x
  2262. // VIA Cyrix III | 6 5 x
  2263. // Transmeta Crusoe | 5 x x
  2264. // Intel Pentium 4 | f x x
  2265. //
  2266. // We check to see if a supported processor is present...
  2267. if (this->ChipManufacturer == AMD)
  2268. {
  2269. if (this->ChipID.Family < 5) return false;
  2270. if ((this->ChipID.Family == 5) && (this->ChipID.Model < 6)) return false;
  2271. }
  2272. else if (this->ChipManufacturer == Cyrix)
  2273. {
  2274. if (this->ChipID.Family < 5) return false;
  2275. if ((this->ChipID.Family == 5) && (this->ChipID.Model < 4)) return false;
  2276. if ((this->ChipID.Family == 6) && (this->ChipID.Model < 5)) return false;
  2277. }
  2278. else if (this->ChipManufacturer == IDT)
  2279. {
  2280. if (this->ChipID.Family < 5) return false;
  2281. if ((this->ChipID.Family == 5) && (this->ChipID.Model < 8)) return false;
  2282. }
  2283. else if (this->ChipManufacturer == Transmeta)
  2284. {
  2285. if (this->ChipID.Family < 5) return false;
  2286. }
  2287. else if (this->ChipManufacturer == Intel)
  2288. {
  2289. if (this->ChipID.Family < 0xf)
  2290. {
  2291. return false;
  2292. }
  2293. }
  2294. #if USE_CPUID
  2295. if (!call_cpuid(0x80000000, cpuinfo))
  2296. {
  2297. return false;
  2298. }
  2299. #endif
  2300. // Now we have to check the level wanted vs level returned...
  2301. int nLevelWanted = (CPULevelToCheck & 0x7FFFFFFF);
  2302. int nLevelReturn = (cpuinfo[0] & 0x7FFFFFFF);
  2303. // Check to see if the level provided is supported...
  2304. if (nLevelWanted > nLevelReturn)
  2305. {
  2306. return false;
  2307. }
  2308. return true;
  2309. }
  2310. /** */
  2311. bool SystemInformationImplementation::RetrieveExtendedCPUFeatures()
  2312. {
  2313. // Check that we are not using an Intel processor as it does not support this.
  2314. if (this->ChipManufacturer == Intel)
  2315. {
  2316. return false;
  2317. }
  2318. // Check to see if what we are about to do is supported...
  2319. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001)))
  2320. {
  2321. return false;
  2322. }
  2323. #if USE_CPUID
  2324. int localCPUExtendedFeatures[4] = { 0, 0, 0, 0 };
  2325. if (!call_cpuid(0x80000001, localCPUExtendedFeatures))
  2326. {
  2327. return false;
  2328. }
  2329. // Retrieve the extended features of CPU present.
  2330. this->Features.ExtendedFeatures.Has3DNow = ((localCPUExtendedFeatures[3] & 0x80000000) != 0); // 3DNow Present --> Bit 31.
  2331. this->Features.ExtendedFeatures.Has3DNowPlus = ((localCPUExtendedFeatures[3] & 0x40000000) != 0); // 3DNow+ Present -- > Bit 30.
  2332. this->Features.ExtendedFeatures.HasSSEMMX = ((localCPUExtendedFeatures[3] & 0x00400000) != 0); // SSE MMX Present --> Bit 22.
  2333. this->Features.ExtendedFeatures.SupportsMP = ((localCPUExtendedFeatures[3] & 0x00080000) != 0); // MP Capable -- > Bit 19.
  2334. // Retrieve AMD specific extended features.
  2335. if (this->ChipManufacturer == AMD)
  2336. {
  2337. this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x00400000) != 0); // AMD specific: MMX-SSE --> Bit 22
  2338. }
  2339. // Retrieve Cyrix specific extended features.
  2340. if (this->ChipManufacturer == Cyrix)
  2341. {
  2342. this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x01000000) != 0); // Cyrix specific: Extended MMX --> Bit 24
  2343. }
  2344. return true;
  2345. #else
  2346. return false;
  2347. #endif
  2348. }
  2349. /** */
  2350. bool SystemInformationImplementation::RetrieveProcessorSerialNumber()
  2351. {
  2352. // Check to see if the processor supports the processor serial number.
  2353. if (!this->Features.HasSerial)
  2354. {
  2355. return false;
  2356. }
  2357. #if USE_CPUID
  2358. int SerialNumber[4];
  2359. if (!call_cpuid(3, SerialNumber))
  2360. {
  2361. return false;
  2362. }
  2363. // Process the returned information.
  2364. // ; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB: Transmeta only ?!?
  2365. // ; ecx: middle 32 bits are the processor signature bits
  2366. // ; edx: bottom 32 bits are the processor signature bits
  2367. char sn[128];
  2368. sprintf (sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x",
  2369. ((SerialNumber[1] & 0xff000000) >> 24),
  2370. ((SerialNumber[1] & 0x00ff0000) >> 16),
  2371. ((SerialNumber[1] & 0x0000ff00) >> 8),
  2372. ((SerialNumber[1] & 0x000000ff) >> 0),
  2373. ((SerialNumber[2] & 0xff000000) >> 24),
  2374. ((SerialNumber[2] & 0x00ff0000) >> 16),
  2375. ((SerialNumber[2] & 0x0000ff00) >> 8),
  2376. ((SerialNumber[2] & 0x000000ff) >> 0),
  2377. ((SerialNumber[3] & 0xff000000) >> 24),
  2378. ((SerialNumber[3] & 0x00ff0000) >> 16),
  2379. ((SerialNumber[3] & 0x0000ff00) >> 8),
  2380. ((SerialNumber[3] & 0x000000ff) >> 0));
  2381. this->ChipID.SerialNumber = sn;
  2382. return true;
  2383. #else
  2384. return false;
  2385. #endif
  2386. }
  2387. /** */
  2388. bool SystemInformationImplementation::RetrieveCPUPowerManagement()
  2389. {
  2390. // Check to see if what we are about to do is supported...
  2391. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007)))
  2392. {
  2393. this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = false;
  2394. this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = false;
  2395. this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = false;
  2396. return false;
  2397. }
  2398. #if USE_CPUID
  2399. int localCPUPowerManagement[4] = { 0, 0, 0, 0 };
  2400. if (!call_cpuid(0x80000007, localCPUPowerManagement))
  2401. {
  2402. return false;
  2403. }
  2404. // Check for the power management capabilities of the CPU.
  2405. this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = ((localCPUPowerManagement[3] & 0x00000001) != 0);
  2406. this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = ((localCPUPowerManagement[3] & 0x00000002) != 0);
  2407. this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = ((localCPUPowerManagement[3] & 0x00000004) != 0);
  2408. return true;
  2409. #else
  2410. return false;
  2411. #endif
  2412. }
  2413. #if USE_CPUID
  2414. // Used only in USE_CPUID implementation below.
  2415. static void SystemInformationStripLeadingSpace(std::string& str)
  2416. {
  2417. // Because some manufacturers have leading white space - we have to post-process the name.
  2418. std::string::size_type pos = str.find_first_not_of(" ");
  2419. if(pos != std::string::npos)
  2420. {
  2421. str = str.substr(pos);
  2422. }
  2423. }
  2424. #endif
  2425. /** */
  2426. bool SystemInformationImplementation::RetrieveExtendedCPUIdentity()
  2427. {
  2428. // Check to see if what we are about to do is supported...
  2429. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000002)))
  2430. return false;
  2431. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000003)))
  2432. return false;
  2433. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000004)))
  2434. return false;
  2435. #if USE_CPUID
  2436. int CPUExtendedIdentity[12];
  2437. if (!call_cpuid(0x80000002, CPUExtendedIdentity))
  2438. {
  2439. return false;
  2440. }
  2441. if (!call_cpuid(0x80000003, CPUExtendedIdentity + 4))
  2442. {
  2443. return false;
  2444. }
  2445. if (!call_cpuid(0x80000004, CPUExtendedIdentity + 8))
  2446. {
  2447. return false;
  2448. }
  2449. // Process the returned information.
  2450. char nbuf[49];
  2451. memcpy (&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof (int));
  2452. memcpy (&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof (int));
  2453. memcpy (&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof (int));
  2454. memcpy (&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof (int));
  2455. memcpy (&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof (int));
  2456. memcpy (&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof (int));
  2457. memcpy (&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof (int));
  2458. memcpy (&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof (int));
  2459. memcpy (&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof (int));
  2460. memcpy (&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof (int));
  2461. memcpy (&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof (int));
  2462. memcpy (&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof (int));
  2463. nbuf[48] = '\0';
  2464. this->ChipID.ProcessorName = nbuf;
  2465. this->ChipID.ModelName = nbuf;
  2466. // Because some manufacturers have leading white space - we have to post-process the name.
  2467. SystemInformationStripLeadingSpace(this->ChipID.ProcessorName);
  2468. return true;
  2469. #else
  2470. return false;
  2471. #endif
  2472. }
  2473. /** */
  2474. bool SystemInformationImplementation::RetrieveClassicalCPUIdentity()
  2475. {
  2476. // Start by decided which manufacturer we are using....
  2477. switch (this->ChipManufacturer)
  2478. {
  2479. case Intel:
  2480. // Check the family / model / revision to determine the CPU ID.
  2481. switch (this->ChipID.Family) {
  2482. case 3:
  2483. this->ChipID.ProcessorName = "Newer i80386 family";
  2484. break;
  2485. case 4:
  2486. switch (this->ChipID.Model) {
  2487. case 0: this->ChipID.ProcessorName = "i80486DX-25/33"; break;
  2488. case 1: this->ChipID.ProcessorName = "i80486DX-50"; break;
  2489. case 2: this->ChipID.ProcessorName = "i80486SX"; break;
  2490. case 3: this->ChipID.ProcessorName = "i80486DX2"; break;
  2491. case 4: this->ChipID.ProcessorName = "i80486SL"; break;
  2492. case 5: this->ChipID.ProcessorName = "i80486SX2"; break;
  2493. case 7: this->ChipID.ProcessorName = "i80486DX2 WriteBack"; break;
  2494. case 8: this->ChipID.ProcessorName = "i80486DX4"; break;
  2495. case 9: this->ChipID.ProcessorName = "i80486DX4 WriteBack"; break;
  2496. default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
  2497. }
  2498. break;
  2499. case 5:
  2500. switch (this->ChipID.Model)
  2501. {
  2502. case 0: this->ChipID.ProcessorName = "P5 A-Step"; break;
  2503. case 1: this->ChipID.ProcessorName = "P5"; break;
  2504. case 2: this->ChipID.ProcessorName = "P54C"; break;
  2505. case 3: this->ChipID.ProcessorName = "P24T OverDrive"; break;
  2506. case 4: this->ChipID.ProcessorName = "P55C"; break;
  2507. case 7: this->ChipID.ProcessorName = "P54C"; break;
  2508. case 8: this->ChipID.ProcessorName = "P55C (0.25micron)"; break;
  2509. default: this->ChipID.ProcessorName = "Unknown Pentium family"; return false;
  2510. }
  2511. break;
  2512. case 6:
  2513. switch (this->ChipID.Model)
  2514. {
  2515. case 0: this->ChipID.ProcessorName = "P6 A-Step"; break;
  2516. case 1: this->ChipID.ProcessorName = "P6"; break;
  2517. case 3: this->ChipID.ProcessorName = "Pentium II (0.28 micron)"; break;
  2518. case 5: this->ChipID.ProcessorName = "Pentium II (0.25 micron)"; break;
  2519. case 6: this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache"; break;
  2520. case 7: this->ChipID.ProcessorName = "Pentium III (0.25 micron)"; break;
  2521. case 8: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "; break;
  2522. case 0xa: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "; break;
  2523. case 0xb: this->ChipID.ProcessorName = "Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "; break;
  2524. case 23: this->ChipID.ProcessorName = "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz"; break;
  2525. default: this->ChipID.ProcessorName = "Unknown P6 family"; return false;
  2526. }
  2527. break;
  2528. case 7:
  2529. this->ChipID.ProcessorName = "Intel Merced (IA-64)";
  2530. break;
  2531. case 0xf:
  2532. // Check the extended family bits...
  2533. switch (this->ChipID.ExtendedFamily)
  2534. {
  2535. case 0:
  2536. switch (this->ChipID.Model)
  2537. {
  2538. case 0: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
  2539. case 1: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
  2540. case 2: this->ChipID.ProcessorName = "Pentium IV (0.13 micron)"; break;
  2541. default: this->ChipID.ProcessorName = "Unknown Pentium 4 family"; return false;
  2542. }
  2543. break;
  2544. case 1:
  2545. this->ChipID.ProcessorName = "Intel McKinley (IA-64)";
  2546. break;
  2547. default:
  2548. this->ChipID.ProcessorName = "Pentium";
  2549. }
  2550. break;
  2551. default:
  2552. this->ChipID.ProcessorName = "Unknown Intel family";
  2553. return false;
  2554. }
  2555. break;
  2556. case AMD:
  2557. // Check the family / model / revision to determine the CPU ID.
  2558. switch (this->ChipID.Family)
  2559. {
  2560. case 4:
  2561. switch (this->ChipID.Model)
  2562. {
  2563. case 3: this->ChipID.ProcessorName = "80486DX2"; break;
  2564. case 7: this->ChipID.ProcessorName = "80486DX2 WriteBack"; break;
  2565. case 8: this->ChipID.ProcessorName = "80486DX4"; break;
  2566. case 9: this->ChipID.ProcessorName = "80486DX4 WriteBack"; break;
  2567. case 0xe: this->ChipID.ProcessorName = "5x86"; break;
  2568. case 0xf: this->ChipID.ProcessorName = "5x86WB"; break;
  2569. default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
  2570. }
  2571. break;
  2572. case 5:
  2573. switch (this->ChipID.Model)
  2574. {
  2575. case 0: this->ChipID.ProcessorName = "SSA5 (PR75, PR90 = PR100)"; break;
  2576. case 1: this->ChipID.ProcessorName = "5k86 (PR120 = PR133)"; break;
  2577. case 2: this->ChipID.ProcessorName = "5k86 (PR166)"; break;
  2578. case 3: this->ChipID.ProcessorName = "5k86 (PR200)"; break;
  2579. case 6: this->ChipID.ProcessorName = "K6 (0.30 micron)"; break;
  2580. case 7: this->ChipID.ProcessorName = "K6 (0.25 micron)"; break;
  2581. case 8: this->ChipID.ProcessorName = "K6-2"; break;
  2582. case 9: this->ChipID.ProcessorName = "K6-III"; break;
  2583. case 0xd: this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)"; break;
  2584. default: this->ChipID.ProcessorName = "Unknown 80586 family"; return false;
  2585. }
  2586. break;
  2587. case 6:
  2588. switch (this->ChipID.Model)
  2589. {
  2590. case 1: this->ChipID.ProcessorName = "Athlon- (0.25 micron)"; break;
  2591. case 2: this->ChipID.ProcessorName = "Athlon- (0.18 micron)"; break;
  2592. case 3: this->ChipID.ProcessorName = "Duron- (SF core)"; break;
  2593. case 4: this->ChipID.ProcessorName = "Athlon- (Thunderbird core)"; break;
  2594. case 6: this->ChipID.ProcessorName = "Athlon- (Palomino core)"; break;
  2595. case 7: this->ChipID.ProcessorName = "Duron- (Morgan core)"; break;
  2596. case 8:
  2597. if (this->Features.ExtendedFeatures.SupportsMP)
  2598. this->ChipID.ProcessorName = "Athlon - MP (Thoroughbred core)";
  2599. else this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)";
  2600. break;
  2601. default: this->ChipID.ProcessorName = "Unknown K7 family"; return false;
  2602. }
  2603. break;
  2604. default:
  2605. this->ChipID.ProcessorName = "Unknown AMD family";
  2606. return false;
  2607. }
  2608. break;
  2609. case Transmeta:
  2610. switch (this->ChipID.Family)
  2611. {
  2612. case 5:
  2613. switch (this->ChipID.Model)
  2614. {
  2615. case 4: this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00"; break;
  2616. default: this->ChipID.ProcessorName = "Unknown Crusoe family"; return false;
  2617. }
  2618. break;
  2619. default:
  2620. this->ChipID.ProcessorName = "Unknown Transmeta family";
  2621. return false;
  2622. }
  2623. break;
  2624. case Rise:
  2625. switch (this->ChipID.Family)
  2626. {
  2627. case 5:
  2628. switch (this->ChipID.Model)
  2629. {
  2630. case 0: this->ChipID.ProcessorName = "mP6 (0.25 micron)"; break;
  2631. case 2: this->ChipID.ProcessorName = "mP6 (0.18 micron)"; break;
  2632. default: this->ChipID.ProcessorName = "Unknown Rise family"; return false;
  2633. }
  2634. break;
  2635. default:
  2636. this->ChipID.ProcessorName = "Unknown Rise family";
  2637. return false;
  2638. }
  2639. break;
  2640. case UMC:
  2641. switch (this->ChipID.Family)
  2642. {
  2643. case 4:
  2644. switch (this->ChipID.Model)
  2645. {
  2646. case 1: this->ChipID.ProcessorName = "U5D"; break;
  2647. case 2: this->ChipID.ProcessorName = "U5S"; break;
  2648. default: this->ChipID.ProcessorName = "Unknown UMC family"; return false;
  2649. }
  2650. break;
  2651. default:
  2652. this->ChipID.ProcessorName = "Unknown UMC family";
  2653. return false;
  2654. }
  2655. break;
  2656. case IDT:
  2657. switch (this->ChipID.Family)
  2658. {
  2659. case 5:
  2660. switch (this->ChipID.Model)
  2661. {
  2662. case 4: this->ChipID.ProcessorName = "C6"; break;
  2663. case 8: this->ChipID.ProcessorName = "C2"; break;
  2664. case 9: this->ChipID.ProcessorName = "C3"; break;
  2665. default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
  2666. }
  2667. break;
  2668. case 6:
  2669. switch (this->ChipID.Model)
  2670. {
  2671. case 6: this->ChipID.ProcessorName = "VIA Cyrix III - Samuel"; break;
  2672. default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
  2673. }
  2674. break;
  2675. default:
  2676. this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
  2677. return false;
  2678. }
  2679. break;
  2680. case Cyrix:
  2681. switch (this->ChipID.Family)
  2682. {
  2683. case 4:
  2684. switch (this->ChipID.Model)
  2685. {
  2686. case 4: this->ChipID.ProcessorName = "MediaGX GX = GXm"; break;
  2687. case 9: this->ChipID.ProcessorName = "5x86"; break;
  2688. default: this->ChipID.ProcessorName = "Unknown Cx5x86 family"; return false;
  2689. }
  2690. break;
  2691. case 5:
  2692. switch (this->ChipID.Model)
  2693. {
  2694. case 2: this->ChipID.ProcessorName = "Cx6x86"; break;
  2695. case 4: this->ChipID.ProcessorName = "MediaGX GXm"; break;
  2696. default: this->ChipID.ProcessorName = "Unknown Cx6x86 family"; return false;
  2697. }
  2698. break;
  2699. case 6:
  2700. switch (this->ChipID.Model)
  2701. {
  2702. case 0: this->ChipID.ProcessorName = "6x86MX"; break;
  2703. case 5: this->ChipID.ProcessorName = "Cyrix M2 Core"; break;
  2704. case 6: this->ChipID.ProcessorName = "WinChip C5A Core"; break;
  2705. case 7: this->ChipID.ProcessorName = "WinChip C5B\\C5C Core"; break;
  2706. case 8: this->ChipID.ProcessorName = "WinChip C5C-T Core"; break;
  2707. default: this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family"; return false;
  2708. }
  2709. break;
  2710. default:
  2711. this->ChipID.ProcessorName = "Unknown Cyrix family";
  2712. return false;
  2713. }
  2714. break;
  2715. case NexGen:
  2716. switch (this->ChipID.Family)
  2717. {
  2718. case 5:
  2719. switch (this->ChipID.Model)
  2720. {
  2721. case 0: this->ChipID.ProcessorName = "Nx586 or Nx586FPU"; break;
  2722. default: this->ChipID.ProcessorName = "Unknown NexGen family"; return false;
  2723. }
  2724. break;
  2725. default:
  2726. this->ChipID.ProcessorName = "Unknown NexGen family";
  2727. return false;
  2728. }
  2729. break;
  2730. case NSC:
  2731. this->ChipID.ProcessorName = "Cx486SLC \\ DLC \\ Cx486S A-Step";
  2732. break;
  2733. case Sun:
  2734. case IBM:
  2735. case Motorola:
  2736. case HP:
  2737. case UnknownManufacturer:
  2738. default:
  2739. this->ChipID.ProcessorName = "Unknown family"; // We cannot identify the processor.
  2740. return false;
  2741. }
  2742. return true;
  2743. }
  2744. /** Extract a value from the CPUInfo file */
  2745. std::string SystemInformationImplementation::ExtractValueFromCpuInfoFile(std::string buffer,const char* word,size_t init)
  2746. {
  2747. size_t pos = buffer.find(word,init);
  2748. if(pos != buffer.npos)
  2749. {
  2750. this->CurrentPositionInFile = pos;
  2751. pos = buffer.find(":",pos);
  2752. size_t pos2 = buffer.find("\n",pos);
  2753. if(pos!=buffer.npos && pos2!=buffer.npos)
  2754. {
  2755. // It may happen that the beginning matches, but this is still not the requested key.
  2756. // An example is looking for "cpu" when "cpu family" comes first. So we check that
  2757. // we have only spaces from here to pos, otherwise we search again.
  2758. for(size_t i=this->CurrentPositionInFile+strlen(word); i < pos; ++i)
  2759. {
  2760. if(buffer[i] != ' ' && buffer[i] != '\t')
  2761. {
  2762. return this->ExtractValueFromCpuInfoFile(buffer, word, pos2);
  2763. }
  2764. }
  2765. return buffer.substr(pos+2,pos2-pos-2);
  2766. }
  2767. }
  2768. this->CurrentPositionInFile = buffer.npos;
  2769. return "";
  2770. }
  2771. /** Query for the cpu status */
  2772. bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
  2773. {
  2774. this->NumberOfLogicalCPU = 0;
  2775. this->NumberOfPhysicalCPU = 0;
  2776. std::string buffer;
  2777. FILE *fd = fopen("/proc/cpuinfo", "r" );
  2778. if ( !fd )
  2779. {
  2780. std::cout << "Problem opening /proc/cpuinfo" << std::endl;
  2781. return false;
  2782. }
  2783. size_t fileSize = 0;
  2784. while(!feof(fd))
  2785. {
  2786. buffer += static_cast<char>(fgetc(fd));
  2787. fileSize++;
  2788. }
  2789. fclose( fd );
  2790. buffer.resize(fileSize-2);
  2791. // Number of logical CPUs (combination of multiple processors, multi-core
  2792. // and hyperthreading)
  2793. size_t pos = buffer.find("processor\t");
  2794. while(pos != buffer.npos)
  2795. {
  2796. this->NumberOfLogicalCPU++;
  2797. pos = buffer.find("processor\t",pos+1);
  2798. }
  2799. #ifdef __linux
  2800. // Find the largest physical id.
  2801. int maxId = -1;
  2802. std::string idc =
  2803. this->ExtractValueFromCpuInfoFile(buffer,"physical id");
  2804. while(this->CurrentPositionInFile != buffer.npos)
  2805. {
  2806. int id = atoi(idc.c_str());
  2807. if(id > maxId)
  2808. {
  2809. maxId=id;
  2810. }
  2811. idc = this->ExtractValueFromCpuInfoFile(buffer,"physical id",
  2812. this->CurrentPositionInFile+1);
  2813. }
  2814. // Physical ids returned by Linux don't distinguish cores.
  2815. // We want to record the total number of cores in this->NumberOfPhysicalCPU
  2816. // (checking only the first proc)
  2817. std::string cores =
  2818. this->ExtractValueFromCpuInfoFile(buffer,"cpu cores");
  2819. int numberOfCoresPerCPU=atoi(cores.c_str());
  2820. if (maxId > 0)
  2821. {
  2822. this->NumberOfPhysicalCPU=static_cast<unsigned int>(
  2823. numberOfCoresPerCPU*(maxId+1));
  2824. }
  2825. else
  2826. {
  2827. // Linux Sparc: get cpu count
  2828. this->NumberOfPhysicalCPU=
  2829. atoi(this->ExtractValueFromCpuInfoFile(buffer,"ncpus active").c_str());
  2830. }
  2831. #else // __CYGWIN__
  2832. // does not have "physical id" entries, neither "cpu cores"
  2833. // this has to be fixed for hyper-threading.
  2834. std::string cpucount =
  2835. this->ExtractValueFromCpuInfoFile(buffer,"cpu count");
  2836. this->NumberOfPhysicalCPU=
  2837. this->NumberOfLogicalCPU = atoi(cpucount.c_str());
  2838. #endif
  2839. // gotta have one, and if this is 0 then we get a / by 0n
  2840. // better to have a bad answer than a crash
  2841. if(this->NumberOfPhysicalCPU <= 0)
  2842. {
  2843. this->NumberOfPhysicalCPU = 1;
  2844. }
  2845. // LogicalProcessorsPerPhysical>1 => hyperthreading.
  2846. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical=
  2847. this->NumberOfLogicalCPU/this->NumberOfPhysicalCPU;
  2848. // CPU speed (checking only the first processor)
  2849. std::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"cpu MHz");
  2850. if(!CPUSpeed.empty())
  2851. {
  2852. this->CPUSpeedInMHz = static_cast<float>(atof(CPUSpeed.c_str()));
  2853. }
  2854. #ifdef __linux
  2855. else
  2856. {
  2857. // Linux Sparc: CPU speed is in Hz and encoded in hexadecimal
  2858. CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"Cpu0ClkTck");
  2859. this->CPUSpeedInMHz = static_cast<float>(
  2860. strtoull(CPUSpeed.c_str(),0,16))/1000000.0f;
  2861. }
  2862. #endif
  2863. // Chip family
  2864. std::string familyStr =
  2865. this->ExtractValueFromCpuInfoFile(buffer,"cpu family");
  2866. if(familyStr.empty())
  2867. {
  2868. familyStr = this->ExtractValueFromCpuInfoFile(buffer,"CPU architecture");
  2869. }
  2870. this->ChipID.Family = atoi(familyStr.c_str());
  2871. // Chip Vendor
  2872. this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer,"vendor_id");
  2873. this->FindManufacturer(familyStr);
  2874. // second try for setting family
  2875. if (this->ChipID.Family == 0 && this->ChipManufacturer == HP)
  2876. {
  2877. if (familyStr == "PA-RISC 1.1a")
  2878. this->ChipID.Family = 0x11a;
  2879. else if (familyStr == "PA-RISC 2.0")
  2880. this->ChipID.Family = 0x200;
  2881. // If you really get CMake to work on a machine not belonging to
  2882. // any of those families I owe you a dinner if you get it to
  2883. // contribute nightly builds regularly.
  2884. }
  2885. // Chip Model
  2886. this->ChipID.Model = atoi(this->ExtractValueFromCpuInfoFile(buffer,"model").c_str());
  2887. if(!this->RetrieveClassicalCPUIdentity())
  2888. {
  2889. // Some platforms (e.g. PA-RISC) tell us their CPU name here.
  2890. // Note: x86 does not.
  2891. std::string cpuname = this->ExtractValueFromCpuInfoFile(buffer,"cpu");
  2892. if(!cpuname.empty())
  2893. {
  2894. this->ChipID.ProcessorName = cpuname;
  2895. }
  2896. }
  2897. // Chip revision
  2898. std::string cpurev = this->ExtractValueFromCpuInfoFile(buffer,"stepping");
  2899. if(cpurev.empty())
  2900. {
  2901. cpurev = this->ExtractValueFromCpuInfoFile(buffer,"CPU revision");
  2902. }
  2903. this->ChipID.Revision = atoi(cpurev.c_str());
  2904. // Chip Model Name
  2905. this->ChipID.ModelName = this->ExtractValueFromCpuInfoFile(buffer,"model name").c_str();
  2906. // L1 Cache size
  2907. // Different architectures may show different names for the caches.
  2908. // Sum up everything we find.
  2909. std::vector<const char*> cachename;
  2910. cachename.clear();
  2911. cachename.push_back("cache size"); // e.g. x86
  2912. cachename.push_back("I-cache"); // e.g. PA-RISC
  2913. cachename.push_back("D-cache"); // e.g. PA-RISC
  2914. this->Features.L1CacheSize = 0;
  2915. for (size_t index = 0; index < cachename.size(); index ++)
  2916. {
  2917. std::string cacheSize = this->ExtractValueFromCpuInfoFile(buffer,cachename[index]);
  2918. if (!cacheSize.empty())
  2919. {
  2920. pos = cacheSize.find(" KB");
  2921. if(pos!=cacheSize.npos)
  2922. {
  2923. cacheSize = cacheSize.substr(0,pos);
  2924. }
  2925. this->Features.L1CacheSize += atoi(cacheSize.c_str());
  2926. }
  2927. }
  2928. // processor feature flags (probably x86 specific)
  2929. std::string cpuflags = this->ExtractValueFromCpuInfoFile(buffer,"flags");
  2930. if(!cpurev.empty())
  2931. {
  2932. // now we can match every flags as space + flag + space
  2933. cpuflags = " " + cpuflags + " ";
  2934. if ((cpuflags.find(" fpu ")!=std::string::npos))
  2935. {
  2936. this->Features.HasFPU = true;
  2937. }
  2938. if ((cpuflags.find(" tsc ")!=std::string::npos))
  2939. {
  2940. this->Features.HasTSC = true;
  2941. }
  2942. if ((cpuflags.find(" mmx ")!=std::string::npos))
  2943. {
  2944. this->Features.HasMMX = true;
  2945. }
  2946. if ((cpuflags.find(" sse ")!=std::string::npos))
  2947. {
  2948. this->Features.HasSSE = true;
  2949. }
  2950. if ((cpuflags.find(" sse2 ")!=std::string::npos))
  2951. {
  2952. this->Features.HasSSE2 = true;
  2953. }
  2954. if ((cpuflags.find(" apic ")!=std::string::npos))
  2955. {
  2956. this->Features.HasAPIC = true;
  2957. }
  2958. if ((cpuflags.find(" cmov ")!=std::string::npos))
  2959. {
  2960. this->Features.HasCMOV = true;
  2961. }
  2962. if ((cpuflags.find(" mtrr ")!=std::string::npos))
  2963. {
  2964. this->Features.HasMTRR = true;
  2965. }
  2966. if ((cpuflags.find(" acpi ")!=std::string::npos))
  2967. {
  2968. this->Features.HasACPI = true;
  2969. }
  2970. if ((cpuflags.find(" 3dnow ")!=std::string::npos))
  2971. {
  2972. this->Features.ExtendedFeatures.Has3DNow = true;
  2973. }
  2974. }
  2975. return true;
  2976. }
  2977. bool SystemInformationImplementation::QueryProcessorBySysconf()
  2978. {
  2979. #if defined(_SC_NPROC_ONLN) && !defined(_SC_NPROCESSORS_ONLN)
  2980. // IRIX names this slightly different
  2981. # define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
  2982. #endif
  2983. #ifdef _SC_NPROCESSORS_ONLN
  2984. long c = sysconf(_SC_NPROCESSORS_ONLN);
  2985. if (c <= 0)
  2986. {
  2987. return false;
  2988. }
  2989. this->NumberOfPhysicalCPU = static_cast<unsigned int>(c);
  2990. this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
  2991. return true;
  2992. #else
  2993. return false;
  2994. #endif
  2995. }
  2996. bool SystemInformationImplementation::QueryProcessor()
  2997. {
  2998. return this->QueryProcessorBySysconf();
  2999. }
  3000. /**
  3001. Get total system RAM in units of KiB.
  3002. */
  3003. SystemInformation::LongLong
  3004. SystemInformationImplementation::GetHostMemoryTotal()
  3005. {
  3006. #if defined(_WIN32)
  3007. # if defined(_MSC_VER) && _MSC_VER < 1300
  3008. MEMORYSTATUS stat;
  3009. stat.dwLength = sizeof(stat);
  3010. GlobalMemoryStatus(&stat);
  3011. return stat.dwTotalPhys/1024;
  3012. # else
  3013. MEMORYSTATUSEX statex;
  3014. statex.dwLength=sizeof(statex);
  3015. GlobalMemoryStatusEx(&statex);
  3016. return statex.ullTotalPhys/1024;
  3017. # endif
  3018. #elif defined(__linux)
  3019. SystemInformation::LongLong memTotal=0;
  3020. int ierr=GetFieldFromFile("/proc/meminfo","MemTotal:",memTotal);
  3021. if (ierr)
  3022. {
  3023. return -1;
  3024. }
  3025. return memTotal;
  3026. #elif defined(__APPLE__)
  3027. uint64_t mem;
  3028. size_t len = sizeof(mem);
  3029. int ierr=sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
  3030. if (ierr)
  3031. {
  3032. return -1;
  3033. }
  3034. return mem/1024;
  3035. #else
  3036. return 0;
  3037. #endif
  3038. }
  3039. /**
  3040. Get total system RAM in units of KiB. This may differ from the
  3041. host total if a host-wide resource limit is applied.
  3042. */
  3043. SystemInformation::LongLong
  3044. SystemInformationImplementation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
  3045. {
  3046. SystemInformation::LongLong memTotal=this->GetHostMemoryTotal();
  3047. // the following mechanism is provided for systems that
  3048. // apply resource limits across groups of processes.
  3049. // this is of use on certain SMP systems (eg. SGI UV)
  3050. // where the host has a large amount of ram but a given user's
  3051. // access to it is severly restricted. The system will
  3052. // apply a limit across a set of processes. Units are in KiB.
  3053. if (hostLimitEnvVarName)
  3054. {
  3055. const char *hostLimitEnvVarValue=getenv(hostLimitEnvVarName);
  3056. if (hostLimitEnvVarValue)
  3057. {
  3058. SystemInformation::LongLong hostLimit=atoLongLong(hostLimitEnvVarValue);
  3059. if (hostLimit>0)
  3060. {
  3061. memTotal=min(hostLimit,memTotal);
  3062. }
  3063. }
  3064. }
  3065. return memTotal;
  3066. }
  3067. /**
  3068. Get total system RAM in units of KiB. This may differ from the
  3069. host total if a per-process resource limit is applied.
  3070. */
  3071. SystemInformation::LongLong
  3072. SystemInformationImplementation::GetProcMemoryAvailable(
  3073. const char *hostLimitEnvVarName,
  3074. const char *procLimitEnvVarName)
  3075. {
  3076. SystemInformation::LongLong memAvail
  3077. = this->GetHostMemoryAvailable(hostLimitEnvVarName);
  3078. // the following mechanism is provide for systems where rlimits
  3079. // are not employed. Units are in KiB.
  3080. if (procLimitEnvVarName)
  3081. {
  3082. const char *procLimitEnvVarValue=getenv(procLimitEnvVarName);
  3083. if (procLimitEnvVarValue)
  3084. {
  3085. SystemInformation::LongLong procLimit=atoLongLong(procLimitEnvVarValue);
  3086. if (procLimit>0)
  3087. {
  3088. memAvail=min(procLimit,memAvail);
  3089. }
  3090. }
  3091. }
  3092. #if defined(__linux)
  3093. int ierr;
  3094. ResourceLimitType rlim;
  3095. ierr=GetResourceLimit(RLIMIT_DATA,&rlim);
  3096. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3097. {
  3098. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3099. }
  3100. ierr=GetResourceLimit(RLIMIT_AS,&rlim);
  3101. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3102. {
  3103. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3104. }
  3105. #elif defined(__APPLE__)
  3106. struct rlimit rlim;
  3107. int ierr;
  3108. ierr=getrlimit(RLIMIT_DATA,&rlim);
  3109. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3110. {
  3111. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3112. }
  3113. ierr=getrlimit(RLIMIT_RSS,&rlim);
  3114. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3115. {
  3116. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3117. }
  3118. #endif
  3119. return memAvail;
  3120. }
  3121. /**
  3122. Get RAM used by all processes in the host, in units of KiB.
  3123. */
  3124. SystemInformation::LongLong
  3125. SystemInformationImplementation::GetHostMemoryUsed()
  3126. {
  3127. #if defined(_WIN32)
  3128. # if defined(_MSC_VER) && _MSC_VER < 1300
  3129. MEMORYSTATUS stat;
  3130. stat.dwLength = sizeof(stat);
  3131. GlobalMemoryStatus(&stat);
  3132. return (stat.dwTotalPhys - stat.dwAvailPhys)/1024;
  3133. # else
  3134. MEMORYSTATUSEX statex;
  3135. statex.dwLength=sizeof(statex);
  3136. GlobalMemoryStatusEx(&statex);
  3137. return (statex.ullTotalPhys - statex.ullAvailPhys)/1024;
  3138. # endif
  3139. #elif defined(__linux)
  3140. // First try to use MemAvailable, but it only works on newer kernels
  3141. const char *names2[3]={"MemTotal:","MemAvailable:",NULL};
  3142. SystemInformation::LongLong values2[2]={SystemInformation::LongLong(0)};
  3143. int ierr=GetFieldsFromFile("/proc/meminfo",names2,values2);
  3144. if (ierr)
  3145. {
  3146. const char *names4[5]={"MemTotal:","MemFree:","Buffers:","Cached:",NULL};
  3147. SystemInformation::LongLong values4[4]={SystemInformation::LongLong(0)};
  3148. ierr=GetFieldsFromFile("/proc/meminfo",names4,values4);
  3149. if(ierr)
  3150. {
  3151. return ierr;
  3152. }
  3153. SystemInformation::LongLong &memTotal=values4[0];
  3154. SystemInformation::LongLong &memFree=values4[1];
  3155. SystemInformation::LongLong &memBuffers=values4[2];
  3156. SystemInformation::LongLong &memCached=values4[3];
  3157. return memTotal - memFree - memBuffers - memCached;
  3158. }
  3159. SystemInformation::LongLong &memTotal=values2[0];
  3160. SystemInformation::LongLong &memAvail=values2[1];
  3161. return memTotal - memAvail;
  3162. #elif defined(__APPLE__)
  3163. SystemInformation::LongLong psz=getpagesize();
  3164. if (psz<1)
  3165. {
  3166. return -1;
  3167. }
  3168. const char *names[3]={"Pages wired down:","Pages active:",NULL};
  3169. SystemInformation::LongLong values[2]={SystemInformation::LongLong(0)};
  3170. int ierr=GetFieldsFromCommand("vm_stat", names, values);
  3171. if (ierr)
  3172. {
  3173. return -1;
  3174. }
  3175. SystemInformation::LongLong &vmWired=values[0];
  3176. SystemInformation::LongLong &vmActive=values[1];
  3177. return ((vmActive+vmWired)*psz)/1024;
  3178. #else
  3179. return 0;
  3180. #endif
  3181. }
  3182. /**
  3183. Get system RAM used by the process associated with the given
  3184. process id in units of KiB.
  3185. */
  3186. SystemInformation::LongLong
  3187. SystemInformationImplementation::GetProcMemoryUsed()
  3188. {
  3189. #if defined(_WIN32) && defined(KWSYS_SYS_HAS_PSAPI)
  3190. long pid=GetCurrentProcessId();
  3191. HANDLE hProc;
  3192. hProc=OpenProcess(
  3193. PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
  3194. false,
  3195. pid);
  3196. if (hProc==0)
  3197. {
  3198. return -1;
  3199. }
  3200. PROCESS_MEMORY_COUNTERS pmc;
  3201. int ok=GetProcessMemoryInfo(hProc,&pmc,sizeof(pmc));
  3202. CloseHandle(hProc);
  3203. if (!ok)
  3204. {
  3205. return -2;
  3206. }
  3207. return pmc.WorkingSetSize/1024;
  3208. #elif defined(__linux)
  3209. SystemInformation::LongLong memUsed=0;
  3210. int ierr=GetFieldFromFile("/proc/self/status","VmRSS:",memUsed);
  3211. if (ierr)
  3212. {
  3213. return -1;
  3214. }
  3215. return memUsed;
  3216. #elif defined(__APPLE__)
  3217. SystemInformation::LongLong memUsed=0;
  3218. pid_t pid=getpid();
  3219. std::ostringstream oss;
  3220. oss << "ps -o rss= -p " << pid;
  3221. FILE *file=popen(oss.str().c_str(),"r");
  3222. if (file==0)
  3223. {
  3224. return -1;
  3225. }
  3226. oss.str("");
  3227. while (!feof(file) && !ferror(file))
  3228. {
  3229. char buf[256]={'\0'};
  3230. errno=0;
  3231. size_t nRead=fread(buf,1,256,file);
  3232. if (ferror(file) && (errno==EINTR))
  3233. {
  3234. clearerr(file);
  3235. }
  3236. if (nRead) oss << buf;
  3237. }
  3238. int ierr=ferror(file);
  3239. pclose(file);
  3240. if (ierr)
  3241. {
  3242. return -2;
  3243. }
  3244. std::istringstream iss(oss.str());
  3245. iss >> memUsed;
  3246. return memUsed;
  3247. #else
  3248. return 0;
  3249. #endif
  3250. }
  3251. double SystemInformationImplementation::GetLoadAverage()
  3252. {
  3253. #if defined(KWSYS_CXX_HAS_GETLOADAVG)
  3254. double loadavg[3] = { 0.0, 0.0, 0.0 };
  3255. if (getloadavg(loadavg, 3) > 0)
  3256. {
  3257. return loadavg[0];
  3258. }
  3259. return -0.0;
  3260. #elif defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
  3261. // Old windows.h headers do not provide GetSystemTimes.
  3262. typedef BOOL (WINAPI *GetSystemTimesType)(LPFILETIME, LPFILETIME,
  3263. LPFILETIME);
  3264. static GetSystemTimesType pGetSystemTimes =
  3265. (GetSystemTimesType)GetProcAddress(GetModuleHandleW(L"kernel32"),
  3266. "GetSystemTimes");
  3267. FILETIME idleTime, kernelTime, userTime;
  3268. if (pGetSystemTimes && pGetSystemTimes(&idleTime, &kernelTime, &userTime))
  3269. {
  3270. unsigned __int64 const idleTicks =
  3271. fileTimeToUInt64(idleTime);
  3272. unsigned __int64 const totalTicks =
  3273. fileTimeToUInt64(kernelTime) + fileTimeToUInt64(userTime);
  3274. return calculateCPULoad(idleTicks, totalTicks) * GetNumberOfPhysicalCPU();
  3275. }
  3276. return -0.0;
  3277. #else
  3278. // Not implemented on this platform.
  3279. return -0.0;
  3280. #endif
  3281. }
  3282. /**
  3283. Get the process id of the running process.
  3284. */
  3285. SystemInformation::LongLong
  3286. SystemInformationImplementation::GetProcessId()
  3287. {
  3288. #if defined(_WIN32)
  3289. return GetCurrentProcessId();
  3290. #elif defined(__linux) || defined(__APPLE__)
  3291. return getpid();
  3292. #else
  3293. return -1;
  3294. #endif
  3295. }
  3296. /**
  3297. return current program stack in a string
  3298. demangle cxx symbols if possible.
  3299. */
  3300. std::string SystemInformationImplementation::GetProgramStack(
  3301. int firstFrame,
  3302. int wholePath)
  3303. {
  3304. std::string programStack = ""
  3305. #if !defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  3306. "WARNING: The stack could not be examined "
  3307. "because backtrace is not supported.\n"
  3308. #elif !defined(KWSYS_SYSTEMINFORMATION_HAS_DEBUG_BUILD)
  3309. "WARNING: The stack trace will not use advanced "
  3310. "capabilities because this is a release build.\n"
  3311. #else
  3312. # if !defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  3313. "WARNING: Function names will not be demangled because "
  3314. "dladdr is not available.\n"
  3315. # endif
  3316. # if !defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
  3317. "WARNING: Function names will not be demangled "
  3318. "because cxxabi is not available.\n"
  3319. # endif
  3320. #endif
  3321. ;
  3322. std::ostringstream oss;
  3323. #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  3324. void *stackSymbols[256];
  3325. int nFrames=backtrace(stackSymbols,256);
  3326. for (int i=firstFrame; i<nFrames; ++i)
  3327. {
  3328. SymbolProperties symProps;
  3329. symProps.SetReportPath(wholePath);
  3330. symProps.Initialize(stackSymbols[i]);
  3331. oss << symProps << std::endl;
  3332. }
  3333. #else
  3334. (void)firstFrame;
  3335. (void)wholePath;
  3336. #endif
  3337. programStack += oss.str();
  3338. return programStack;
  3339. }
  3340. /**
  3341. when set print stack trace in response to common signals.
  3342. */
  3343. void SystemInformationImplementation::SetStackTraceOnError(int enable)
  3344. {
  3345. #if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
  3346. static int saOrigValid=0;
  3347. static struct sigaction saABRTOrig;
  3348. static struct sigaction saSEGVOrig;
  3349. static struct sigaction saTERMOrig;
  3350. static struct sigaction saINTOrig;
  3351. static struct sigaction saILLOrig;
  3352. static struct sigaction saBUSOrig;
  3353. static struct sigaction saFPEOrig;
  3354. if (enable && !saOrigValid)
  3355. {
  3356. // save the current actions
  3357. sigaction(SIGABRT,0,&saABRTOrig);
  3358. sigaction(SIGSEGV,0,&saSEGVOrig);
  3359. sigaction(SIGTERM,0,&saTERMOrig);
  3360. sigaction(SIGINT,0,&saINTOrig);
  3361. sigaction(SIGILL,0,&saILLOrig);
  3362. sigaction(SIGBUS,0,&saBUSOrig);
  3363. sigaction(SIGFPE,0,&saFPEOrig);
  3364. // enable read, disable write
  3365. saOrigValid=1;
  3366. // install ours
  3367. struct sigaction sa;
  3368. sa.sa_sigaction=(SigAction)StacktraceSignalHandler;
  3369. sa.sa_flags=SA_SIGINFO|SA_RESETHAND;
  3370. # ifdef SA_RESTART
  3371. sa.sa_flags|=SA_RESTART;
  3372. # endif
  3373. sigemptyset(&sa.sa_mask);
  3374. sigaction(SIGABRT,&sa,0);
  3375. sigaction(SIGSEGV,&sa,0);
  3376. sigaction(SIGTERM,&sa,0);
  3377. sigaction(SIGINT,&sa,0);
  3378. sigaction(SIGILL,&sa,0);
  3379. sigaction(SIGBUS,&sa,0);
  3380. sigaction(SIGFPE,&sa,0);
  3381. }
  3382. else
  3383. if (!enable && saOrigValid)
  3384. {
  3385. // restore previous actions
  3386. sigaction(SIGABRT,&saABRTOrig,0);
  3387. sigaction(SIGSEGV,&saSEGVOrig,0);
  3388. sigaction(SIGTERM,&saTERMOrig,0);
  3389. sigaction(SIGINT,&saINTOrig,0);
  3390. sigaction(SIGILL,&saILLOrig,0);
  3391. sigaction(SIGBUS,&saBUSOrig,0);
  3392. sigaction(SIGFPE,&saFPEOrig,0);
  3393. // enable write, disable read
  3394. saOrigValid=0;
  3395. }
  3396. #else
  3397. // avoid warning C4100
  3398. (void)enable;
  3399. #endif
  3400. }
  3401. bool SystemInformationImplementation::QueryWindowsMemory()
  3402. {
  3403. #if defined(_WIN32)
  3404. # if defined(_MSC_VER) && _MSC_VER < 1300
  3405. MEMORYSTATUS ms;
  3406. unsigned long tv, tp, av, ap;
  3407. ms.dwLength = sizeof(ms);
  3408. GlobalMemoryStatus(&ms);
  3409. # define MEM_VAL(value) dw##value
  3410. # else
  3411. MEMORYSTATUSEX ms;
  3412. DWORDLONG tv, tp, av, ap;
  3413. ms.dwLength = sizeof(ms);
  3414. if (0 == GlobalMemoryStatusEx(&ms))
  3415. {
  3416. return 0;
  3417. }
  3418. # define MEM_VAL(value) ull##value
  3419. # endif
  3420. tv = ms.MEM_VAL(TotalPageFile);
  3421. tp = ms.MEM_VAL(TotalPhys);
  3422. av = ms.MEM_VAL(AvailPageFile);
  3423. ap = ms.MEM_VAL(AvailPhys);
  3424. this->TotalVirtualMemory = tv>>10>>10;
  3425. this->TotalPhysicalMemory = tp>>10>>10;
  3426. this->AvailableVirtualMemory = av>>10>>10;
  3427. this->AvailablePhysicalMemory = ap>>10>>10;
  3428. return true;
  3429. #else
  3430. return false;
  3431. #endif
  3432. }
  3433. bool SystemInformationImplementation::QueryLinuxMemory()
  3434. {
  3435. #if defined(__linux)
  3436. unsigned long tv=0;
  3437. unsigned long tp=0;
  3438. unsigned long av=0;
  3439. unsigned long ap=0;
  3440. char buffer[1024]; // for reading lines
  3441. int linuxMajor = 0;
  3442. int linuxMinor = 0;
  3443. // Find the Linux kernel version first
  3444. struct utsname unameInfo;
  3445. int errorFlag = uname(&unameInfo);
  3446. if( errorFlag!=0 )
  3447. {
  3448. std::cout << "Problem calling uname(): " << strerror(errno) << std::endl;
  3449. return false;
  3450. }
  3451. if( strlen(unameInfo.release)>=3 )
  3452. {
  3453. // release looks like "2.6.3-15mdk-i686-up-4GB"
  3454. char majorChar=unameInfo.release[0];
  3455. char minorChar=unameInfo.release[2];
  3456. if( isdigit(majorChar) )
  3457. {
  3458. linuxMajor=majorChar-'0';
  3459. }
  3460. if( isdigit(minorChar) )
  3461. {
  3462. linuxMinor=minorChar-'0';
  3463. }
  3464. }
  3465. FILE *fd = fopen("/proc/meminfo", "r" );
  3466. if ( !fd )
  3467. {
  3468. std::cout << "Problem opening /proc/meminfo" << std::endl;
  3469. return false;
  3470. }
  3471. if( linuxMajor>=3 || ( (linuxMajor>=2) && (linuxMinor>=6) ) )
  3472. {
  3473. // new /proc/meminfo format since kernel 2.6.x
  3474. // Rigorously, this test should check from the developping version 2.5.x
  3475. // that introduced the new format...
  3476. enum { mMemTotal, mMemFree, mBuffers, mCached, mSwapTotal, mSwapFree };
  3477. const char* format[6] =
  3478. { "MemTotal:%lu kB", "MemFree:%lu kB", "Buffers:%lu kB",
  3479. "Cached:%lu kB", "SwapTotal:%lu kB", "SwapFree:%lu kB" };
  3480. bool have[6] = { false, false, false, false, false, false };
  3481. unsigned long value[6];
  3482. int count = 0;
  3483. while(fgets(buffer, static_cast<int>(sizeof(buffer)), fd))
  3484. {
  3485. for(int i=0; i < 6; ++i)
  3486. {
  3487. if(!have[i] && sscanf(buffer, format[i], &value[i]) == 1)
  3488. {
  3489. have[i] = true;
  3490. ++count;
  3491. }
  3492. }
  3493. }
  3494. if(count == 6)
  3495. {
  3496. this->TotalPhysicalMemory = value[mMemTotal] / 1024;
  3497. this->AvailablePhysicalMemory =
  3498. (value[mMemFree] + value[mBuffers] + value[mCached]) / 1024;
  3499. this->TotalVirtualMemory = value[mSwapTotal] / 1024;
  3500. this->AvailableVirtualMemory = value[mSwapFree] / 1024;
  3501. }
  3502. else
  3503. {
  3504. std::cout << "Problem parsing /proc/meminfo" << std::endl;
  3505. fclose(fd);
  3506. return false;
  3507. }
  3508. }
  3509. else
  3510. {
  3511. // /proc/meminfo format for kernel older than 2.6.x
  3512. unsigned long temp;
  3513. unsigned long cachedMem;
  3514. unsigned long buffersMem;
  3515. // Skip "total: used:..."
  3516. char *r=fgets(buffer, static_cast<int>(sizeof(buffer)), fd);
  3517. int status=0;
  3518. if(r==buffer)
  3519. {
  3520. status+=fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n",
  3521. &tp, &temp, &ap, &temp, &buffersMem, &cachedMem);
  3522. }
  3523. if(status==6)
  3524. {
  3525. status+=fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av);
  3526. }
  3527. if(status==9)
  3528. {
  3529. this->TotalVirtualMemory = tv>>10>>10;
  3530. this->TotalPhysicalMemory = tp>>10>>10;
  3531. this->AvailableVirtualMemory = av>>10>>10;
  3532. this->AvailablePhysicalMemory = (ap+buffersMem+cachedMem)>>10>>10;
  3533. }
  3534. else
  3535. {
  3536. std::cout << "Problem parsing /proc/meminfo" << std::endl;
  3537. fclose(fd);
  3538. return false;
  3539. }
  3540. }
  3541. fclose( fd );
  3542. return true;
  3543. #else
  3544. return false;
  3545. #endif
  3546. }
  3547. bool SystemInformationImplementation::QueryCygwinMemory()
  3548. {
  3549. #ifdef __CYGWIN__
  3550. // _SC_PAGE_SIZE does return the mmap() granularity on Cygwin,
  3551. // see http://cygwin.com/ml/cygwin/2006-06/msg00350.html
  3552. // Therefore just use 4096 as the page size of Windows.
  3553. long m = sysconf(_SC_PHYS_PAGES);
  3554. if (m < 0)
  3555. {
  3556. return false;
  3557. }
  3558. this->TotalPhysicalMemory = m >> 8;
  3559. return true;
  3560. #else
  3561. return false;
  3562. #endif
  3563. }
  3564. bool SystemInformationImplementation::QueryAIXMemory()
  3565. {
  3566. #if defined(_AIX) && defined(_SC_AIX_REALMEM)
  3567. long c = sysconf(_SC_AIX_REALMEM);
  3568. if (c <= 0)
  3569. {
  3570. return false;
  3571. }
  3572. this->TotalPhysicalMemory = c / 1024;
  3573. return true;
  3574. #else
  3575. return false;
  3576. #endif
  3577. }
  3578. bool SystemInformationImplementation::QueryMemoryBySysconf()
  3579. {
  3580. #if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
  3581. // Assume the mmap() granularity as returned by _SC_PAGESIZE is also
  3582. // the system page size. The only known system where this isn't true
  3583. // is Cygwin.
  3584. long p = sysconf(_SC_PHYS_PAGES);
  3585. long m = sysconf(_SC_PAGESIZE);
  3586. if (p < 0 || m < 0)
  3587. {
  3588. return false;
  3589. }
  3590. // assume pagesize is a power of 2 and smaller 1 MiB
  3591. size_t pagediv = (1024 * 1024 / m);
  3592. this->TotalPhysicalMemory = p;
  3593. this->TotalPhysicalMemory /= pagediv;
  3594. #if defined(_SC_AVPHYS_PAGES)
  3595. p = sysconf(_SC_AVPHYS_PAGES);
  3596. if (p < 0)
  3597. {
  3598. return false;
  3599. }
  3600. this->AvailablePhysicalMemory = p;
  3601. this->AvailablePhysicalMemory /= pagediv;
  3602. #endif
  3603. return true;
  3604. #else
  3605. return false;
  3606. #endif
  3607. }
  3608. /** Query for the memory status */
  3609. bool SystemInformationImplementation::QueryMemory()
  3610. {
  3611. return this->QueryMemoryBySysconf();
  3612. }
  3613. /** */
  3614. size_t SystemInformationImplementation::GetTotalVirtualMemory()
  3615. {
  3616. return this->TotalVirtualMemory;
  3617. }
  3618. /** */
  3619. size_t SystemInformationImplementation::GetAvailableVirtualMemory()
  3620. {
  3621. return this->AvailableVirtualMemory;
  3622. }
  3623. size_t SystemInformationImplementation::GetTotalPhysicalMemory()
  3624. {
  3625. return this->TotalPhysicalMemory;
  3626. }
  3627. /** */
  3628. size_t SystemInformationImplementation::GetAvailablePhysicalMemory()
  3629. {
  3630. return this->AvailablePhysicalMemory;
  3631. }
  3632. /** Get Cycle differences */
  3633. SystemInformation::LongLong
  3634. SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
  3635. unsigned int uiParameter)
  3636. {
  3637. #if defined(_MSC_VER) && (_MSC_VER >= 1400)
  3638. unsigned __int64 stamp1, stamp2;
  3639. stamp1 = __rdtsc();
  3640. DelayFunction(uiParameter);
  3641. stamp2 = __rdtsc();
  3642. return stamp2 - stamp1;
  3643. #elif USE_ASM_INSTRUCTIONS
  3644. unsigned int edx1, eax1;
  3645. unsigned int edx2, eax2;
  3646. // Calculate the frequency of the CPU instructions.
  3647. __try {
  3648. _asm {
  3649. push uiParameter ; push parameter param
  3650. mov ebx, DelayFunction ; store func in ebx
  3651. RDTSC_INSTRUCTION
  3652. mov esi, eax ; esi = eax
  3653. mov edi, edx ; edi = edx
  3654. call ebx ; call the delay functions
  3655. RDTSC_INSTRUCTION
  3656. pop ebx
  3657. mov edx2, edx ; edx2 = edx
  3658. mov eax2, eax ; eax2 = eax
  3659. mov edx1, edi ; edx2 = edi
  3660. mov eax1, esi ; eax2 = esi
  3661. }
  3662. }
  3663. __except(1)
  3664. {
  3665. return -1;
  3666. }
  3667. return ((((__int64) edx2 << 32) + eax2) - (((__int64) edx1 << 32) + eax1));
  3668. #else
  3669. (void)DelayFunction;
  3670. (void)uiParameter;
  3671. return -1;
  3672. #endif
  3673. }
  3674. /** Compute the delay overhead */
  3675. void SystemInformationImplementation::DelayOverhead(unsigned int uiMS)
  3676. {
  3677. #if defined(_WIN32)
  3678. LARGE_INTEGER Frequency, StartCounter, EndCounter;
  3679. __int64 x;
  3680. // Get the frequency of the high performance counter.
  3681. if(!QueryPerformanceFrequency (&Frequency))
  3682. {
  3683. return;
  3684. }
  3685. x = Frequency.QuadPart / 1000 * uiMS;
  3686. // Get the starting position of the counter.
  3687. QueryPerformanceCounter (&StartCounter);
  3688. do {
  3689. // Get the ending position of the counter.
  3690. QueryPerformanceCounter (&EndCounter);
  3691. } while (EndCounter.QuadPart - StartCounter.QuadPart == x);
  3692. #endif
  3693. (void)uiMS;
  3694. }
  3695. /** Return the number of logical CPU per physical CPUs Works only for windows */
  3696. unsigned char SystemInformationImplementation::LogicalCPUPerPhysicalCPU(void)
  3697. {
  3698. #ifdef __APPLE__
  3699. size_t len = 4;
  3700. int cores_per_package = 0;
  3701. int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &len, NULL, 0);
  3702. if (err != 0)
  3703. {
  3704. return 1; // That name was not found, default to 1
  3705. }
  3706. return static_cast<unsigned char>(cores_per_package);
  3707. #else
  3708. int Regs[4] = { 0, 0, 0, 0 };
  3709. #if USE_CPUID
  3710. if (!this->IsHyperThreadingSupported())
  3711. {
  3712. return static_cast<unsigned char>(1); // HT not supported
  3713. }
  3714. call_cpuid(1, Regs);
  3715. #endif
  3716. return static_cast<unsigned char> ((Regs[1] & NUM_LOGICAL_BITS) >> 16);
  3717. #endif
  3718. }
  3719. /** Works only for windows */
  3720. bool SystemInformationImplementation::IsHyperThreadingSupported()
  3721. {
  3722. if (this->Features.ExtendedFeatures.SupportsHyperthreading)
  3723. {
  3724. return true;
  3725. }
  3726. #if USE_CPUID
  3727. int Regs[4] = { 0, 0, 0, 0 },
  3728. VendorId[4] = { 0, 0, 0, 0 };
  3729. // Get vendor id string
  3730. if (!call_cpuid(0, VendorId))
  3731. {
  3732. return false;
  3733. }
  3734. // eax contains family processor type
  3735. // edx has info about the availability of hyper-Threading
  3736. if (!call_cpuid(1, Regs))
  3737. {
  3738. return false;
  3739. }
  3740. if (((Regs[0] & FAMILY_ID) == PENTIUM4_ID) || (Regs[0] & EXT_FAMILY_ID))
  3741. {
  3742. if (VendorId[1] == 0x756e6547) // 'uneG'
  3743. {
  3744. if (VendorId[3] == 0x49656e69) // 'Ieni'
  3745. {
  3746. if (VendorId[2] == 0x6c65746e) // 'letn'
  3747. {
  3748. // Genuine Intel with hyper-Threading technology
  3749. this->Features.ExtendedFeatures.SupportsHyperthreading = ((Regs[3] & HT_BIT) != 0);
  3750. return this->Features.ExtendedFeatures.SupportsHyperthreading;
  3751. }
  3752. }
  3753. }
  3754. }
  3755. #endif
  3756. return 0; // Not genuine Intel processor
  3757. }
  3758. /** Return the APIC Id. Works only for windows. */
  3759. unsigned char SystemInformationImplementation::GetAPICId()
  3760. {
  3761. int Regs[4] = { 0, 0, 0, 0 };
  3762. #if USE_CPUID
  3763. if (!this->IsHyperThreadingSupported())
  3764. {
  3765. return static_cast<unsigned char>(-1); // HT not supported
  3766. } // Logical processor = 1
  3767. call_cpuid(1, Regs);
  3768. #endif
  3769. return static_cast<unsigned char>((Regs[1] & INITIAL_APIC_ID_BITS) >> 24);
  3770. }
  3771. /** Count the number of CPUs. Works only on windows. */
  3772. int SystemInformationImplementation::CPUCount()
  3773. {
  3774. #if defined(_WIN32)
  3775. unsigned char StatusFlag = 0;
  3776. SYSTEM_INFO info;
  3777. this->NumberOfPhysicalCPU = 0;
  3778. this->NumberOfLogicalCPU = 0;
  3779. info.dwNumberOfProcessors = 0;
  3780. GetSystemInfo (&info);
  3781. // Number of physical processors in a non-Intel system
  3782. // or in a 32-bit Intel system with Hyper-Threading technology disabled
  3783. this->NumberOfPhysicalCPU = (unsigned char) info.dwNumberOfProcessors;
  3784. if (this->IsHyperThreadingSupported())
  3785. {
  3786. unsigned char HT_Enabled = 0;
  3787. this->NumberOfLogicalCPU = this->LogicalCPUPerPhysicalCPU();
  3788. if (this->NumberOfLogicalCPU >= 1) // >1 Doesn't mean HT is enabled in the BIOS
  3789. {
  3790. HANDLE hCurrentProcessHandle;
  3791. #ifndef _WIN64
  3792. # define DWORD_PTR DWORD
  3793. #endif
  3794. DWORD_PTR dwProcessAffinity;
  3795. DWORD_PTR dwSystemAffinity;
  3796. DWORD dwAffinityMask;
  3797. // Calculate the appropriate shifts and mask based on the
  3798. // number of logical processors.
  3799. unsigned int i = 1;
  3800. unsigned char PHY_ID_MASK = 0xFF;
  3801. //unsigned char PHY_ID_SHIFT = 0;
  3802. while (i < this->NumberOfLogicalCPU)
  3803. {
  3804. i *= 2;
  3805. PHY_ID_MASK <<= 1;
  3806. // PHY_ID_SHIFT++;
  3807. }
  3808. hCurrentProcessHandle = GetCurrentProcess();
  3809. GetProcessAffinityMask(hCurrentProcessHandle, &dwProcessAffinity,
  3810. &dwSystemAffinity);
  3811. // Check if available process affinity mask is equal to the
  3812. // available system affinity mask
  3813. if (dwProcessAffinity != dwSystemAffinity)
  3814. {
  3815. StatusFlag = HT_CANNOT_DETECT;
  3816. this->NumberOfPhysicalCPU = (unsigned char)-1;
  3817. return StatusFlag;
  3818. }
  3819. dwAffinityMask = 1;
  3820. while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity)
  3821. {
  3822. // Check if this CPU is available
  3823. if (dwAffinityMask & dwProcessAffinity)
  3824. {
  3825. if (SetProcessAffinityMask(hCurrentProcessHandle,
  3826. dwAffinityMask))
  3827. {
  3828. unsigned char APIC_ID, LOG_ID;
  3829. Sleep(0); // Give OS time to switch CPU
  3830. APIC_ID = GetAPICId();
  3831. LOG_ID = APIC_ID & ~PHY_ID_MASK;
  3832. if (LOG_ID != 0)
  3833. {
  3834. HT_Enabled = 1;
  3835. }
  3836. }
  3837. }
  3838. dwAffinityMask = dwAffinityMask << 1;
  3839. }
  3840. // Reset the processor affinity
  3841. SetProcessAffinityMask(hCurrentProcessHandle, dwProcessAffinity);
  3842. if (this->NumberOfLogicalCPU == 1) // Normal P4 : HT is disabled in hardware
  3843. {
  3844. StatusFlag = HT_DISABLED;
  3845. }
  3846. else
  3847. {
  3848. if (HT_Enabled)
  3849. {
  3850. // Total physical processors in a Hyper-Threading enabled system.
  3851. this->NumberOfPhysicalCPU /= (this->NumberOfLogicalCPU);
  3852. StatusFlag = HT_ENABLED;
  3853. }
  3854. else
  3855. {
  3856. StatusFlag = HT_SUPPORTED_NOT_ENABLED;
  3857. }
  3858. }
  3859. }
  3860. }
  3861. else
  3862. {
  3863. // Processors do not have Hyper-Threading technology
  3864. StatusFlag = HT_NOT_CAPABLE;
  3865. this->NumberOfLogicalCPU = 1;
  3866. }
  3867. return StatusFlag;
  3868. #else
  3869. return 0;
  3870. #endif
  3871. }
  3872. /** Return the number of logical CPUs on the system */
  3873. unsigned int SystemInformationImplementation::GetNumberOfLogicalCPU()
  3874. {
  3875. return this->NumberOfLogicalCPU;
  3876. }
  3877. /** Return the number of physical CPUs on the system */
  3878. unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU()
  3879. {
  3880. return this->NumberOfPhysicalCPU;
  3881. }
  3882. /** For Mac use sysctlbyname calls to find system info */
  3883. bool SystemInformationImplementation::ParseSysCtl()
  3884. {
  3885. #if defined(__APPLE__)
  3886. char retBuf[128];
  3887. int err = 0;
  3888. uint64_t value = 0;
  3889. size_t len = sizeof(value);
  3890. sysctlbyname("hw.memsize", &value, &len, NULL, 0);
  3891. this->TotalPhysicalMemory = static_cast< size_t >( value/1048576 );
  3892. // Parse values for Mac
  3893. this->AvailablePhysicalMemory = 0;
  3894. vm_statistics_data_t vmstat;
  3895. mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
  3896. if ( host_statistics(mach_host_self(), HOST_VM_INFO,
  3897. (host_info_t) &vmstat, &count) == KERN_SUCCESS )
  3898. {
  3899. len = sizeof(value);
  3900. err = sysctlbyname("hw.pagesize", &value, &len, NULL, 0);
  3901. int64_t available_memory = vmstat.free_count * value;
  3902. this->AvailablePhysicalMemory = static_cast< size_t >( available_memory / 1048576 );
  3903. }
  3904. #ifdef VM_SWAPUSAGE
  3905. // Virtual memory.
  3906. int mib[2] = { CTL_VM, VM_SWAPUSAGE };
  3907. size_t miblen = sizeof(mib) / sizeof(mib[0]);
  3908. struct xsw_usage swap;
  3909. len = sizeof(swap);
  3910. err = sysctl(mib, miblen, &swap, &len, NULL, 0);
  3911. if (err == 0)
  3912. {
  3913. this->AvailableVirtualMemory = static_cast< size_t >( swap.xsu_avail/1048576 );
  3914. this->TotalVirtualMemory = static_cast< size_t >( swap.xsu_total/1048576 );
  3915. }
  3916. #else
  3917. this->AvailableVirtualMemory = 0;
  3918. this->TotalVirtualMemory = 0;
  3919. #endif
  3920. // CPU Info
  3921. len = sizeof(this->NumberOfPhysicalCPU);
  3922. sysctlbyname("hw.physicalcpu", &this->NumberOfPhysicalCPU, &len, NULL, 0);
  3923. len = sizeof(this->NumberOfLogicalCPU);
  3924. sysctlbyname("hw.logicalcpu", &this->NumberOfLogicalCPU, &len, NULL, 0);
  3925. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
  3926. this->LogicalCPUPerPhysicalCPU();
  3927. len = sizeof(value);
  3928. sysctlbyname("hw.cpufrequency", &value, &len, NULL, 0);
  3929. this->CPUSpeedInMHz = static_cast< float >( value )/ 1000000;
  3930. // Chip family
  3931. len = sizeof(this->ChipID.Family);
  3932. //Seems only the intel chips will have this name so if this fails it is
  3933. //probably a PPC machine
  3934. err = sysctlbyname("machdep.cpu.family",
  3935. &this->ChipID.Family, &len, NULL, 0);
  3936. if (err != 0) // Go back to names we know but are less descriptive
  3937. {
  3938. this->ChipID.Family = 0;
  3939. ::memset(retBuf, 0, 128);
  3940. len = 32;
  3941. err = sysctlbyname("hw.machine", &retBuf, &len, NULL, 0);
  3942. std::string machineBuf(retBuf);
  3943. if (machineBuf.find_first_of("Power") != std::string::npos)
  3944. {
  3945. this->ChipID.Vendor = "IBM";
  3946. len = sizeof(this->ChipID.Family);
  3947. err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, NULL, 0);
  3948. len = sizeof(this->ChipID.Model);
  3949. err = sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, NULL, 0);
  3950. this->FindManufacturer();
  3951. }
  3952. }
  3953. else // Should be an Intel Chip.
  3954. {
  3955. len = sizeof(this->ChipID.Family);
  3956. err =
  3957. sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0);
  3958. ::memset(retBuf, 0, 128);
  3959. len = 128;
  3960. err = sysctlbyname("machdep.cpu.vendor", retBuf, &len, NULL, 0);
  3961. // Chip Vendor
  3962. this->ChipID.Vendor = retBuf;
  3963. this->FindManufacturer();
  3964. // Chip Model
  3965. len = sizeof(value);
  3966. err = sysctlbyname("machdep.cpu.model", &value, &len, NULL, 0);
  3967. this->ChipID.Model = static_cast< int >( value );
  3968. // Chip Stepping
  3969. len = sizeof(value);
  3970. value = 0;
  3971. err = sysctlbyname("machdep.cpu.stepping", &value, &len, NULL, 0);
  3972. if (!err)
  3973. {
  3974. this->ChipID.Revision = static_cast< int >( value );
  3975. }
  3976. // feature string
  3977. char *buf = 0;
  3978. size_t allocSize = 128;
  3979. err = 0;
  3980. len = 0;
  3981. // sysctlbyname() will return with err==0 && len==0 if the buffer is too small
  3982. while (err == 0 && len == 0)
  3983. {
  3984. delete[] buf;
  3985. allocSize *= 2;
  3986. buf = new char[allocSize];
  3987. if (!buf)
  3988. {
  3989. break;
  3990. }
  3991. buf[0] = ' ';
  3992. len = allocSize - 2; // keep space for leading and trailing space
  3993. err = sysctlbyname("machdep.cpu.features", buf + 1, &len, NULL, 0);
  3994. }
  3995. if (!err && buf && len)
  3996. {
  3997. // now we can match every flags as space + flag + space
  3998. buf[len + 1] = ' ';
  3999. std::string cpuflags(buf, len + 2);
  4000. if ((cpuflags.find(" FPU ")!=std::string::npos))
  4001. {
  4002. this->Features.HasFPU = true;
  4003. }
  4004. if ((cpuflags.find(" TSC ")!=std::string::npos))
  4005. {
  4006. this->Features.HasTSC = true;
  4007. }
  4008. if ((cpuflags.find(" MMX ")!=std::string::npos))
  4009. {
  4010. this->Features.HasMMX = true;
  4011. }
  4012. if ((cpuflags.find(" SSE ")!=std::string::npos))
  4013. {
  4014. this->Features.HasSSE = true;
  4015. }
  4016. if ((cpuflags.find(" SSE2 ")!=std::string::npos))
  4017. {
  4018. this->Features.HasSSE2 = true;
  4019. }
  4020. if ((cpuflags.find(" APIC ")!=std::string::npos))
  4021. {
  4022. this->Features.HasAPIC = true;
  4023. }
  4024. if ((cpuflags.find(" CMOV ")!=std::string::npos))
  4025. {
  4026. this->Features.HasCMOV = true;
  4027. }
  4028. if ((cpuflags.find(" MTRR ")!=std::string::npos))
  4029. {
  4030. this->Features.HasMTRR = true;
  4031. }
  4032. if ((cpuflags.find(" ACPI ")!=std::string::npos))
  4033. {
  4034. this->Features.HasACPI = true;
  4035. }
  4036. }
  4037. delete[] buf;
  4038. }
  4039. // brand string
  4040. ::memset(retBuf, 0, sizeof(retBuf));
  4041. len = sizeof(retBuf);
  4042. err = sysctlbyname("machdep.cpu.brand_string", retBuf, &len, NULL, 0);
  4043. if (!err)
  4044. {
  4045. this->ChipID.ProcessorName = retBuf;
  4046. this->ChipID.ModelName = retBuf;
  4047. }
  4048. // Cache size
  4049. len = sizeof(value);
  4050. err = sysctlbyname("hw.l1icachesize", &value, &len, NULL, 0);
  4051. this->Features.L1CacheSize = static_cast< int >( value );
  4052. len = sizeof(value);
  4053. err = sysctlbyname("hw.l2cachesize", &value, &len, NULL, 0);
  4054. this->Features.L2CacheSize = static_cast< int >( value );
  4055. return true;
  4056. #else
  4057. return false;
  4058. #endif
  4059. }
  4060. /** Extract a value from sysctl command */
  4061. std::string SystemInformationImplementation::ExtractValueFromSysCtl(const char* word)
  4062. {
  4063. size_t pos = this->SysCtlBuffer.find(word);
  4064. if(pos != this->SysCtlBuffer.npos)
  4065. {
  4066. pos = this->SysCtlBuffer.find(": ",pos);
  4067. size_t pos2 = this->SysCtlBuffer.find("\n",pos);
  4068. if(pos!=this->SysCtlBuffer.npos && pos2!=this->SysCtlBuffer.npos)
  4069. {
  4070. return this->SysCtlBuffer.substr(pos+2,pos2-pos-2);
  4071. }
  4072. }
  4073. return "";
  4074. }
  4075. /** Run a given process */
  4076. std::string SystemInformationImplementation::RunProcess(std::vector<const char*> args)
  4077. {
  4078. std::string buffer = "";
  4079. // Run the application
  4080. kwsysProcess* gp = kwsysProcess_New();
  4081. kwsysProcess_SetCommand(gp, &*args.begin());
  4082. kwsysProcess_SetOption(gp,kwsysProcess_Option_HideWindow,1);
  4083. kwsysProcess_Execute(gp);
  4084. char* data = NULL;
  4085. int length;
  4086. double timeout = 255;
  4087. int pipe; // pipe id as returned by kwsysProcess_WaitForData()
  4088. while( ( pipe = kwsysProcess_WaitForData(gp,&data,&length,&timeout),
  4089. (pipe == kwsysProcess_Pipe_STDOUT || pipe == kwsysProcess_Pipe_STDERR) ) ) // wait for 1s
  4090. {
  4091. buffer.append(data, length);
  4092. }
  4093. kwsysProcess_WaitForExit(gp, 0);
  4094. int result = 0;
  4095. switch(kwsysProcess_GetState(gp))
  4096. {
  4097. case kwsysProcess_State_Exited:
  4098. {
  4099. result = kwsysProcess_GetExitValue(gp);
  4100. } break;
  4101. case kwsysProcess_State_Error:
  4102. {
  4103. std::cerr << "Error: Could not run " << args[0] << ":\n";
  4104. std::cerr << kwsysProcess_GetErrorString(gp) << "\n";
  4105. } break;
  4106. case kwsysProcess_State_Exception:
  4107. {
  4108. std::cerr << "Error: " << args[0]
  4109. << " terminated with an exception: "
  4110. << kwsysProcess_GetExceptionString(gp) << "\n";
  4111. } break;
  4112. case kwsysProcess_State_Starting:
  4113. case kwsysProcess_State_Executing:
  4114. case kwsysProcess_State_Expired:
  4115. case kwsysProcess_State_Killed:
  4116. {
  4117. // Should not get here.
  4118. std::cerr << "Unexpected ending state after running " << args[0]
  4119. << std::endl;
  4120. } break;
  4121. }
  4122. kwsysProcess_Delete(gp);
  4123. if(result)
  4124. {
  4125. std::cerr << "Error " << args[0] << " returned :" << result << "\n";
  4126. }
  4127. return buffer;
  4128. }
  4129. std::string SystemInformationImplementation::ParseValueFromKStat(const char* arguments)
  4130. {
  4131. std::vector<const char*> args;
  4132. args.clear();
  4133. args.push_back("kstat");
  4134. args.push_back("-p");
  4135. std::string command = arguments;
  4136. size_t start = command.npos;
  4137. size_t pos = command.find(' ',0);
  4138. while(pos!=command.npos)
  4139. {
  4140. bool inQuotes = false;
  4141. // Check if we are between quotes
  4142. size_t b0 = command.find('"',0);
  4143. size_t b1 = command.find('"',b0+1);
  4144. while(b0 != command.npos && b1 != command.npos && b1>b0)
  4145. {
  4146. if(pos>b0 && pos<b1)
  4147. {
  4148. inQuotes = true;
  4149. break;
  4150. }
  4151. b0 = command.find('"',b1+1);
  4152. b1 = command.find('"',b0+1);
  4153. }
  4154. if(!inQuotes)
  4155. {
  4156. std::string arg = command.substr(start+1,pos-start-1);
  4157. // Remove the quotes if any
  4158. size_t quotes = arg.find('"');
  4159. while(quotes != arg.npos)
  4160. {
  4161. arg.erase(quotes,1);
  4162. quotes = arg.find('"');
  4163. }
  4164. args.push_back(arg.c_str());
  4165. start = pos;
  4166. }
  4167. pos = command.find(' ',pos+1);
  4168. }
  4169. std::string lastArg = command.substr(start+1,command.size()-start-1);
  4170. args.push_back(lastArg.c_str());
  4171. args.push_back(0);
  4172. std::string buffer = this->RunProcess(args);
  4173. std::string value = "";
  4174. for(size_t i=buffer.size()-1;i>0;i--)
  4175. {
  4176. if(buffer[i] == ' ' || buffer[i] == '\t')
  4177. {
  4178. break;
  4179. }
  4180. if(buffer[i] != '\n' && buffer[i] != '\r')
  4181. {
  4182. std::string val = value;
  4183. value = buffer[i];
  4184. value += val;
  4185. }
  4186. }
  4187. return value;
  4188. }
  4189. /** Querying for system information from Solaris */
  4190. bool SystemInformationImplementation::QuerySolarisMemory()
  4191. {
  4192. #if defined (__SVR4) && defined (__sun)
  4193. // Solaris allows querying this value by sysconf, but if this is
  4194. // a 32 bit process on a 64 bit host the returned memory will be
  4195. // limited to 4GiB. So if this is a 32 bit process or if the sysconf
  4196. // method fails use the kstat interface.
  4197. #if SIZEOF_VOID_P == 8
  4198. if (this->QueryMemoryBySysconf())
  4199. {
  4200. return true;
  4201. }
  4202. #endif
  4203. char* tail;
  4204. unsigned long totalMemory =
  4205. strtoul(this->ParseValueFromKStat("-s physmem").c_str(),&tail,0);
  4206. this->TotalPhysicalMemory = totalMemory/128;
  4207. return true;
  4208. #else
  4209. return false;
  4210. #endif
  4211. }
  4212. bool SystemInformationImplementation::QuerySolarisProcessor()
  4213. {
  4214. if (!this->QueryProcessorBySysconf())
  4215. {
  4216. return false;
  4217. }
  4218. // Parse values
  4219. this->CPUSpeedInMHz = static_cast<float>(atoi(this->ParseValueFromKStat("-s clock_MHz").c_str()));
  4220. // Chip family
  4221. this->ChipID.Family = 0;
  4222. // Chip Model
  4223. this->ChipID.ProcessorName = this->ParseValueFromKStat("-s cpu_type");
  4224. this->ChipID.Model = 0;
  4225. // Chip Vendor
  4226. if (this->ChipID.ProcessorName != "i386")
  4227. {
  4228. this->ChipID.Vendor = "Sun";
  4229. this->FindManufacturer();
  4230. }
  4231. return true;
  4232. }
  4233. /** Querying for system information from Haiku OS */
  4234. bool SystemInformationImplementation::QueryHaikuInfo()
  4235. {
  4236. #if defined(__HAIKU__)
  4237. // CPU count
  4238. system_info info;
  4239. get_system_info(&info);
  4240. this->NumberOfPhysicalCPU = info.cpu_count;
  4241. // CPU speed
  4242. uint32 topologyNodeCount = 0;
  4243. cpu_topology_node_info* topology = 0;
  4244. get_cpu_topology_info(0, &topologyNodeCount);
  4245. if (topologyNodeCount != 0)
  4246. topology = new cpu_topology_node_info[topologyNodeCount];
  4247. get_cpu_topology_info(topology, &topologyNodeCount);
  4248. for (uint32 i = 0; i < topologyNodeCount; i++) {
  4249. if (topology[i].type == B_TOPOLOGY_CORE) {
  4250. this->CPUSpeedInMHz = topology[i].data.core.default_frequency /
  4251. 1000000.0f;
  4252. break;
  4253. }
  4254. }
  4255. delete[] topology;
  4256. // Physical Memory
  4257. this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024) ;
  4258. this->AvailablePhysicalMemory = this->TotalPhysicalMemory -
  4259. ((info.used_pages * B_PAGE_SIZE) / (1024 * 1024));
  4260. // NOTE: get_system_info_etc is currently a private call so just set to 0
  4261. // until it becomes public
  4262. this->TotalVirtualMemory = 0;
  4263. this->AvailableVirtualMemory = 0;
  4264. // Retrieve cpuid_info union for cpu 0
  4265. cpuid_info cpu_info;
  4266. get_cpuid(&cpu_info, 0, 0);
  4267. // Chip Vendor
  4268. // Use a temporary buffer so that we can add NULL termination to the string
  4269. char vbuf[13];
  4270. strncpy(vbuf, cpu_info.eax_0.vendor_id, 12);
  4271. vbuf[12] = '\0';
  4272. this->ChipID.Vendor = vbuf;
  4273. this->FindManufacturer();
  4274. // Retrieve cpuid_info union for cpu 0 this time using a register value of 1
  4275. get_cpuid(&cpu_info, 1, 0);
  4276. this->NumberOfLogicalCPU = cpu_info.eax_1.logical_cpus;
  4277. // Chip type
  4278. this->ChipID.Type = cpu_info.eax_1.type;
  4279. // Chip family
  4280. this->ChipID.Family = cpu_info.eax_1.family;
  4281. // Chip Model
  4282. this->ChipID.Model = cpu_info.eax_1.model;
  4283. // Chip Revision
  4284. this->ChipID.Revision = cpu_info.eax_1.stepping;
  4285. // Chip Extended Family
  4286. this->ChipID.ExtendedFamily = cpu_info.eax_1.extended_family;
  4287. // Chip Extended Model
  4288. this->ChipID.ExtendedModel = cpu_info.eax_1.extended_model;
  4289. // Get ChipID.ProcessorName from other information already gathered
  4290. this->RetrieveClassicalCPUIdentity();
  4291. // Cache size
  4292. this->Features.L1CacheSize = 0;
  4293. this->Features.L2CacheSize = 0;
  4294. return true;
  4295. #else
  4296. return false;
  4297. #endif
  4298. }
  4299. bool SystemInformationImplementation::QueryQNXMemory()
  4300. {
  4301. #if defined(__QNX__)
  4302. std::string buffer;
  4303. std::vector<const char*> args;
  4304. args.clear();
  4305. args.push_back("showmem");
  4306. args.push_back("-S");
  4307. args.push_back(0);
  4308. buffer = this->RunProcess(args);
  4309. args.clear();
  4310. size_t pos = buffer.find("System RAM:");
  4311. if (pos == buffer.npos)
  4312. return false;
  4313. pos = buffer.find(":", pos);
  4314. size_t pos2 = buffer.find("M (", pos);
  4315. if (pos2 == buffer.npos)
  4316. return false;
  4317. pos++;
  4318. while (buffer[pos] == ' ')
  4319. pos++;
  4320. this->TotalPhysicalMemory = atoi(buffer.substr(pos, pos2 - pos).c_str());
  4321. return true;
  4322. #endif
  4323. return false;
  4324. }
  4325. bool SystemInformationImplementation::QueryBSDMemory()
  4326. {
  4327. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  4328. int ctrl[2] = { CTL_HW, HW_PHYSMEM };
  4329. #if defined(HW_PHYSMEM64)
  4330. int64_t k;
  4331. ctrl[1] = HW_PHYSMEM64;
  4332. #else
  4333. int k;
  4334. #endif
  4335. size_t sz = sizeof(k);
  4336. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4337. {
  4338. return false;
  4339. }
  4340. this->TotalPhysicalMemory = k>>10>>10;
  4341. return true;
  4342. #else
  4343. return false;
  4344. #endif
  4345. }
  4346. bool SystemInformationImplementation::QueryQNXProcessor()
  4347. {
  4348. #if defined(__QNX__)
  4349. // the output on my QNX 6.4.1 looks like this:
  4350. // Processor1: 686 Pentium II Stepping 3 2175MHz FPU
  4351. std::string buffer;
  4352. std::vector<const char*> args;
  4353. args.clear();
  4354. args.push_back("pidin");
  4355. args.push_back("info");
  4356. args.push_back(0);
  4357. buffer = this->RunProcess(args);
  4358. args.clear();
  4359. size_t pos = buffer.find("Processor1:");
  4360. if (pos == buffer.npos)
  4361. return false;
  4362. size_t pos2 = buffer.find("MHz", pos);
  4363. if (pos2 == buffer.npos)
  4364. return false;
  4365. size_t pos3 = pos2;
  4366. while (buffer[pos3] != ' ')
  4367. --pos3;
  4368. this->CPUSpeedInMHz = atoi(buffer.substr(pos3 + 1, pos2 - pos3 - 1).c_str());
  4369. pos2 = buffer.find(" Stepping", pos);
  4370. if (pos2 != buffer.npos)
  4371. {
  4372. pos2 = buffer.find(" ", pos2 + 1);
  4373. if (pos2 != buffer.npos && pos2 < pos3)
  4374. {
  4375. this->ChipID.Revision = atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str());
  4376. }
  4377. }
  4378. this->NumberOfPhysicalCPU = 0;
  4379. do
  4380. {
  4381. pos = buffer.find("\nProcessor", pos + 1);
  4382. ++this->NumberOfPhysicalCPU;
  4383. } while (pos != buffer.npos);
  4384. this->NumberOfLogicalCPU = 1;
  4385. return true;
  4386. #else
  4387. return false;
  4388. #endif
  4389. }
  4390. bool SystemInformationImplementation::QueryBSDProcessor()
  4391. {
  4392. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  4393. int k;
  4394. size_t sz = sizeof(k);
  4395. int ctrl[2] = { CTL_HW, HW_NCPU };
  4396. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4397. {
  4398. return false;
  4399. }
  4400. this->NumberOfPhysicalCPU = k;
  4401. this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
  4402. #if defined(HW_CPUSPEED)
  4403. ctrl[1] = HW_CPUSPEED;
  4404. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4405. {
  4406. return false;
  4407. }
  4408. this->CPUSpeedInMHz = (float) k;
  4409. #endif
  4410. #if defined(CPU_SSE)
  4411. ctrl[0] = CTL_MACHDEP;
  4412. ctrl[1] = CPU_SSE;
  4413. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4414. {
  4415. return false;
  4416. }
  4417. this->Features.HasSSE = (k > 0);
  4418. #endif
  4419. #if defined(CPU_SSE2)
  4420. ctrl[0] = CTL_MACHDEP;
  4421. ctrl[1] = CPU_SSE2;
  4422. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4423. {
  4424. return false;
  4425. }
  4426. this->Features.HasSSE2 = (k > 0);
  4427. #endif
  4428. #if defined(CPU_CPUVENDOR)
  4429. ctrl[0] = CTL_MACHDEP;
  4430. ctrl[1] = CPU_CPUVENDOR;
  4431. char vbuf[25];
  4432. ::memset(vbuf, 0, sizeof(vbuf));
  4433. sz = sizeof(vbuf) - 1;
  4434. if (sysctl(ctrl, 2, vbuf, &sz, NULL, 0) != 0)
  4435. {
  4436. return false;
  4437. }
  4438. this->ChipID.Vendor = vbuf;
  4439. this->FindManufacturer();
  4440. #endif
  4441. return true;
  4442. #else
  4443. return false;
  4444. #endif
  4445. }
  4446. bool SystemInformationImplementation::QueryHPUXMemory()
  4447. {
  4448. #if defined(__hpux)
  4449. unsigned long tv=0;
  4450. unsigned long tp=0;
  4451. unsigned long av=0;
  4452. unsigned long ap=0;
  4453. struct pst_static pst;
  4454. struct pst_dynamic pdy;
  4455. unsigned long ps = 0;
  4456. if (pstat_getstatic(&pst, sizeof(pst), (size_t) 1, 0) == -1)
  4457. {
  4458. return false;
  4459. }
  4460. ps = pst.page_size;
  4461. tp = pst.physical_memory *ps;
  4462. tv = (pst.physical_memory + pst.pst_maxmem) * ps;
  4463. if (pstat_getdynamic(&pdy, sizeof(pdy), (size_t) 1, 0) == -1)
  4464. {
  4465. return false;
  4466. }
  4467. ap = tp - pdy.psd_rm * ps;
  4468. av = tv - pdy.psd_vm;
  4469. this->TotalVirtualMemory = tv>>10>>10;
  4470. this->TotalPhysicalMemory = tp>>10>>10;
  4471. this->AvailableVirtualMemory = av>>10>>10;
  4472. this->AvailablePhysicalMemory = ap>>10>>10;
  4473. return true;
  4474. #else
  4475. return false;
  4476. #endif
  4477. }
  4478. bool SystemInformationImplementation::QueryHPUXProcessor()
  4479. {
  4480. #if defined(__hpux)
  4481. # if defined(KWSYS_SYS_HAS_MPCTL_H)
  4482. int c = mpctl(MPC_GETNUMSPUS_SYS, 0, 0);
  4483. if (c <= 0)
  4484. {
  4485. return false;
  4486. }
  4487. this->NumberOfPhysicalCPU = c;
  4488. this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
  4489. long t = sysconf(_SC_CPU_VERSION);
  4490. if (t == -1)
  4491. {
  4492. return false;
  4493. }
  4494. switch (t)
  4495. {
  4496. case CPU_PA_RISC1_0:
  4497. this->ChipID.Vendor = "Hewlett-Packard";
  4498. this->ChipID.Family = 0x100;
  4499. break;
  4500. case CPU_PA_RISC1_1:
  4501. this->ChipID.Vendor = "Hewlett-Packard";
  4502. this->ChipID.Family = 0x110;
  4503. break;
  4504. case CPU_PA_RISC2_0:
  4505. this->ChipID.Vendor = "Hewlett-Packard";
  4506. this->ChipID.Family = 0x200;
  4507. break;
  4508. # if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0)
  4509. # ifdef CPU_HP_INTEL_EM_1_0
  4510. case CPU_HP_INTEL_EM_1_0:
  4511. # endif
  4512. # ifdef CPU_IA64_ARCHREV_0
  4513. case CPU_IA64_ARCHREV_0:
  4514. # endif
  4515. this->ChipID.Vendor = "GenuineIntel";
  4516. this->Features.HasIA64 = true;
  4517. break;
  4518. # endif
  4519. default:
  4520. return false;
  4521. }
  4522. this->FindManufacturer();
  4523. return true;
  4524. # else
  4525. return false;
  4526. # endif
  4527. #else
  4528. return false;
  4529. #endif
  4530. }
  4531. /** Query the operating system information */
  4532. bool SystemInformationImplementation::QueryOSInformation()
  4533. {
  4534. #if defined(_WIN32)
  4535. this->OSName = "Windows";
  4536. OSVERSIONINFOEXW osvi;
  4537. BOOL bIsWindows64Bit;
  4538. BOOL bOsVersionInfoEx;
  4539. char operatingSystem[256];
  4540. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  4541. ZeroMemory (&osvi, sizeof (OSVERSIONINFOEXW));
  4542. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
  4543. #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  4544. # pragma warning (push)
  4545. # ifdef __INTEL_COMPILER
  4546. # pragma warning (disable:1478)
  4547. # else
  4548. # pragma warning (disable:4996)
  4549. # endif
  4550. #endif
  4551. bOsVersionInfoEx = GetVersionExW ((OSVERSIONINFOW*)&osvi);
  4552. if (!bOsVersionInfoEx)
  4553. {
  4554. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOW);
  4555. if (!GetVersionExW((OSVERSIONINFOW*)&osvi))
  4556. {
  4557. return false;
  4558. }
  4559. }
  4560. #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  4561. # pragma warning (pop)
  4562. #endif
  4563. switch (osvi.dwPlatformId)
  4564. {
  4565. case VER_PLATFORM_WIN32_NT:
  4566. // Test for the product.
  4567. if (osvi.dwMajorVersion <= 4)
  4568. {
  4569. this->OSRelease = "NT";
  4570. }
  4571. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  4572. {
  4573. this->OSRelease = "2000";
  4574. }
  4575. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4576. {
  4577. this->OSRelease = "XP";
  4578. }
  4579. // XP Professional x64
  4580. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  4581. {
  4582. this->OSRelease = "XP";
  4583. }
  4584. #ifdef VER_NT_WORKSTATION
  4585. // Test for product type.
  4586. if (bOsVersionInfoEx)
  4587. {
  4588. if (osvi.wProductType == VER_NT_WORKSTATION)
  4589. {
  4590. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
  4591. {
  4592. this->OSRelease = "Vista";
  4593. }
  4594. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
  4595. {
  4596. this->OSRelease = "7";
  4597. }
  4598. // VER_SUITE_PERSONAL may not be defined
  4599. #ifdef VER_SUITE_PERSONAL
  4600. else
  4601. {
  4602. if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  4603. {
  4604. this->OSRelease += " Personal";
  4605. }
  4606. else
  4607. {
  4608. this->OSRelease += " Professional";
  4609. }
  4610. }
  4611. #endif
  4612. }
  4613. else if (osvi.wProductType == VER_NT_SERVER)
  4614. {
  4615. // Check for .NET Server instead of Windows XP.
  4616. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4617. {
  4618. this->OSRelease = ".NET";
  4619. }
  4620. // Continue with the type detection.
  4621. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  4622. {
  4623. this->OSRelease += " DataCenter Server";
  4624. }
  4625. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4626. {
  4627. this->OSRelease += " Advanced Server";
  4628. }
  4629. else
  4630. {
  4631. this->OSRelease += " Server";
  4632. }
  4633. }
  4634. sprintf (operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
  4635. this->OSVersion = operatingSystem;
  4636. }
  4637. else
  4638. #endif // VER_NT_WORKSTATION
  4639. {
  4640. HKEY hKey;
  4641. wchar_t szProductType[80];
  4642. DWORD dwBufLen;
  4643. // Query the registry to retrieve information.
  4644. RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey);
  4645. RegQueryValueExW(hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen);
  4646. RegCloseKey (hKey);
  4647. if (lstrcmpiW(L"WINNT", szProductType) == 0)
  4648. {
  4649. this->OSRelease += " Professional";
  4650. }
  4651. if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
  4652. {
  4653. // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
  4654. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4655. {
  4656. this->OSRelease += " Standard Server";
  4657. }
  4658. else
  4659. {
  4660. this->OSRelease += " Server";
  4661. }
  4662. }
  4663. if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
  4664. {
  4665. // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
  4666. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4667. {
  4668. this->OSRelease += " Enterprise Server";
  4669. }
  4670. else
  4671. {
  4672. this->OSRelease += " Advanced Server";
  4673. }
  4674. }
  4675. }
  4676. // Display version, service pack (if any), and build number.
  4677. if (osvi.dwMajorVersion <= 4)
  4678. {
  4679. // NB: NT 4.0 and earlier.
  4680. sprintf (operatingSystem, "version %ld.%ld %ls (Build %ld)",
  4681. osvi.dwMajorVersion,
  4682. osvi.dwMinorVersion,
  4683. osvi.szCSDVersion,
  4684. osvi.dwBuildNumber & 0xFFFF);
  4685. this->OSVersion = operatingSystem;
  4686. }
  4687. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4688. {
  4689. // Windows XP and .NET server.
  4690. typedef BOOL (CALLBACK* LPFNPROC) (HANDLE, BOOL *);
  4691. HINSTANCE hKernelDLL;
  4692. LPFNPROC DLLProc;
  4693. // Load the Kernel32 DLL.
  4694. hKernelDLL = LoadLibraryW(L"kernel32");
  4695. if (hKernelDLL != NULL) {
  4696. // Only XP and .NET Server support IsWOW64Process so... Load dynamically!
  4697. DLLProc = (LPFNPROC) GetProcAddress (hKernelDLL, "IsWow64Process");
  4698. // If the function address is valid, call the function.
  4699. if (DLLProc != NULL) (DLLProc) (GetCurrentProcess (), &bIsWindows64Bit);
  4700. else bIsWindows64Bit = false;
  4701. // Free the DLL module.
  4702. FreeLibrary (hKernelDLL);
  4703. }
  4704. }
  4705. else
  4706. {
  4707. // Windows 2000 and everything else.
  4708. sprintf (operatingSystem,"%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
  4709. this->OSVersion = operatingSystem;
  4710. }
  4711. break;
  4712. case VER_PLATFORM_WIN32_WINDOWS:
  4713. // Test for the product.
  4714. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  4715. {
  4716. this->OSRelease = "95";
  4717. if(osvi.szCSDVersion[1] == 'C')
  4718. {
  4719. this->OSRelease += "OSR 2.5";
  4720. }
  4721. else if(osvi.szCSDVersion[1] == 'B')
  4722. {
  4723. this->OSRelease += "OSR 2";
  4724. }
  4725. }
  4726. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  4727. {
  4728. this->OSRelease = "98";
  4729. if (osvi.szCSDVersion[1] == 'A' )
  4730. {
  4731. this->OSRelease += "SE";
  4732. }
  4733. }
  4734. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  4735. {
  4736. this->OSRelease = "Me";
  4737. }
  4738. break;
  4739. case VER_PLATFORM_WIN32s:
  4740. this->OSRelease = "Win32s";
  4741. break;
  4742. default:
  4743. this->OSRelease = "Unknown";
  4744. break;
  4745. }
  4746. // Get the hostname
  4747. WORD wVersionRequested;
  4748. WSADATA wsaData;
  4749. char name[255];
  4750. wVersionRequested = MAKEWORD(2,0);
  4751. if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
  4752. {
  4753. gethostname(name,sizeof(name));
  4754. WSACleanup( );
  4755. }
  4756. this->Hostname = name;
  4757. const char* arch = getenv("PROCESSOR_ARCHITECTURE");
  4758. if(arch)
  4759. {
  4760. this->OSPlatform = arch;
  4761. }
  4762. #else
  4763. struct utsname unameInfo;
  4764. int errorFlag = uname(&unameInfo);
  4765. if(errorFlag == 0)
  4766. {
  4767. this->OSName = unameInfo.sysname;
  4768. this->Hostname = unameInfo.nodename;
  4769. this->OSRelease = unameInfo.release;
  4770. this->OSVersion = unameInfo.version;
  4771. this->OSPlatform = unameInfo.machine;
  4772. }
  4773. #ifdef __APPLE__
  4774. this->OSName="Unknown Apple OS";
  4775. this->OSRelease="Unknown product version";
  4776. this->OSVersion="Unknown build version";
  4777. this->CallSwVers("-productName",this->OSName);
  4778. this->CallSwVers("-productVersion",this->OSRelease);
  4779. this->CallSwVers("-buildVersion",this->OSVersion);
  4780. #endif
  4781. #endif
  4782. return true;
  4783. }
  4784. int SystemInformationImplementation::CallSwVers(
  4785. const char *arg,
  4786. std::string &ver)
  4787. {
  4788. #ifdef __APPLE__
  4789. std::vector<const char*> args;
  4790. args.push_back("sw_vers");
  4791. args.push_back(arg);
  4792. args.push_back(0);
  4793. ver = this->RunProcess(args);
  4794. this->TrimNewline(ver);
  4795. #else
  4796. // avoid C4100
  4797. (void)arg;
  4798. (void)ver;
  4799. #endif
  4800. return 0;
  4801. }
  4802. void SystemInformationImplementation::TrimNewline(std::string& output)
  4803. {
  4804. // remove \r
  4805. std::string::size_type pos=0;
  4806. while((pos = output.find("\r", pos)) != std::string::npos)
  4807. {
  4808. output.erase(pos);
  4809. }
  4810. // remove \n
  4811. pos = 0;
  4812. while((pos = output.find("\n", pos)) != std::string::npos)
  4813. {
  4814. output.erase(pos);
  4815. }
  4816. }
  4817. /** Return true if the machine is 64 bits */
  4818. bool SystemInformationImplementation::Is64Bits()
  4819. {
  4820. return (sizeof(void*) == 8);
  4821. }
  4822. } // namespace @KWSYS_NAMESPACE@