SystemInformation.cxx 150 KB

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