SystemInformation.cxx 153 KB

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