SystemInformation.cxx 152 KB

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