SystemInformation.cxx 147 KB

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