SystemInformation.cxx 152 KB

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