SystemInformation.cxx 144 KB

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