SystemInformation.cxx 152 KB

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