SystemTools.cxx 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647
  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. #ifdef __osf__
  11. # define _OSF_SOURCE
  12. # define _POSIX_C_SOURCE 199506L
  13. # define _XOPEN_SOURCE_EXTENDED
  14. #endif
  15. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
  16. # define KWSYS_WINDOWS_DIRS
  17. #else
  18. # if defined(__SUNPRO_CC)
  19. # include <fcntl.h>
  20. # endif
  21. #endif
  22. #include "kwsysPrivate.h"
  23. #include KWSYS_HEADER(RegularExpression.hxx)
  24. #include KWSYS_HEADER(SystemTools.hxx)
  25. #include KWSYS_HEADER(Directory.hxx)
  26. #include KWSYS_HEADER(FStream.hxx)
  27. #include KWSYS_HEADER(Encoding.hxx)
  28. #include <iostream>
  29. #include <fstream>
  30. #include <sstream>
  31. #include <set>
  32. #include <vector>
  33. // Work-around CMake dependency scanning limitation. This must
  34. // duplicate the above list of headers.
  35. #if 0
  36. # include "RegularExpression.hxx.in"
  37. # include "SystemTools.hxx.in"
  38. # include "Directory.hxx.in"
  39. # include "FStream.hxx.in"
  40. # include "Encoding.hxx.in"
  41. #endif
  42. #ifdef _MSC_VER
  43. # pragma warning (disable: 4786)
  44. #endif
  45. #if defined(__sgi) && !defined(__GNUC__)
  46. # pragma set woff 1375 /* base class destructor not virtual */
  47. #endif
  48. #include <ctype.h>
  49. #include <errno.h>
  50. #ifdef __QNX__
  51. # include <malloc.h> /* for malloc/free on QNX */
  52. #endif
  53. #include <stdio.h>
  54. #include <stdlib.h>
  55. #include <string.h>
  56. #include <sys/stat.h>
  57. #include <time.h>
  58. #ifdef _MSC_VER
  59. # define umask _umask // Note this is still umask on Borland
  60. #endif
  61. // support for realpath call
  62. #ifndef _WIN32
  63. #include <sys/time.h>
  64. #include <utime.h>
  65. #include <limits.h>
  66. #include <sys/wait.h>
  67. #include <sys/ioctl.h>
  68. #include <unistd.h>
  69. #include <pwd.h>
  70. #ifndef __VMS
  71. #include <sys/param.h>
  72. #include <termios.h>
  73. #endif
  74. #include <signal.h> /* sigprocmask */
  75. #endif
  76. // Windows API.
  77. #if defined(_WIN32)
  78. # include <windows.h>
  79. # include <winioctl.h>
  80. # ifndef INVALID_FILE_ATTRIBUTES
  81. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  82. # endif
  83. # if defined(_MSC_VER) && _MSC_VER >= 1800
  84. # define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  85. # endif
  86. #elif defined (__CYGWIN__)
  87. # include <windows.h>
  88. # undef _WIN32
  89. #endif
  90. #if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
  91. extern char **environ;
  92. #endif
  93. #ifdef __CYGWIN__
  94. # include <sys/cygwin.h>
  95. #endif
  96. // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
  97. // same for TIOCGWINSZ
  98. #if defined(_WIN32) || defined (__LIBCATAMOUNT__)
  99. # undef HAVE_GETPWNAM
  100. # undef HAVE_TTY_INFO
  101. #else
  102. # define HAVE_GETPWNAM 1
  103. # define HAVE_TTY_INFO 1
  104. #endif
  105. #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
  106. #define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"
  107. #ifdef _MSC_VER
  108. #include <sys/utime.h>
  109. #else
  110. #include <utime.h>
  111. #endif
  112. // This is a hack to prevent warnings about these functions being
  113. // declared but not referenced.
  114. #if defined(__sgi) && !defined(__GNUC__)
  115. # include <sys/termios.h>
  116. namespace KWSYS_NAMESPACE
  117. {
  118. class SystemToolsHack
  119. {
  120. public:
  121. enum
  122. {
  123. Ref1 = sizeof(cfgetospeed(0)),
  124. Ref2 = sizeof(cfgetispeed(0)),
  125. Ref3 = sizeof(tcgetattr(0, 0)),
  126. Ref4 = sizeof(tcsetattr(0, 0, 0)),
  127. Ref5 = sizeof(cfsetospeed(0,0)),
  128. Ref6 = sizeof(cfsetispeed(0,0))
  129. };
  130. };
  131. }
  132. #endif
  133. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
  134. #include <io.h>
  135. #include <direct.h>
  136. #define _unlink unlink
  137. #endif
  138. /* The maximum length of a file name. */
  139. #if defined(PATH_MAX)
  140. # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
  141. #elif defined(MAXPATHLEN)
  142. # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
  143. #else
  144. # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
  145. #endif
  146. #if defined(__WATCOMC__)
  147. #include <direct.h>
  148. #define _mkdir mkdir
  149. #define _rmdir rmdir
  150. #define _getcwd getcwd
  151. #define _chdir chdir
  152. #endif
  153. #if defined(__BEOS__) && !defined(__ZETA__)
  154. #include <be/kernel/OS.h>
  155. #include <be/storage/Path.h>
  156. // BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
  157. static inline void usleep(unsigned int msec)
  158. {
  159. ::snooze(msec);
  160. }
  161. // BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
  162. static inline char *realpath(const char *path, char *resolved_path)
  163. {
  164. const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
  165. snprintf(resolved_path, maxlen, "%s", path);
  166. BPath normalized(resolved_path, NULL, true);
  167. const char *resolved = normalized.Path();
  168. if (resolved != NULL) // NULL == No such file.
  169. {
  170. if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
  171. {
  172. return resolved_path;
  173. }
  174. }
  175. return NULL; // something went wrong.
  176. }
  177. #endif
  178. #ifdef _WIN32
  179. static time_t windows_filetime_to_posix_time(const FILETIME& ft)
  180. {
  181. LARGE_INTEGER date;
  182. date.HighPart = ft.dwHighDateTime;
  183. date.LowPart = ft.dwLowDateTime;
  184. // removes the diff between 1970 and 1601
  185. date.QuadPart -= ((LONGLONG)(369 * 365 + 89) * 24 * 3600 * 10000000);
  186. // converts back from 100-nanoseconds to seconds
  187. return date.QuadPart / 10000000;
  188. }
  189. #endif
  190. #ifdef KWSYS_WINDOWS_DIRS
  191. #include <wctype.h>
  192. inline int Mkdir(const std::string& dir)
  193. {
  194. return _wmkdir(
  195. KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str());
  196. }
  197. inline int Rmdir(const std::string& dir)
  198. {
  199. return _wrmdir(
  200. KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str());
  201. }
  202. inline const char* Getcwd(char* buf, unsigned int len)
  203. {
  204. std::vector<wchar_t> w_buf(len);
  205. if(_wgetcwd(&w_buf[0], len))
  206. {
  207. // make sure the drive letter is capital
  208. if(wcslen(&w_buf[0]) > 1 && w_buf[1] == L':')
  209. {
  210. w_buf[0] = towupper(w_buf[0]);
  211. }
  212. std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]);
  213. strcpy(buf, tmp.c_str());
  214. return buf;
  215. }
  216. return 0;
  217. }
  218. inline int Chdir(const std::string& dir)
  219. {
  220. #if defined(__BORLANDC__)
  221. return chdir(dir.c_str());
  222. #else
  223. return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
  224. #endif
  225. }
  226. inline void Realpath(const std::string& path,
  227. std::string& resolved_path,
  228. std::string* errorMessage = 0)
  229. {
  230. std::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
  231. wchar_t *ptemp;
  232. wchar_t fullpath[MAX_PATH];
  233. DWORD bufferLen = GetFullPathNameW(tmp.c_str(),
  234. sizeof(fullpath) / sizeof(fullpath[0]),
  235. fullpath, &ptemp);
  236. if( bufferLen < sizeof(fullpath)/sizeof(fullpath[0]) )
  237. {
  238. resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath);
  239. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  240. }
  241. else if(errorMessage)
  242. {
  243. if(bufferLen)
  244. {
  245. *errorMessage = "Destination path buffer size too small.";
  246. }
  247. else if(unsigned int errorId = GetLastError())
  248. {
  249. LPSTR message = NULL;
  250. DWORD size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
  251. | FORMAT_MESSAGE_FROM_SYSTEM
  252. | FORMAT_MESSAGE_IGNORE_INSERTS,
  253. NULL, errorId,
  254. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  255. (LPSTR)&message, 0, NULL);
  256. *errorMessage = std::string(message, size);
  257. LocalFree(message);
  258. }
  259. else
  260. {
  261. *errorMessage = "Unknown error.";
  262. }
  263. resolved_path = "";
  264. }
  265. else
  266. {
  267. resolved_path = path;
  268. }
  269. }
  270. #else
  271. #include <sys/types.h>
  272. #include <fcntl.h>
  273. #include <unistd.h>
  274. inline int Mkdir(const std::string& dir)
  275. {
  276. return mkdir(dir.c_str(), 00777);
  277. }
  278. inline int Rmdir(const std::string& dir)
  279. {
  280. return rmdir(dir.c_str());
  281. }
  282. inline const char* Getcwd(char* buf, unsigned int len)
  283. {
  284. return getcwd(buf, len);
  285. }
  286. inline int Chdir(const std::string& dir)
  287. {
  288. return chdir(dir.c_str());
  289. }
  290. inline void Realpath(const std::string& path,
  291. std::string& resolved_path,
  292. std::string* errorMessage = 0)
  293. {
  294. char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
  295. errno = 0;
  296. char *ret = realpath(path.c_str(), resolved_name);
  297. if(ret)
  298. {
  299. resolved_path = ret;
  300. }
  301. else if(errorMessage)
  302. {
  303. if(errno)
  304. {
  305. *errorMessage = strerror(errno);
  306. }
  307. else
  308. {
  309. *errorMessage = "Unknown error.";
  310. }
  311. resolved_path = "";
  312. }
  313. else
  314. {
  315. // if path resolution fails, return what was passed in
  316. resolved_path = path;
  317. }
  318. }
  319. #endif
  320. #if !defined(_WIN32) && defined(__COMO__)
  321. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  322. extern "C"
  323. {
  324. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  325. extern int pclose (FILE *__stream) __THROW;
  326. extern char *realpath (__const char *__restrict __name,
  327. char *__restrict __resolved) __THROW;
  328. extern char *strdup (__const char *__s) __THROW;
  329. extern int putenv (char *__string) __THROW;
  330. }
  331. #endif
  332. namespace KWSYS_NAMESPACE
  333. {
  334. double SystemTools::GetTime(void)
  335. {
  336. #if defined(_WIN32) && !defined(__CYGWIN__)
  337. FILETIME ft;
  338. GetSystemTimeAsFileTime(&ft);
  339. return (429.4967296*ft.dwHighDateTime
  340. + 0.0000001*ft.dwLowDateTime
  341. - 11644473600.0);
  342. #else
  343. struct timeval t;
  344. gettimeofday(&t, 0);
  345. return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec);
  346. #endif
  347. }
  348. class SystemToolsTranslationMap :
  349. public std::map<std::string,std::string>
  350. {
  351. };
  352. /* Type of character storing the environment. */
  353. #if defined(_WIN32)
  354. typedef wchar_t envchar;
  355. #else
  356. typedef char envchar;
  357. #endif
  358. /* Order by environment key only (VAR from VAR=VALUE). */
  359. struct kwsysEnvCompare
  360. {
  361. bool operator() (const envchar* l, const envchar* r) const
  362. {
  363. #if defined(_WIN32)
  364. const wchar_t* leq = wcschr(l, L'=');
  365. const wchar_t* req = wcschr(r, L'=');
  366. size_t llen = leq? (leq-l) : wcslen(l);
  367. size_t rlen = req? (req-r) : wcslen(r);
  368. if(llen == rlen)
  369. {
  370. return wcsncmp(l,r,llen) < 0;
  371. }
  372. else
  373. {
  374. return wcscmp(l,r) < 0;
  375. }
  376. #else
  377. const char* leq = strchr(l, '=');
  378. const char* req = strchr(r, '=');
  379. size_t llen = leq? (leq-l) : strlen(l);
  380. size_t rlen = req? (req-r) : strlen(r);
  381. if(llen == rlen)
  382. {
  383. return strncmp(l,r,llen) < 0;
  384. }
  385. else
  386. {
  387. return strcmp(l,r) < 0;
  388. }
  389. #endif
  390. }
  391. };
  392. class kwsysEnvSet: public std::set<const envchar*, kwsysEnvCompare>
  393. {
  394. public:
  395. class Free
  396. {
  397. const envchar* Env;
  398. public:
  399. Free(const envchar* env): Env(env) {}
  400. ~Free() { free(const_cast<envchar*>(this->Env)); }
  401. };
  402. const envchar* Release(const envchar* env)
  403. {
  404. const envchar* old = 0;
  405. iterator i = this->find(env);
  406. if(i != this->end())
  407. {
  408. old = *i;
  409. this->erase(i);
  410. }
  411. return old;
  412. }
  413. };
  414. #ifdef _WIN32
  415. struct SystemToolsPathCaseCmp
  416. {
  417. bool operator()(std::string const& l, std::string const& r) const
  418. {
  419. # ifdef _MSC_VER
  420. return _stricmp(l.c_str(), r.c_str()) < 0;
  421. # elif defined(__GNUC__)
  422. return strcasecmp(l.c_str(), r.c_str()) < 0;
  423. # else
  424. return SystemTools::Strucmp(l.c_str(), r.c_str()) < 0;
  425. # endif
  426. }
  427. };
  428. class SystemToolsPathCaseMap:
  429. public std::map<std::string, std::string,
  430. SystemToolsPathCaseCmp> {};
  431. class SystemToolsEnvMap :
  432. public std::map<std::string,std::string> {};
  433. #endif
  434. // adds the elements of the env variable path to the arg passed in
  435. void SystemTools::GetPath(std::vector<std::string>& path, const char* env)
  436. {
  437. size_t const old_size = path.size();
  438. #if defined(_WIN32) && !defined(__CYGWIN__)
  439. const char pathSep = ';';
  440. #else
  441. const char pathSep = ':';
  442. #endif
  443. if(!env)
  444. {
  445. env = "PATH";
  446. }
  447. std::string pathEnv;
  448. if ( !SystemTools::GetEnv(env, pathEnv) )
  449. {
  450. return;
  451. }
  452. // A hack to make the below algorithm work.
  453. if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep)
  454. {
  455. pathEnv += pathSep;
  456. }
  457. std::string::size_type start =0;
  458. bool done = false;
  459. while(!done)
  460. {
  461. std::string::size_type endpos = pathEnv.find(pathSep, start);
  462. if(endpos != std::string::npos)
  463. {
  464. path.push_back(pathEnv.substr(start, endpos-start));
  465. start = endpos+1;
  466. }
  467. else
  468. {
  469. done = true;
  470. }
  471. }
  472. for(std::vector<std::string>::iterator i = path.begin() + old_size;
  473. i != path.end(); ++i)
  474. {
  475. SystemTools::ConvertToUnixSlashes(*i);
  476. }
  477. }
  478. const char* SystemTools::GetEnvImpl(const char* key)
  479. {
  480. const char *v = 0;
  481. #if defined(_WIN32)
  482. std::string env;
  483. if (SystemTools::GetEnv(key, env))
  484. {
  485. std::string& menv = (*SystemTools::EnvMap)[key];
  486. menv = env;
  487. v = menv.c_str();
  488. }
  489. #else
  490. v = getenv(key);
  491. #endif
  492. return v;
  493. }
  494. const char* SystemTools::GetEnv(const char* key)
  495. {
  496. return SystemTools::GetEnvImpl(key);
  497. }
  498. const char* SystemTools::GetEnv(const std::string& key)
  499. {
  500. return SystemTools::GetEnvImpl(key.c_str());
  501. }
  502. bool SystemTools::GetEnv(const char* key, std::string& result)
  503. {
  504. #if defined(_WIN32)
  505. const std::wstring wkey = Encoding::ToWide(key);
  506. const wchar_t* wv = _wgetenv(wkey.c_str());
  507. if (wv)
  508. {
  509. result = Encoding::ToNarrow(wv);
  510. return true;
  511. }
  512. #else
  513. const char* v = getenv(key);
  514. if(v)
  515. {
  516. result = v;
  517. return true;
  518. }
  519. #endif
  520. return false;
  521. }
  522. bool SystemTools::GetEnv(const std::string& key, std::string& result)
  523. {
  524. return SystemTools::GetEnv(key.c_str(), result);
  525. }
  526. bool SystemTools::HasEnv(const char* key)
  527. {
  528. #if defined(_WIN32)
  529. const std::wstring wkey = Encoding::ToWide(key);
  530. const wchar_t* v = _wgetenv(wkey.c_str());
  531. #else
  532. const char* v = getenv(key);
  533. #endif
  534. return v != 0;
  535. }
  536. bool SystemTools::HasEnv(const std::string& key)
  537. {
  538. return SystemTools::HasEnv(key.c_str());
  539. }
  540. //----------------------------------------------------------------------------
  541. #if KWSYS_CXX_HAS_UNSETENV
  542. /* unsetenv("A") removes A from the environment.
  543. On older platforms it returns void instead of int. */
  544. static int kwsysUnPutEnv(const std::string& env)
  545. {
  546. size_t pos = env.find('=');
  547. if(pos != env.npos)
  548. {
  549. std::string name = env.substr(0, pos);
  550. unsetenv(name.c_str());
  551. }
  552. else
  553. {
  554. unsetenv(env.c_str());
  555. }
  556. return 0;
  557. }
  558. #elif defined(__CYGWIN__) || defined(__GLIBC__)
  559. /* putenv("A") removes A from the environment. It must not put the
  560. memory in the environment because it does not have any "=" syntax. */
  561. static int kwsysUnPutEnv(const std::string& env)
  562. {
  563. int err = 0;
  564. size_t pos = env.find('=');
  565. size_t const len = pos == env.npos ? env.size() : pos;
  566. size_t const sz = len + 1;
  567. char local_buf[256];
  568. char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
  569. if(!buf)
  570. {
  571. return -1;
  572. }
  573. strncpy(buf, env.c_str(), len);
  574. buf[len] = 0;
  575. if(putenv(buf) < 0 && errno != EINVAL)
  576. {
  577. err = errno;
  578. }
  579. if(buf != local_buf)
  580. {
  581. free(buf);
  582. }
  583. if(err)
  584. {
  585. errno = err;
  586. return -1;
  587. }
  588. return 0;
  589. }
  590. #elif defined(_WIN32)
  591. /* putenv("A=") places "A=" in the environment, which is as close to
  592. removal as we can get with the putenv API. We have to leak the
  593. most recent value placed in the environment for each variable name
  594. on program exit in case exit routines access it. */
  595. static kwsysEnvSet kwsysUnPutEnvSet;
  596. static int kwsysUnPutEnv(std::string const& env)
  597. {
  598. std::wstring wEnv = Encoding::ToWide(env);
  599. size_t const pos = wEnv.find('=');
  600. size_t const len = pos == wEnv.npos ? wEnv.size() : pos;
  601. wEnv.resize(len+1, L'=');
  602. wchar_t* newEnv = _wcsdup(wEnv.c_str());
  603. if(!newEnv)
  604. {
  605. return -1;
  606. }
  607. kwsysEnvSet::Free oldEnv(kwsysUnPutEnvSet.Release(newEnv));
  608. kwsysUnPutEnvSet.insert(newEnv);
  609. return _wputenv(newEnv);
  610. }
  611. #else
  612. /* Manipulate the "environ" global directly. */
  613. static int kwsysUnPutEnv(const std::string& env)
  614. {
  615. size_t pos = env.find('=');
  616. size_t const len = pos == env.npos ? env.size() : pos;
  617. int in = 0;
  618. int out = 0;
  619. while(environ[in])
  620. {
  621. if(strlen(environ[in]) > len &&
  622. environ[in][len] == '=' &&
  623. strncmp(env.c_str(), environ[in], len) == 0)
  624. {
  625. ++in;
  626. }
  627. else
  628. {
  629. environ[out++] = environ[in++];
  630. }
  631. }
  632. while(out < in)
  633. {
  634. environ[out++] = 0;
  635. }
  636. return 0;
  637. }
  638. #endif
  639. //----------------------------------------------------------------------------
  640. #if KWSYS_CXX_HAS_SETENV
  641. /* setenv("A", "B", 1) will set A=B in the environment and makes its
  642. own copies of the strings. */
  643. bool SystemTools::PutEnv(const std::string& env)
  644. {
  645. size_t pos = env.find('=');
  646. if(pos != env.npos)
  647. {
  648. std::string name = env.substr(0, pos);
  649. return setenv(name.c_str(), env.c_str() + pos + 1, 1) == 0;
  650. }
  651. else
  652. {
  653. return kwsysUnPutEnv(env) == 0;
  654. }
  655. }
  656. bool SystemTools::UnPutEnv(const std::string& env)
  657. {
  658. return kwsysUnPutEnv(env) == 0;
  659. }
  660. #else
  661. /* putenv("A=B") will set A=B in the environment. Most putenv implementations
  662. put their argument directly in the environment. They never free the memory
  663. on program exit. Keep an active set of pointers to memory we allocate and
  664. pass to putenv, one per environment key. At program exit remove any
  665. environment values that may still reference memory we allocated. Then free
  666. the memory. This will not affect any environment values we never set. */
  667. # ifdef __INTEL_COMPILER
  668. # pragma warning disable 444 /* base has non-virtual destructor */
  669. # endif
  670. class kwsysEnv: public kwsysEnvSet
  671. {
  672. public:
  673. ~kwsysEnv()
  674. {
  675. for(iterator i = this->begin(); i != this->end(); ++i)
  676. {
  677. #if defined(_WIN32)
  678. const std::string s = Encoding::ToNarrow(*i);
  679. kwsysUnPutEnv(s.c_str());
  680. #else
  681. kwsysUnPutEnv(*i);
  682. #endif
  683. free(const_cast<envchar*>(*i));
  684. }
  685. }
  686. bool Put(const char* env)
  687. {
  688. #if defined(_WIN32)
  689. const std::wstring wEnv = Encoding::ToWide(env);
  690. wchar_t* newEnv = _wcsdup(wEnv.c_str());
  691. #else
  692. char* newEnv = strdup(env);
  693. #endif
  694. Free oldEnv(this->Release(newEnv));
  695. this->insert(newEnv);
  696. #if defined(_WIN32)
  697. return _wputenv(newEnv) == 0;
  698. #else
  699. return putenv(newEnv) == 0;
  700. #endif
  701. }
  702. bool UnPut(const char* env)
  703. {
  704. #if defined(_WIN32)
  705. const std::wstring wEnv = Encoding::ToWide(env);
  706. Free oldEnv(this->Release(wEnv.c_str()));
  707. #else
  708. Free oldEnv(this->Release(env));
  709. #endif
  710. return kwsysUnPutEnv(env) == 0;
  711. }
  712. };
  713. static kwsysEnv kwsysEnvInstance;
  714. bool SystemTools::PutEnv(const std::string& env)
  715. {
  716. return kwsysEnvInstance.Put(env.c_str());
  717. }
  718. bool SystemTools::UnPutEnv(const std::string& env)
  719. {
  720. return kwsysEnvInstance.UnPut(env.c_str());
  721. }
  722. #endif
  723. //----------------------------------------------------------------------------
  724. const char* SystemTools::GetExecutableExtension()
  725. {
  726. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS)
  727. return ".exe";
  728. #else
  729. return "";
  730. #endif
  731. }
  732. FILE* SystemTools::Fopen(const std::string& file, const char* mode)
  733. {
  734. #ifdef _WIN32
  735. return _wfopen(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
  736. Encoding::ToWide(mode).c_str());
  737. #else
  738. return fopen(file.c_str(), mode);
  739. #endif
  740. }
  741. bool SystemTools::MakeDirectory(const char* path)
  742. {
  743. if(!path)
  744. {
  745. return false;
  746. }
  747. return SystemTools::MakeDirectory(std::string(path));
  748. }
  749. bool SystemTools::MakeDirectory(const std::string& path)
  750. {
  751. if(SystemTools::FileExists(path))
  752. {
  753. return SystemTools::FileIsDirectory(path);
  754. }
  755. if(path.empty())
  756. {
  757. return false;
  758. }
  759. std::string dir = path;
  760. SystemTools::ConvertToUnixSlashes(dir);
  761. std::string::size_type pos = 0;
  762. std::string topdir;
  763. while((pos = dir.find('/', pos)) != std::string::npos)
  764. {
  765. topdir = dir.substr(0, pos);
  766. Mkdir(topdir);
  767. pos++;
  768. }
  769. topdir = dir;
  770. if(Mkdir(topdir) != 0)
  771. {
  772. // There is a bug in the Borland Run time library which makes MKDIR
  773. // return EACCES when it should return EEXISTS
  774. // if it is some other error besides directory exists
  775. // then return false
  776. if( (errno != EEXIST)
  777. #ifdef __BORLANDC__
  778. && (errno != EACCES)
  779. #endif
  780. )
  781. {
  782. return false;
  783. }
  784. }
  785. return true;
  786. }
  787. // replace replace with with as many times as it shows up in source.
  788. // write the result into source.
  789. void SystemTools::ReplaceString(std::string& source,
  790. const std::string& replace,
  791. const std::string& with)
  792. {
  793. // do while hangs if replaceSize is 0
  794. if (replace.empty())
  795. {
  796. return;
  797. }
  798. SystemTools::ReplaceString(source, replace.c_str(), replace.size(), with);
  799. }
  800. void SystemTools::ReplaceString(std::string& source,
  801. const char* replace,
  802. const char* with)
  803. {
  804. // do while hangs if replaceSize is 0
  805. if (!*replace)
  806. {
  807. return;
  808. }
  809. SystemTools::ReplaceString(source, replace, strlen(replace), with ? with : "");
  810. }
  811. void SystemTools::ReplaceString(std::string& source,
  812. const char* replace,
  813. size_t replaceSize,
  814. const std::string& with)
  815. {
  816. const char *src = source.c_str();
  817. char *searchPos = const_cast<char *>(strstr(src,replace));
  818. // get out quick if string is not found
  819. if (!searchPos)
  820. {
  821. return;
  822. }
  823. // perform replacements until done
  824. char *orig = strdup(src);
  825. char *currentPos = orig;
  826. searchPos = searchPos - src + orig;
  827. // initialize the result
  828. source.erase(source.begin(),source.end());
  829. do
  830. {
  831. *searchPos = '\0';
  832. source += currentPos;
  833. currentPos = searchPos + replaceSize;
  834. // replace
  835. source += with;
  836. searchPos = strstr(currentPos,replace);
  837. }
  838. while (searchPos);
  839. // copy any trailing text
  840. source += currentPos;
  841. free(orig);
  842. }
  843. #if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
  844. # define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
  845. # define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
  846. #else
  847. # define KWSYS_ST_KEY_WOW64_32KEY 0x0200
  848. # define KWSYS_ST_KEY_WOW64_64KEY 0x0100
  849. #endif
  850. #if defined(_WIN32) && !defined(__CYGWIN__)
  851. static bool SystemToolsParseRegistryKey(const std::string& key,
  852. HKEY& primaryKey,
  853. std::string& second,
  854. std::string& valuename)
  855. {
  856. std::string primary = key;
  857. size_t start = primary.find('\\');
  858. if (start == std::string::npos)
  859. {
  860. return false;
  861. }
  862. size_t valuenamepos = primary.find(';');
  863. if (valuenamepos != std::string::npos)
  864. {
  865. valuename = primary.substr(valuenamepos+1);
  866. }
  867. second = primary.substr(start+1, valuenamepos-start-1);
  868. primary = primary.substr(0, start);
  869. if (primary == "HKEY_CURRENT_USER")
  870. {
  871. primaryKey = HKEY_CURRENT_USER;
  872. }
  873. if (primary == "HKEY_CURRENT_CONFIG")
  874. {
  875. primaryKey = HKEY_CURRENT_CONFIG;
  876. }
  877. if (primary == "HKEY_CLASSES_ROOT")
  878. {
  879. primaryKey = HKEY_CLASSES_ROOT;
  880. }
  881. if (primary == "HKEY_LOCAL_MACHINE")
  882. {
  883. primaryKey = HKEY_LOCAL_MACHINE;
  884. }
  885. if (primary == "HKEY_USERS")
  886. {
  887. primaryKey = HKEY_USERS;
  888. }
  889. return true;
  890. }
  891. static DWORD SystemToolsMakeRegistryMode(DWORD mode,
  892. SystemTools::KeyWOW64 view)
  893. {
  894. // only add the modes when on a system that supports Wow64.
  895. static FARPROC wow64p = GetProcAddress(GetModuleHandleW(L"kernel32"),
  896. "IsWow64Process");
  897. if(wow64p == NULL)
  898. {
  899. return mode;
  900. }
  901. if(view == SystemTools::KeyWOW64_32)
  902. {
  903. return mode | KWSYS_ST_KEY_WOW64_32KEY;
  904. }
  905. else if(view == SystemTools::KeyWOW64_64)
  906. {
  907. return mode | KWSYS_ST_KEY_WOW64_64KEY;
  908. }
  909. return mode;
  910. }
  911. #endif
  912. #if defined(_WIN32) && !defined(__CYGWIN__)
  913. bool
  914. SystemTools::GetRegistrySubKeys(const std::string& key,
  915. std::vector<std::string>& subkeys,
  916. KeyWOW64 view)
  917. {
  918. HKEY primaryKey = HKEY_CURRENT_USER;
  919. std::string second;
  920. std::string valuename;
  921. if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
  922. {
  923. return false;
  924. }
  925. HKEY hKey;
  926. if(RegOpenKeyExW(primaryKey,
  927. Encoding::ToWide(second).c_str(),
  928. 0,
  929. SystemToolsMakeRegistryMode(KEY_READ, view),
  930. &hKey) != ERROR_SUCCESS)
  931. {
  932. return false;
  933. }
  934. else
  935. {
  936. wchar_t name[1024];
  937. DWORD dwNameSize = sizeof(name)/sizeof(name[0]);
  938. DWORD i = 0;
  939. while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS)
  940. {
  941. subkeys.push_back(Encoding::ToNarrow(name));
  942. ++i;
  943. }
  944. RegCloseKey(hKey);
  945. }
  946. return true;
  947. }
  948. #else
  949. bool SystemTools::GetRegistrySubKeys(const std::string&,
  950. std::vector<std::string>&,
  951. KeyWOW64)
  952. {
  953. return false;
  954. }
  955. #endif
  956. // Read a registry value.
  957. // Example :
  958. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  959. // => will return the data of the "default" value of the key
  960. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  961. // => will return the data of the "Root" value of the key
  962. #if defined(_WIN32) && !defined(__CYGWIN__)
  963. bool SystemTools::ReadRegistryValue(const std::string& key, std::string &value,
  964. KeyWOW64 view)
  965. {
  966. bool valueset = false;
  967. HKEY primaryKey = HKEY_CURRENT_USER;
  968. std::string second;
  969. std::string valuename;
  970. if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
  971. {
  972. return false;
  973. }
  974. HKEY hKey;
  975. if(RegOpenKeyExW(primaryKey,
  976. Encoding::ToWide(second).c_str(),
  977. 0,
  978. SystemToolsMakeRegistryMode(KEY_READ, view),
  979. &hKey) != ERROR_SUCCESS)
  980. {
  981. return false;
  982. }
  983. else
  984. {
  985. DWORD dwType, dwSize;
  986. dwSize = 1023;
  987. wchar_t data[1024];
  988. if(RegQueryValueExW(hKey,
  989. Encoding::ToWide(valuename).c_str(),
  990. NULL,
  991. &dwType,
  992. (BYTE *)data,
  993. &dwSize) == ERROR_SUCCESS)
  994. {
  995. if (dwType == REG_SZ)
  996. {
  997. value = Encoding::ToNarrow(data);
  998. valueset = true;
  999. }
  1000. else if (dwType == REG_EXPAND_SZ)
  1001. {
  1002. wchar_t expanded[1024];
  1003. DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
  1004. if(ExpandEnvironmentStringsW(data, expanded,
  1005. dwExpandedSize))
  1006. {
  1007. value = Encoding::ToNarrow(expanded);
  1008. valueset = true;
  1009. }
  1010. }
  1011. }
  1012. RegCloseKey(hKey);
  1013. }
  1014. return valueset;
  1015. }
  1016. #else
  1017. bool SystemTools::ReadRegistryValue(const std::string&, std::string &,
  1018. KeyWOW64)
  1019. {
  1020. return false;
  1021. }
  1022. #endif
  1023. // Write a registry value.
  1024. // Example :
  1025. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  1026. // => will set the data of the "default" value of the key
  1027. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  1028. // => will set the data of the "Root" value of the key
  1029. #if defined(_WIN32) && !defined(__CYGWIN__)
  1030. bool SystemTools::WriteRegistryValue(const std::string& key,
  1031. const std::string& value,
  1032. KeyWOW64 view)
  1033. {
  1034. HKEY primaryKey = HKEY_CURRENT_USER;
  1035. std::string second;
  1036. std::string valuename;
  1037. if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
  1038. {
  1039. return false;
  1040. }
  1041. HKEY hKey;
  1042. DWORD dwDummy;
  1043. wchar_t lpClass[] = L"";
  1044. if(RegCreateKeyExW(primaryKey,
  1045. Encoding::ToWide(second).c_str(),
  1046. 0,
  1047. lpClass,
  1048. REG_OPTION_NON_VOLATILE,
  1049. SystemToolsMakeRegistryMode(KEY_WRITE, view),
  1050. NULL,
  1051. &hKey,
  1052. &dwDummy) != ERROR_SUCCESS)
  1053. {
  1054. return false;
  1055. }
  1056. std::wstring wvalue = Encoding::ToWide(value);
  1057. if(RegSetValueExW(hKey,
  1058. Encoding::ToWide(valuename).c_str(),
  1059. 0,
  1060. REG_SZ,
  1061. (CONST BYTE *)wvalue.c_str(),
  1062. (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) == ERROR_SUCCESS)
  1063. {
  1064. return true;
  1065. }
  1066. return false;
  1067. }
  1068. #else
  1069. bool SystemTools::WriteRegistryValue(const std::string&, const std::string&, KeyWOW64)
  1070. {
  1071. return false;
  1072. }
  1073. #endif
  1074. // Delete a registry value.
  1075. // Example :
  1076. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  1077. // => will delete the data of the "default" value of the key
  1078. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  1079. // => will delete the data of the "Root" value of the key
  1080. #if defined(_WIN32) && !defined(__CYGWIN__)
  1081. bool SystemTools::DeleteRegistryValue(const std::string& key, KeyWOW64 view)
  1082. {
  1083. HKEY primaryKey = HKEY_CURRENT_USER;
  1084. std::string second;
  1085. std::string valuename;
  1086. if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
  1087. {
  1088. return false;
  1089. }
  1090. HKEY hKey;
  1091. if(RegOpenKeyExW(primaryKey,
  1092. Encoding::ToWide(second).c_str(),
  1093. 0,
  1094. SystemToolsMakeRegistryMode(KEY_WRITE, view),
  1095. &hKey) != ERROR_SUCCESS)
  1096. {
  1097. return false;
  1098. }
  1099. else
  1100. {
  1101. if(RegDeleteValue(hKey,
  1102. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  1103. {
  1104. RegCloseKey(hKey);
  1105. return true;
  1106. }
  1107. }
  1108. return false;
  1109. }
  1110. #else
  1111. bool SystemTools::DeleteRegistryValue(const std::string&, KeyWOW64)
  1112. {
  1113. return false;
  1114. }
  1115. #endif
  1116. bool SystemTools::SameFile(const std::string& file1, const std::string& file2)
  1117. {
  1118. #ifdef _WIN32
  1119. HANDLE hFile1, hFile2;
  1120. hFile1 = CreateFileW( Encoding::ToWide(file1).c_str(),
  1121. GENERIC_READ,
  1122. FILE_SHARE_READ ,
  1123. NULL,
  1124. OPEN_EXISTING,
  1125. FILE_FLAG_BACKUP_SEMANTICS,
  1126. NULL
  1127. );
  1128. hFile2 = CreateFileW( Encoding::ToWide(file2).c_str(),
  1129. GENERIC_READ,
  1130. FILE_SHARE_READ,
  1131. NULL,
  1132. OPEN_EXISTING,
  1133. FILE_FLAG_BACKUP_SEMANTICS,
  1134. NULL
  1135. );
  1136. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  1137. {
  1138. if(hFile1 != INVALID_HANDLE_VALUE)
  1139. {
  1140. CloseHandle(hFile1);
  1141. }
  1142. if(hFile2 != INVALID_HANDLE_VALUE)
  1143. {
  1144. CloseHandle(hFile2);
  1145. }
  1146. return false;
  1147. }
  1148. BY_HANDLE_FILE_INFORMATION fiBuf1;
  1149. BY_HANDLE_FILE_INFORMATION fiBuf2;
  1150. GetFileInformationByHandle( hFile1, &fiBuf1 );
  1151. GetFileInformationByHandle( hFile2, &fiBuf2 );
  1152. CloseHandle(hFile1);
  1153. CloseHandle(hFile2);
  1154. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  1155. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  1156. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  1157. #else
  1158. struct stat fileStat1, fileStat2;
  1159. if (stat(file1.c_str(), &fileStat1) == 0 && stat(file2.c_str(), &fileStat2) == 0)
  1160. {
  1161. // see if the files are the same file
  1162. // check the device inode and size
  1163. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  1164. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  1165. fileStat2.st_size == fileStat1.st_size
  1166. )
  1167. {
  1168. return true;
  1169. }
  1170. }
  1171. return false;
  1172. #endif
  1173. }
  1174. //----------------------------------------------------------------------------
  1175. bool SystemTools::PathExists(const std::string& path)
  1176. {
  1177. if(path.empty())
  1178. {
  1179. return false;
  1180. }
  1181. #if defined(__CYGWIN__)
  1182. // Convert path to native windows path if possible.
  1183. char winpath[MAX_PATH];
  1184. if(SystemTools::PathCygwinToWin32(path.c_str(), winpath))
  1185. {
  1186. return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
  1187. }
  1188. struct stat st;
  1189. return lstat(path.c_str(), &st) == 0;
  1190. #elif defined(_WIN32)
  1191. return (GetFileAttributesW(
  1192. SystemTools::ConvertToWindowsExtendedPath(path).c_str())
  1193. != INVALID_FILE_ATTRIBUTES);
  1194. #else
  1195. struct stat st;
  1196. return lstat(path.c_str(), &st) == 0;
  1197. #endif
  1198. }
  1199. //----------------------------------------------------------------------------
  1200. bool SystemTools::FileExists(const char* filename)
  1201. {
  1202. if(!filename)
  1203. {
  1204. return false;
  1205. }
  1206. return SystemTools::FileExists(std::string(filename));
  1207. }
  1208. //----------------------------------------------------------------------------
  1209. bool SystemTools::FileExists(const std::string& filename)
  1210. {
  1211. if(filename.empty())
  1212. {
  1213. return false;
  1214. }
  1215. #if defined(__CYGWIN__)
  1216. // Convert filename to native windows path if possible.
  1217. char winpath[MAX_PATH];
  1218. if(SystemTools::PathCygwinToWin32(filename.c_str(), winpath))
  1219. {
  1220. return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
  1221. }
  1222. return access(filename.c_str(), R_OK) == 0;
  1223. #elif defined(_WIN32)
  1224. return (GetFileAttributesW(
  1225. SystemTools::ConvertToWindowsExtendedPath(filename).c_str())
  1226. != INVALID_FILE_ATTRIBUTES);
  1227. #else
  1228. // SCO OpenServer 5.0.7/3.2's command has 711 permission.
  1229. #if defined(_SCO_DS)
  1230. return access(filename.c_str(), F_OK) == 0;
  1231. #else
  1232. return access(filename.c_str(), R_OK) == 0;
  1233. #endif
  1234. #endif
  1235. }
  1236. //----------------------------------------------------------------------------
  1237. bool SystemTools::FileExists(const char* filename, bool isFile)
  1238. {
  1239. if(!filename)
  1240. {
  1241. return false;
  1242. }
  1243. return SystemTools::FileExists(std::string(filename), isFile);
  1244. }
  1245. //----------------------------------------------------------------------------
  1246. bool SystemTools::FileExists(const std::string& filename, bool isFile)
  1247. {
  1248. if(SystemTools::FileExists(filename))
  1249. {
  1250. // If isFile is set return not FileIsDirectory,
  1251. // so this will only be true if it is a file
  1252. return !isFile || !SystemTools::FileIsDirectory(filename);
  1253. }
  1254. return false;
  1255. }
  1256. //----------------------------------------------------------------------------
  1257. bool SystemTools::TestFileAccess(const char* filename,
  1258. TestFilePermissions permissions)
  1259. {
  1260. if(!filename)
  1261. {
  1262. return false;
  1263. }
  1264. return SystemTools::TestFileAccess(std::string(filename),
  1265. permissions);
  1266. }
  1267. //----------------------------------------------------------------------------
  1268. bool SystemTools::TestFileAccess(const std::string& filename,
  1269. TestFilePermissions permissions)
  1270. {
  1271. if(filename.empty())
  1272. {
  1273. return false;
  1274. }
  1275. #if defined(_WIN32) && !defined(__CYGWIN__)
  1276. // If execute set, change to read permission (all files on Windows
  1277. // are executable if they are readable). The CRT will always fail
  1278. // if you pass an execute bit.
  1279. if(permissions & TEST_FILE_EXECUTE)
  1280. {
  1281. permissions &= ~TEST_FILE_EXECUTE;
  1282. permissions |= TEST_FILE_READ;
  1283. }
  1284. return _waccess(
  1285. SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
  1286. permissions) == 0;
  1287. #else
  1288. return access(filename.c_str(), permissions) == 0;
  1289. #endif
  1290. }
  1291. //----------------------------------------------------------------------------
  1292. #ifdef __CYGWIN__
  1293. bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
  1294. {
  1295. SystemToolsTranslationMap::iterator i =
  1296. SystemTools::Cyg2Win32Map->find(path);
  1297. if (i != SystemTools::Cyg2Win32Map->end())
  1298. {
  1299. strncpy(win32_path, i->second.c_str(), MAX_PATH);
  1300. }
  1301. else
  1302. {
  1303. if(cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) != 0)
  1304. {
  1305. win32_path[0] = 0;
  1306. }
  1307. SystemToolsTranslationMap::value_type entry(path, win32_path);
  1308. SystemTools::Cyg2Win32Map->insert(entry);
  1309. }
  1310. return win32_path[0] != 0;
  1311. }
  1312. #endif
  1313. bool SystemTools::Touch(const std::string& filename, bool create)
  1314. {
  1315. if (!SystemTools::FileExists(filename))
  1316. {
  1317. if(create)
  1318. {
  1319. FILE* file = Fopen(filename, "a+b");
  1320. if(file)
  1321. {
  1322. fclose(file);
  1323. return true;
  1324. }
  1325. return false;
  1326. }
  1327. else
  1328. {
  1329. return true;
  1330. }
  1331. }
  1332. #if defined(_WIN32) && !defined(__CYGWIN__)
  1333. HANDLE h = CreateFileW(
  1334. SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
  1335. FILE_WRITE_ATTRIBUTES,
  1336. FILE_SHARE_WRITE, 0, OPEN_EXISTING,
  1337. FILE_FLAG_BACKUP_SEMANTICS, 0);
  1338. if(!h)
  1339. {
  1340. return false;
  1341. }
  1342. FILETIME mtime;
  1343. GetSystemTimeAsFileTime(&mtime);
  1344. if(!SetFileTime(h, 0, 0, &mtime))
  1345. {
  1346. CloseHandle(h);
  1347. return false;
  1348. }
  1349. CloseHandle(h);
  1350. #elif KWSYS_CXX_HAS_UTIMENSAT
  1351. struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
  1352. if(utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0)
  1353. {
  1354. return false;
  1355. }
  1356. #else
  1357. struct stat st;
  1358. if(stat(filename.c_str(), &st) < 0)
  1359. {
  1360. return false;
  1361. }
  1362. struct timeval mtime;
  1363. gettimeofday(&mtime, 0);
  1364. # if KWSYS_CXX_HAS_UTIMES
  1365. struct timeval atime;
  1366. # if KWSYS_CXX_STAT_HAS_ST_MTIM
  1367. atime.tv_sec = st.st_atim.tv_sec;
  1368. atime.tv_usec = st.st_atim.tv_nsec/1000;
  1369. # elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
  1370. atime.tv_sec = st.st_atimespec.tv_sec;
  1371. atime.tv_usec = st.st_atimespec.tv_nsec/1000;
  1372. # else
  1373. atime.tv_sec = st.st_atime;
  1374. atime.tv_usec = 0;
  1375. # endif
  1376. struct timeval times[2] = { atime, mtime };
  1377. if(utimes(filename.c_str(), times) < 0)
  1378. {
  1379. return false;
  1380. }
  1381. # else
  1382. struct utimbuf times = {st.st_atime, mtime.tv_sec};
  1383. if(utime(filename.c_str(), &times) < 0)
  1384. {
  1385. return false;
  1386. }
  1387. # endif
  1388. #endif
  1389. return true;
  1390. }
  1391. bool SystemTools::FileTimeCompare(const std::string& f1,
  1392. const std::string& f2,
  1393. int* result)
  1394. {
  1395. // Default to same time.
  1396. *result = 0;
  1397. #if !defined(_WIN32) || defined(__CYGWIN__)
  1398. // POSIX version. Use stat function to get file modification time.
  1399. struct stat s1;
  1400. if(stat(f1.c_str(), &s1) != 0)
  1401. {
  1402. return false;
  1403. }
  1404. struct stat s2;
  1405. if(stat(f2.c_str(), &s2) != 0)
  1406. {
  1407. return false;
  1408. }
  1409. # if KWSYS_CXX_STAT_HAS_ST_MTIM
  1410. // Compare using nanosecond resolution.
  1411. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  1412. {
  1413. *result = -1;
  1414. }
  1415. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  1416. {
  1417. *result = 1;
  1418. }
  1419. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  1420. {
  1421. *result = -1;
  1422. }
  1423. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  1424. {
  1425. *result = 1;
  1426. }
  1427. # elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
  1428. // Compare using nanosecond resolution.
  1429. if(s1.st_mtimespec.tv_sec < s2.st_mtimespec.tv_sec)
  1430. {
  1431. *result = -1;
  1432. }
  1433. else if(s1.st_mtimespec.tv_sec > s2.st_mtimespec.tv_sec)
  1434. {
  1435. *result = 1;
  1436. }
  1437. else if(s1.st_mtimespec.tv_nsec < s2.st_mtimespec.tv_nsec)
  1438. {
  1439. *result = -1;
  1440. }
  1441. else if(s1.st_mtimespec.tv_nsec > s2.st_mtimespec.tv_nsec)
  1442. {
  1443. *result = 1;
  1444. }
  1445. # else
  1446. // Compare using 1 second resolution.
  1447. if(s1.st_mtime < s2.st_mtime)
  1448. {
  1449. *result = -1;
  1450. }
  1451. else if(s1.st_mtime > s2.st_mtime)
  1452. {
  1453. *result = 1;
  1454. }
  1455. # endif
  1456. #else
  1457. // Windows version. Get the modification time from extended file attributes.
  1458. WIN32_FILE_ATTRIBUTE_DATA f1d;
  1459. WIN32_FILE_ATTRIBUTE_DATA f2d;
  1460. if(!GetFileAttributesExW(
  1461. SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
  1462. GetFileExInfoStandard, &f1d))
  1463. {
  1464. return false;
  1465. }
  1466. if(!GetFileAttributesExW(
  1467. SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
  1468. GetFileExInfoStandard, &f2d))
  1469. {
  1470. return false;
  1471. }
  1472. // Compare the file times using resolution provided by system call.
  1473. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  1474. #endif
  1475. return true;
  1476. }
  1477. // Return a capitalized string (i.e the first letter is uppercased, all other
  1478. // are lowercased)
  1479. std::string SystemTools::Capitalized(const std::string& s)
  1480. {
  1481. std::string n;
  1482. if(s.empty())
  1483. {
  1484. return n;
  1485. }
  1486. n.resize(s.size());
  1487. n[0] = static_cast<std::string::value_type>(toupper(s[0]));
  1488. for (size_t i = 1; i < s.size(); i++)
  1489. {
  1490. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  1491. }
  1492. return n;
  1493. }
  1494. // Return capitalized words
  1495. std::string SystemTools::CapitalizedWords(const std::string& s)
  1496. {
  1497. std::string n(s);
  1498. for (size_t i = 0; i < s.size(); i++)
  1499. {
  1500. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  1501. // MS has an assert that will fail if s[i] < 0; setting
  1502. // LC_CTYPE using setlocale() does *not* help. Painful.
  1503. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1504. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1505. #else
  1506. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1507. #endif
  1508. {
  1509. n[i] = static_cast<std::string::value_type>(toupper(s[i]));
  1510. }
  1511. }
  1512. return n;
  1513. }
  1514. // Return uncapitalized words
  1515. std::string SystemTools::UnCapitalizedWords(const std::string& s)
  1516. {
  1517. std::string n(s);
  1518. for (size_t i = 0; i < s.size(); i++)
  1519. {
  1520. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  1521. // MS has an assert that will fail if s[i] < 0; setting
  1522. // LC_CTYPE using setlocale() does *not* help. Painful.
  1523. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1524. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1525. #else
  1526. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1527. #endif
  1528. {
  1529. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  1530. }
  1531. }
  1532. return n;
  1533. }
  1534. // only works for words with at least two letters
  1535. std::string SystemTools::AddSpaceBetweenCapitalizedWords(
  1536. const std::string& s)
  1537. {
  1538. std::string n;
  1539. if (!s.empty())
  1540. {
  1541. n.reserve(s.size());
  1542. n += s[0];
  1543. for (size_t i = 1; i < s.size(); i++)
  1544. {
  1545. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  1546. {
  1547. n += ' ';
  1548. }
  1549. n += s[i];
  1550. }
  1551. }
  1552. return n;
  1553. }
  1554. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  1555. {
  1556. if (!str1)
  1557. {
  1558. return SystemTools::DuplicateString(str2);
  1559. }
  1560. if (!str2)
  1561. {
  1562. return SystemTools::DuplicateString(str1);
  1563. }
  1564. size_t len1 = strlen(str1);
  1565. char *newstr = new char[len1 + strlen(str2) + 1];
  1566. if (!newstr)
  1567. {
  1568. return 0;
  1569. }
  1570. strcpy(newstr, str1);
  1571. strcat(newstr + len1, str2);
  1572. return newstr;
  1573. }
  1574. char* SystemTools::AppendStrings(
  1575. const char* str1, const char* str2, const char* str3)
  1576. {
  1577. if (!str1)
  1578. {
  1579. return SystemTools::AppendStrings(str2, str3);
  1580. }
  1581. if (!str2)
  1582. {
  1583. return SystemTools::AppendStrings(str1, str3);
  1584. }
  1585. if (!str3)
  1586. {
  1587. return SystemTools::AppendStrings(str1, str2);
  1588. }
  1589. size_t len1 = strlen(str1), len2 = strlen(str2);
  1590. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  1591. if (!newstr)
  1592. {
  1593. return 0;
  1594. }
  1595. strcpy(newstr, str1);
  1596. strcat(newstr + len1, str2);
  1597. strcat(newstr + len1 + len2, str3);
  1598. return newstr;
  1599. }
  1600. // Return a lower case string
  1601. std::string SystemTools::LowerCase(const std::string& s)
  1602. {
  1603. std::string n;
  1604. n.resize(s.size());
  1605. for (size_t i = 0; i < s.size(); i++)
  1606. {
  1607. n[i] = static_cast<std::string::value_type>(tolower(s[i]));
  1608. }
  1609. return n;
  1610. }
  1611. // Return a lower case string
  1612. std::string SystemTools::UpperCase(const std::string& s)
  1613. {
  1614. std::string n;
  1615. n.resize(s.size());
  1616. for (size_t i = 0; i < s.size(); i++)
  1617. {
  1618. n[i] = static_cast<std::string::value_type>(toupper(s[i]));
  1619. }
  1620. return n;
  1621. }
  1622. // Count char in string
  1623. size_t SystemTools::CountChar(const char* str, char c)
  1624. {
  1625. size_t count = 0;
  1626. if (str)
  1627. {
  1628. while (*str)
  1629. {
  1630. if (*str == c)
  1631. {
  1632. ++count;
  1633. }
  1634. ++str;
  1635. }
  1636. }
  1637. return count;
  1638. }
  1639. // Remove chars in string
  1640. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  1641. {
  1642. if (!str)
  1643. {
  1644. return NULL;
  1645. }
  1646. char *clean_str = new char [strlen(str) + 1];
  1647. char *ptr = clean_str;
  1648. while (*str)
  1649. {
  1650. const char *str2 = toremove;
  1651. while (*str2 && *str != *str2)
  1652. {
  1653. ++str2;
  1654. }
  1655. if (!*str2)
  1656. {
  1657. *ptr++ = *str;
  1658. }
  1659. ++str;
  1660. }
  1661. *ptr = '\0';
  1662. return clean_str;
  1663. }
  1664. // Remove chars in string
  1665. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  1666. {
  1667. if (!str)
  1668. {
  1669. return 0;
  1670. }
  1671. char *clean_str = new char [strlen(str) + 1];
  1672. char *ptr = clean_str;
  1673. while (*str)
  1674. {
  1675. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
  1676. {
  1677. *ptr++ = *str;
  1678. }
  1679. ++str;
  1680. }
  1681. *ptr = '\0';
  1682. return clean_str;
  1683. }
  1684. // Replace chars in string
  1685. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  1686. {
  1687. if (str)
  1688. {
  1689. char *ptr = str;
  1690. while (*ptr)
  1691. {
  1692. const char *ptr2 = toreplace;
  1693. while (*ptr2)
  1694. {
  1695. if (*ptr == *ptr2)
  1696. {
  1697. *ptr = replacement;
  1698. }
  1699. ++ptr2;
  1700. }
  1701. ++ptr;
  1702. }
  1703. }
  1704. return str;
  1705. }
  1706. // Returns if string starts with another string
  1707. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  1708. {
  1709. if (!str1 || !str2)
  1710. {
  1711. return false;
  1712. }
  1713. size_t len1 = strlen(str1), len2 = strlen(str2);
  1714. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  1715. }
  1716. // Returns if string starts with another string
  1717. bool SystemTools::StringStartsWith(const std::string& str1, const char* str2)
  1718. {
  1719. if (!str2)
  1720. {
  1721. return false;
  1722. }
  1723. size_t len1 = str1.size(), len2 = strlen(str2);
  1724. return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false;
  1725. }
  1726. // Returns if string ends with another string
  1727. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  1728. {
  1729. if (!str1 || !str2)
  1730. {
  1731. return false;
  1732. }
  1733. size_t len1 = strlen(str1), len2 = strlen(str2);
  1734. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  1735. }
  1736. // Returns if string ends with another string
  1737. bool SystemTools::StringEndsWith(const std::string& str1, const char* str2)
  1738. {
  1739. if (!str2)
  1740. {
  1741. return false;
  1742. }
  1743. size_t len1 = str1.size(), len2 = strlen(str2);
  1744. return len1 >= len2 && !strncmp(str1.c_str() + (len1 - len2), str2, len2) ? true : false;
  1745. }
  1746. // Returns a pointer to the last occurence of str2 in str1
  1747. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  1748. {
  1749. if (!str1 || !str2)
  1750. {
  1751. return NULL;
  1752. }
  1753. size_t len1 = strlen(str1), len2 = strlen(str2);
  1754. if (len1 >= len2)
  1755. {
  1756. const char *ptr = str1 + len1 - len2;
  1757. do
  1758. {
  1759. if (!strncmp(ptr, str2, len2))
  1760. {
  1761. return ptr;
  1762. }
  1763. } while (ptr-- != str1);
  1764. }
  1765. return NULL;
  1766. }
  1767. // Duplicate string
  1768. char* SystemTools::DuplicateString(const char* str)
  1769. {
  1770. if (str)
  1771. {
  1772. char *newstr = new char [strlen(str) + 1];
  1773. return strcpy(newstr, str);
  1774. }
  1775. return NULL;
  1776. }
  1777. // Return a cropped string
  1778. std::string SystemTools::CropString(const std::string& s,
  1779. size_t max_len)
  1780. {
  1781. if (!s.size() || max_len == 0 || max_len >= s.size())
  1782. {
  1783. return s;
  1784. }
  1785. std::string n;
  1786. n.reserve(max_len);
  1787. size_t middle = max_len / 2;
  1788. n += s.substr(0, middle);
  1789. n += s.substr(s.size() - (max_len - middle), std::string::npos);
  1790. if (max_len > 2)
  1791. {
  1792. n[middle] = '.';
  1793. if (max_len > 3)
  1794. {
  1795. n[middle - 1] = '.';
  1796. if (max_len > 4)
  1797. {
  1798. n[middle + 1] = '.';
  1799. }
  1800. }
  1801. }
  1802. return n;
  1803. }
  1804. //----------------------------------------------------------------------------
  1805. std::vector<kwsys::String> SystemTools::SplitString(const std::string& p, char sep, bool isPath)
  1806. {
  1807. std::string path = p;
  1808. std::vector<kwsys::String> paths;
  1809. if(path.empty())
  1810. {
  1811. return paths;
  1812. }
  1813. if(isPath && path[0] == '/')
  1814. {
  1815. path.erase(path.begin());
  1816. paths.push_back("/");
  1817. }
  1818. std::string::size_type pos1 = 0;
  1819. std::string::size_type pos2 = path.find(sep, pos1+1);
  1820. while(pos2 != std::string::npos)
  1821. {
  1822. paths.push_back(path.substr(pos1, pos2-pos1));
  1823. pos1 = pos2+1;
  1824. pos2 = path.find(sep, pos1+1);
  1825. }
  1826. paths.push_back(path.substr(pos1, pos2-pos1));
  1827. return paths;
  1828. }
  1829. //----------------------------------------------------------------------------
  1830. int SystemTools::EstimateFormatLength(const char *format, va_list ap)
  1831. {
  1832. if (!format)
  1833. {
  1834. return 0;
  1835. }
  1836. // Quick-hack attempt at estimating the length of the string.
  1837. // Should never under-estimate.
  1838. // Start with the length of the format string itself.
  1839. size_t length = strlen(format);
  1840. // Increase the length for every argument in the format.
  1841. const char* cur = format;
  1842. while(*cur)
  1843. {
  1844. if(*cur++ == '%')
  1845. {
  1846. // Skip "%%" since it doesn't correspond to a va_arg.
  1847. if(*cur != '%')
  1848. {
  1849. while(!int(isalpha(*cur)))
  1850. {
  1851. ++cur;
  1852. }
  1853. switch (*cur)
  1854. {
  1855. case 's':
  1856. {
  1857. // Check the length of the string.
  1858. char* s = va_arg(ap, char*);
  1859. if(s)
  1860. {
  1861. length += strlen(s);
  1862. }
  1863. } break;
  1864. case 'e':
  1865. case 'f':
  1866. case 'g':
  1867. {
  1868. // Assume the argument contributes no more than 64 characters.
  1869. length += 64;
  1870. // Eat the argument.
  1871. static_cast<void>(va_arg(ap, double));
  1872. } break;
  1873. default:
  1874. {
  1875. // Assume the argument contributes no more than 64 characters.
  1876. length += 64;
  1877. // Eat the argument.
  1878. static_cast<void>(va_arg(ap, int));
  1879. } break;
  1880. }
  1881. }
  1882. // Move past the characters just tested.
  1883. ++cur;
  1884. }
  1885. }
  1886. return static_cast<int>(length);
  1887. }
  1888. std::string SystemTools::EscapeChars(
  1889. const char *str,
  1890. const char *chars_to_escape,
  1891. char escape_char)
  1892. {
  1893. std::string n;
  1894. if (str)
  1895. {
  1896. if (!chars_to_escape || !*chars_to_escape)
  1897. {
  1898. n.append(str);
  1899. }
  1900. else
  1901. {
  1902. n.reserve(strlen(str));
  1903. while (*str)
  1904. {
  1905. const char *ptr = chars_to_escape;
  1906. while (*ptr)
  1907. {
  1908. if (*str == *ptr)
  1909. {
  1910. n += escape_char;
  1911. break;
  1912. }
  1913. ++ptr;
  1914. }
  1915. n += *str;
  1916. ++str;
  1917. }
  1918. }
  1919. }
  1920. return n;
  1921. }
  1922. #ifdef __VMS
  1923. static void ConvertVMSToUnix(std::string& path)
  1924. {
  1925. std::string::size_type rootEnd = path.find(":[");
  1926. std::string::size_type pathEnd = path.find("]");
  1927. if(rootEnd != path.npos)
  1928. {
  1929. std::string root = path.substr(0, rootEnd);
  1930. std::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
  1931. const char* pathCString = pathPart.c_str();
  1932. const char* pos0 = pathCString;
  1933. for (std::string::size_type pos = 0; *pos0; ++ pos )
  1934. {
  1935. if ( *pos0 == '.' )
  1936. {
  1937. pathPart[pos] = '/';
  1938. }
  1939. pos0 ++;
  1940. }
  1941. path = "/"+ root + "/" + pathPart;
  1942. }
  1943. }
  1944. #endif
  1945. // convert windows slashes to unix slashes
  1946. void SystemTools::ConvertToUnixSlashes(std::string& path)
  1947. {
  1948. const char* pathCString = path.c_str();
  1949. bool hasDoubleSlash = false;
  1950. #ifdef __VMS
  1951. ConvertVMSToUnix(path);
  1952. #else
  1953. const char* pos0 = pathCString;
  1954. const char* pos1 = pathCString+1;
  1955. for (std::string::size_type pos = 0; *pos0; ++ pos )
  1956. {
  1957. // make sure we don't convert an escaped space to a unix slash
  1958. if ( *pos0 == '\\' && *pos1 != ' ' )
  1959. {
  1960. path[pos] = '/';
  1961. }
  1962. // Also, reuse the loop to check for slash followed by another slash
  1963. if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
  1964. {
  1965. #ifdef _WIN32
  1966. // However, on windows if the first characters are both slashes,
  1967. // then keep them that way, so that network paths can be handled.
  1968. if ( pos > 0)
  1969. {
  1970. hasDoubleSlash = true;
  1971. }
  1972. #else
  1973. hasDoubleSlash = true;
  1974. #endif
  1975. }
  1976. pos0 ++;
  1977. pos1 ++;
  1978. }
  1979. if ( hasDoubleSlash )
  1980. {
  1981. SystemTools::ReplaceString(path, "//", "/");
  1982. }
  1983. #endif
  1984. // remove any trailing slash
  1985. if(!path.empty())
  1986. {
  1987. // if there is a tilda ~ then replace it with HOME
  1988. pathCString = path.c_str();
  1989. if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
  1990. {
  1991. std::string homeEnv;
  1992. if (SystemTools::GetEnv("HOME", homeEnv))
  1993. {
  1994. path.replace(0,1,homeEnv);
  1995. }
  1996. }
  1997. #ifdef HAVE_GETPWNAM
  1998. else if(pathCString[0] == '~')
  1999. {
  2000. std::string::size_type idx = path.find_first_of("/\0");
  2001. std::string user = path.substr(1, idx-1);
  2002. passwd* pw = getpwnam(user.c_str());
  2003. if(pw)
  2004. {
  2005. path.replace(0, idx, pw->pw_dir);
  2006. }
  2007. }
  2008. #endif
  2009. // remove trailing slash if the path is more than
  2010. // a single /
  2011. pathCString = path.c_str();
  2012. size_t size = path.size();
  2013. if(size > 1 && *path.rbegin() == '/')
  2014. {
  2015. // if it is c:/ then do not remove the trailing slash
  2016. if(!((size == 3 && pathCString[1] == ':')))
  2017. {
  2018. path.resize(size - 1);
  2019. }
  2020. }
  2021. }
  2022. }
  2023. #ifdef _WIN32
  2024. // Convert local paths to UNC style paths
  2025. std::wstring
  2026. SystemTools::ConvertToWindowsExtendedPath(const std::string &source)
  2027. {
  2028. std::wstring wsource = Encoding::ToWide(source);
  2029. // Resolve any relative paths
  2030. DWORD wfull_len;
  2031. /* The +3 is a workaround for a bug in some versions of GetFullPathNameW that
  2032. * won't return a large enough buffer size if the input is too small */
  2033. wfull_len = GetFullPathNameW(wsource.c_str(), 0, NULL, NULL) + 3;
  2034. std::vector<wchar_t> wfull(wfull_len);
  2035. GetFullPathNameW(wsource.c_str(), wfull_len, &wfull[0], NULL);
  2036. /* This should get the correct size without any extra padding from the
  2037. * previous size workaround. */
  2038. wfull_len = static_cast<DWORD>(wcslen(&wfull[0]));
  2039. if(wfull_len >= 2 && isalpha(wfull[0]) && wfull[1] == L':')
  2040. { /* C:\Foo\bar\FooBar.txt */
  2041. return L"\\\\?\\" + std::wstring(&wfull[0]);
  2042. }
  2043. else if(wfull_len >= 2 && wfull[0] == L'\\' && wfull[1] == L'\\')
  2044. { /* Starts with \\ */
  2045. if(wfull_len >= 4 && wfull[2] == L'?' && wfull[3] == L'\\')
  2046. { /* Starts with \\?\ */
  2047. if(wfull_len >= 8 && wfull[4] == L'U' && wfull[5] == L'N' &&
  2048. wfull[6] == L'C' && wfull[7] == L'\\')
  2049. { /* \\?\UNC\Foo\bar\FooBar.txt */
  2050. return std::wstring(&wfull[0]);
  2051. }
  2052. else if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
  2053. { /* \\?\C:\Foo\bar\FooBar.txt */
  2054. return std::wstring(&wfull[0]);
  2055. }
  2056. else if(wfull_len >= 5)
  2057. { /* \\?\Foo\bar\FooBar.txt */
  2058. return L"\\\\?\\UNC\\" + std::wstring(&wfull[4]);
  2059. }
  2060. }
  2061. else if(wfull_len >= 4 && wfull[2] == L'.' && wfull[3] == L'\\')
  2062. { /* Starts with \\.\ a device name */
  2063. if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
  2064. { /* \\.\C:\Foo\bar\FooBar.txt */
  2065. return L"\\\\?\\" + std::wstring(&wfull[4]);
  2066. }
  2067. else if(wfull_len >= 5)
  2068. { /* \\.\Foo\bar\ Device name is left unchanged */
  2069. return std::wstring(&wfull[0]);
  2070. }
  2071. }
  2072. else if(wfull_len >= 3)
  2073. { /* \\Foo\bar\FooBar.txt */
  2074. return L"\\\\?\\UNC\\" + std::wstring(&wfull[2]);
  2075. }
  2076. }
  2077. // If this case has been reached, then the path is invalid. Leave it
  2078. // unchanged
  2079. return Encoding::ToWide(source);
  2080. }
  2081. #endif
  2082. // change // to /, and escape any spaces in the path
  2083. std::string SystemTools::ConvertToUnixOutputPath(const std::string& path)
  2084. {
  2085. std::string ret = path;
  2086. // remove // except at the beginning might be a cygwin drive
  2087. std::string::size_type pos=1;
  2088. while((pos = ret.find("//", pos)) != std::string::npos)
  2089. {
  2090. ret.erase(pos, 1);
  2091. }
  2092. // escape spaces and () in the path
  2093. if(ret.find_first_of(" ") != std::string::npos)
  2094. {
  2095. std::string result = "";
  2096. char lastch = 1;
  2097. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  2098. {
  2099. // if it is already escaped then don't try to escape it again
  2100. if((*ch == ' ') && lastch != '\\')
  2101. {
  2102. result += '\\';
  2103. }
  2104. result += *ch;
  2105. lastch = *ch;
  2106. }
  2107. ret = result;
  2108. }
  2109. return ret;
  2110. }
  2111. std::string SystemTools::ConvertToOutputPath(const std::string& path)
  2112. {
  2113. #if defined(_WIN32) && !defined(__CYGWIN__)
  2114. return SystemTools::ConvertToWindowsOutputPath(path);
  2115. #else
  2116. return SystemTools::ConvertToUnixOutputPath(path);
  2117. #endif
  2118. }
  2119. // remove double slashes not at the start
  2120. std::string SystemTools::ConvertToWindowsOutputPath(const std::string& path)
  2121. {
  2122. std::string ret;
  2123. // make it big enough for all of path and double quotes
  2124. ret.reserve(path.size()+3);
  2125. // put path into the string
  2126. ret = path;
  2127. std::string::size_type pos = 0;
  2128. // first convert all of the slashes
  2129. while((pos = ret.find('/', pos)) != std::string::npos)
  2130. {
  2131. ret[pos] = '\\';
  2132. pos++;
  2133. }
  2134. // check for really small paths
  2135. if(ret.size() < 2)
  2136. {
  2137. return ret;
  2138. }
  2139. // now clean up a bit and remove double slashes
  2140. // Only if it is not the first position in the path which is a network
  2141. // path on windows
  2142. pos = 1; // start at position 1
  2143. if(ret[0] == '\"')
  2144. {
  2145. pos = 2; // if the string is already quoted then start at 2
  2146. if(ret.size() < 3)
  2147. {
  2148. return ret;
  2149. }
  2150. }
  2151. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  2152. {
  2153. ret.erase(pos, 1);
  2154. }
  2155. // now double quote the path if it has spaces in it
  2156. // and is not already double quoted
  2157. if(ret.find(' ') != std::string::npos
  2158. && ret[0] != '\"')
  2159. {
  2160. ret.insert(static_cast<std::string::size_type>(0),
  2161. static_cast<std::string::size_type>(1), '\"');
  2162. ret.append(1, '\"');
  2163. }
  2164. return ret;
  2165. }
  2166. bool SystemTools::CopyFileIfDifferent(const std::string& source,
  2167. const std::string& destination)
  2168. {
  2169. // special check for a destination that is a directory
  2170. // FilesDiffer does not handle file to directory compare
  2171. if(SystemTools::FileIsDirectory(destination))
  2172. {
  2173. std::string new_destination = destination;
  2174. SystemTools::ConvertToUnixSlashes(new_destination);
  2175. new_destination += '/';
  2176. std::string source_name = source;
  2177. new_destination += SystemTools::GetFilenameName(source_name);
  2178. if(SystemTools::FilesDiffer(source, new_destination))
  2179. {
  2180. return SystemTools::CopyFileAlways(source, destination);
  2181. }
  2182. else
  2183. {
  2184. // the files are the same so the copy is done return
  2185. // true
  2186. return true;
  2187. }
  2188. }
  2189. // source and destination are files so do a copy if they
  2190. // are different
  2191. if(SystemTools::FilesDiffer(source, destination))
  2192. {
  2193. return SystemTools::CopyFileAlways(source, destination);
  2194. }
  2195. // at this point the files must be the same so return true
  2196. return true;
  2197. }
  2198. #define KWSYS_ST_BUFFER 4096
  2199. bool SystemTools::FilesDiffer(const std::string& source,
  2200. const std::string& destination)
  2201. {
  2202. #if defined(_WIN32)
  2203. WIN32_FILE_ATTRIBUTE_DATA statSource;
  2204. if (GetFileAttributesExW(
  2205. SystemTools::ConvertToWindowsExtendedPath(source).c_str(),
  2206. GetFileExInfoStandard,
  2207. &statSource) == 0)
  2208. {
  2209. return true;
  2210. }
  2211. WIN32_FILE_ATTRIBUTE_DATA statDestination;
  2212. if (GetFileAttributesExW(
  2213. SystemTools::ConvertToWindowsExtendedPath(destination).c_str(),
  2214. GetFileExInfoStandard,
  2215. &statDestination) == 0)
  2216. {
  2217. return true;
  2218. }
  2219. if(statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
  2220. statSource.nFileSizeLow != statDestination.nFileSizeLow)
  2221. {
  2222. return true;
  2223. }
  2224. if(statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0)
  2225. {
  2226. return false;
  2227. }
  2228. off_t nleft = ((__int64)statSource.nFileSizeHigh << 32) +
  2229. statSource.nFileSizeLow;
  2230. #else
  2231. struct stat statSource;
  2232. if (stat(source.c_str(), &statSource) != 0)
  2233. {
  2234. return true;
  2235. }
  2236. struct stat statDestination;
  2237. if (stat(destination.c_str(), &statDestination) != 0)
  2238. {
  2239. return true;
  2240. }
  2241. if(statSource.st_size != statDestination.st_size)
  2242. {
  2243. return true;
  2244. }
  2245. if(statSource.st_size == 0)
  2246. {
  2247. return false;
  2248. }
  2249. off_t nleft = statSource.st_size;
  2250. #endif
  2251. #if defined(_WIN32)
  2252. kwsys::ifstream finSource(source.c_str(),
  2253. (std::ios::binary |
  2254. std::ios::in));
  2255. kwsys::ifstream finDestination(destination.c_str(),
  2256. (std::ios::binary |
  2257. std::ios::in));
  2258. #else
  2259. kwsys::ifstream finSource(source.c_str());
  2260. kwsys::ifstream finDestination(destination.c_str());
  2261. #endif
  2262. if(!finSource || !finDestination)
  2263. {
  2264. return true;
  2265. }
  2266. // Compare the files a block at a time.
  2267. char source_buf[KWSYS_ST_BUFFER];
  2268. char dest_buf[KWSYS_ST_BUFFER];
  2269. while(nleft > 0)
  2270. {
  2271. // Read a block from each file.
  2272. std::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<std::streamsize>(nleft);
  2273. finSource.read(source_buf, nnext);
  2274. finDestination.read(dest_buf, nnext);
  2275. // If either failed to read assume they are different.
  2276. if(static_cast<std::streamsize>(finSource.gcount()) != nnext ||
  2277. static_cast<std::streamsize>(finDestination.gcount()) != nnext)
  2278. {
  2279. return true;
  2280. }
  2281. // If this block differs the file differs.
  2282. if(memcmp(static_cast<const void*>(source_buf),
  2283. static_cast<const void*>(dest_buf),
  2284. static_cast<size_t>(nnext)) != 0)
  2285. {
  2286. return true;
  2287. }
  2288. // Update the byte count remaining.
  2289. nleft -= nnext;
  2290. }
  2291. // No differences found.
  2292. return false;
  2293. }
  2294. //----------------------------------------------------------------------------
  2295. /**
  2296. * Copy a file named by "source" to the file named by "destination".
  2297. */
  2298. bool SystemTools::CopyFileAlways(const std::string& source, const std::string& destination)
  2299. {
  2300. // If files are the same do not copy
  2301. if ( SystemTools::SameFile(source, destination) )
  2302. {
  2303. return true;
  2304. }
  2305. mode_t perm = 0;
  2306. bool perms = SystemTools::GetPermissions(source, perm);
  2307. std::string real_destination = destination;
  2308. if(SystemTools::FileIsDirectory(source))
  2309. {
  2310. SystemTools::MakeDirectory(destination);
  2311. }
  2312. else
  2313. {
  2314. const int bufferSize = 4096;
  2315. char buffer[bufferSize];
  2316. // If destination is a directory, try to create a file with the same
  2317. // name as the source in that directory.
  2318. std::string destination_dir;
  2319. if(SystemTools::FileIsDirectory(destination))
  2320. {
  2321. destination_dir = real_destination;
  2322. SystemTools::ConvertToUnixSlashes(real_destination);
  2323. real_destination += '/';
  2324. std::string source_name = source;
  2325. real_destination += SystemTools::GetFilenameName(source_name);
  2326. }
  2327. else
  2328. {
  2329. destination_dir = SystemTools::GetFilenamePath(destination);
  2330. }
  2331. // Create destination directory
  2332. SystemTools::MakeDirectory(destination_dir);
  2333. // Open files
  2334. #if defined(_WIN32)
  2335. kwsys::ifstream fin(Encoding::ToNarrow(
  2336. SystemTools::ConvertToWindowsExtendedPath(source)).c_str(),
  2337. std::ios::in | std::ios::binary);
  2338. #else
  2339. kwsys::ifstream fin(source.c_str(),
  2340. std::ios::in | std::ios::binary);
  2341. #endif
  2342. if(!fin)
  2343. {
  2344. return false;
  2345. }
  2346. // try and remove the destination file so that read only destination files
  2347. // can be written to.
  2348. // If the remove fails continue so that files in read only directories
  2349. // that do not allow file removal can be modified.
  2350. SystemTools::RemoveFile(real_destination);
  2351. #if defined(_WIN32)
  2352. kwsys::ofstream fout(Encoding::ToNarrow(
  2353. SystemTools::ConvertToWindowsExtendedPath(real_destination)).c_str(),
  2354. std::ios::out | std::ios::trunc | std::ios::binary);
  2355. #else
  2356. kwsys::ofstream fout(real_destination.c_str(),
  2357. std::ios::out | std::ios::trunc | std::ios::binary);
  2358. #endif
  2359. if(!fout)
  2360. {
  2361. return false;
  2362. }
  2363. // This copy loop is very sensitive on certain platforms with
  2364. // slightly broken stream libraries (like HPUX). Normally, it is
  2365. // incorrect to not check the error condition on the fin.read()
  2366. // before using the data, but the fin.gcount() will be zero if an
  2367. // error occurred. Therefore, the loop should be safe everywhere.
  2368. while(fin)
  2369. {
  2370. fin.read(buffer, bufferSize);
  2371. if(fin.gcount())
  2372. {
  2373. fout.write(buffer, fin.gcount());
  2374. }
  2375. else
  2376. {
  2377. break;
  2378. }
  2379. }
  2380. // Make sure the operating system has finished writing the file
  2381. // before closing it. This will ensure the file is finished before
  2382. // the check below.
  2383. fout.flush();
  2384. fin.close();
  2385. fout.close();
  2386. if(!fout)
  2387. {
  2388. return false;
  2389. }
  2390. }
  2391. if ( perms )
  2392. {
  2393. if ( !SystemTools::SetPermissions(real_destination, perm) )
  2394. {
  2395. return false;
  2396. }
  2397. }
  2398. return true;
  2399. }
  2400. //----------------------------------------------------------------------------
  2401. bool SystemTools::CopyAFile(const std::string& source, const std::string& destination,
  2402. bool always)
  2403. {
  2404. if(always)
  2405. {
  2406. return SystemTools::CopyFileAlways(source, destination);
  2407. }
  2408. else
  2409. {
  2410. return SystemTools::CopyFileIfDifferent(source, destination);
  2411. }
  2412. }
  2413. /**
  2414. * Copy a directory content from "source" directory to the directory named by
  2415. * "destination".
  2416. */
  2417. bool SystemTools::CopyADirectory(const std::string& source, const std::string& destination,
  2418. bool always)
  2419. {
  2420. Directory dir;
  2421. #ifdef _WIN32
  2422. dir.Load(Encoding::ToNarrow(
  2423. SystemTools::ConvertToWindowsExtendedPath(source)));
  2424. #else
  2425. dir.Load(source);
  2426. #endif
  2427. size_t fileNum;
  2428. if ( !SystemTools::MakeDirectory(destination) )
  2429. {
  2430. return false;
  2431. }
  2432. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  2433. {
  2434. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  2435. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  2436. {
  2437. std::string fullPath = source;
  2438. fullPath += "/";
  2439. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2440. if(SystemTools::FileIsDirectory(fullPath))
  2441. {
  2442. std::string fullDestPath = destination;
  2443. fullDestPath += "/";
  2444. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2445. if (!SystemTools::CopyADirectory(fullPath,
  2446. fullDestPath,
  2447. always))
  2448. {
  2449. return false;
  2450. }
  2451. }
  2452. else
  2453. {
  2454. if(!SystemTools::CopyAFile(fullPath, destination, always))
  2455. {
  2456. return false;
  2457. }
  2458. }
  2459. }
  2460. }
  2461. return true;
  2462. }
  2463. // return size of file; also returns zero if no file exists
  2464. unsigned long SystemTools::FileLength(const std::string& filename)
  2465. {
  2466. unsigned long length = 0;
  2467. #ifdef _WIN32
  2468. WIN32_FILE_ATTRIBUTE_DATA fs;
  2469. if (GetFileAttributesExW(
  2470. SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
  2471. GetFileExInfoStandard, &fs) != 0)
  2472. {
  2473. /* To support the full 64-bit file size, use fs.nFileSizeHigh
  2474. * and fs.nFileSizeLow to construct the 64 bit size
  2475. length = ((__int64)fs.nFileSizeHigh << 32) + fs.nFileSizeLow;
  2476. */
  2477. length = static_cast<unsigned long>(fs.nFileSizeLow);
  2478. }
  2479. #else
  2480. struct stat fs;
  2481. if (stat(filename.c_str(), &fs) == 0)
  2482. {
  2483. length = static_cast<unsigned long>(fs.st_size);
  2484. }
  2485. #endif
  2486. return length;
  2487. }
  2488. int SystemTools::Strucmp(const char *s1, const char *s2)
  2489. {
  2490. // lifted from Graphvis http://www.graphviz.org
  2491. while ((*s1 != '\0')
  2492. && (tolower(*s1) == tolower(*s2)))
  2493. {
  2494. s1++;
  2495. s2++;
  2496. }
  2497. return tolower(*s1) - tolower(*s2);
  2498. }
  2499. // return file's modified time
  2500. long int SystemTools::ModifiedTime(const std::string& filename)
  2501. {
  2502. long int mt = 0;
  2503. #ifdef _WIN32
  2504. WIN32_FILE_ATTRIBUTE_DATA fs;
  2505. if (GetFileAttributesExW(
  2506. SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
  2507. GetFileExInfoStandard,
  2508. &fs) != 0)
  2509. {
  2510. mt = windows_filetime_to_posix_time(fs.ftLastWriteTime);
  2511. }
  2512. #else
  2513. struct stat fs;
  2514. if (stat(filename.c_str(), &fs) == 0)
  2515. {
  2516. mt = static_cast<long int>(fs.st_mtime);
  2517. }
  2518. #endif
  2519. return mt;
  2520. }
  2521. // return file's creation time
  2522. long int SystemTools::CreationTime(const std::string& filename)
  2523. {
  2524. long int ct = 0;
  2525. #ifdef _WIN32
  2526. WIN32_FILE_ATTRIBUTE_DATA fs;
  2527. if (GetFileAttributesExW(
  2528. SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
  2529. GetFileExInfoStandard,
  2530. &fs) != 0)
  2531. {
  2532. ct = windows_filetime_to_posix_time(fs.ftCreationTime);
  2533. }
  2534. #else
  2535. struct stat fs;
  2536. if (stat(filename.c_str(), &fs) == 0)
  2537. {
  2538. ct = fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
  2539. }
  2540. #endif
  2541. return ct;
  2542. }
  2543. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  2544. {
  2545. if (!str || !tmt || strlen(str) > 11)
  2546. {
  2547. return false;
  2548. }
  2549. struct tm tmt2;
  2550. // __DATE__
  2551. // The compilation date of the current source file. The date is a string
  2552. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  2553. // dates generated by the library function asctime declared in TIME.H.
  2554. // index: 012345678901
  2555. // format: Mmm dd yyyy
  2556. // example: Dec 19 2003
  2557. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  2558. char buffer[12];
  2559. strcpy(buffer, str);
  2560. buffer[3] = 0;
  2561. char *ptr = strstr(month_names, buffer);
  2562. if (!ptr)
  2563. {
  2564. return false;
  2565. }
  2566. int month = static_cast<int>((ptr - month_names) / 3);
  2567. int day = atoi(buffer + 4);
  2568. int year = atoi(buffer + 7);
  2569. tmt2.tm_isdst = -1;
  2570. tmt2.tm_hour = 0;
  2571. tmt2.tm_min = 0;
  2572. tmt2.tm_sec = 0;
  2573. tmt2.tm_wday = 0;
  2574. tmt2.tm_yday = 0;
  2575. tmt2.tm_mday = day;
  2576. tmt2.tm_mon = month;
  2577. tmt2.tm_year = year - 1900;
  2578. *tmt = mktime(&tmt2);
  2579. return true;
  2580. }
  2581. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  2582. {
  2583. if (!str || !tmt || strlen(str) > 26)
  2584. {
  2585. return false;
  2586. }
  2587. struct tm tmt2;
  2588. // __TIMESTAMP__
  2589. // The date and time of the last modification of the current source file,
  2590. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  2591. /// where Ddd is the abbreviated day of the week and Date is an integer
  2592. // from 1 to 31.
  2593. // index: 0123456789
  2594. // 0123456789
  2595. // 0123456789
  2596. // format: Ddd Mmm Date hh:mm:ss yyyy
  2597. // example: Fri Dec 19 14:34:58 2003
  2598. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  2599. char buffer[27];
  2600. strcpy(buffer, str);
  2601. buffer[7] = 0;
  2602. char *ptr = strstr(month_names, buffer + 4);
  2603. if (!ptr)
  2604. {
  2605. return false;
  2606. }
  2607. int month = static_cast<int>((ptr - month_names) / 3);
  2608. int day = atoi(buffer + 8);
  2609. int hour = atoi(buffer + 11);
  2610. int min = atoi(buffer + 14);
  2611. int sec = atoi(buffer + 17);
  2612. int year = atoi(buffer + 20);
  2613. tmt2.tm_isdst = -1;
  2614. tmt2.tm_hour = hour;
  2615. tmt2.tm_min = min;
  2616. tmt2.tm_sec = sec;
  2617. tmt2.tm_wday = 0;
  2618. tmt2.tm_yday = 0;
  2619. tmt2.tm_mday = day;
  2620. tmt2.tm_mon = month;
  2621. tmt2.tm_year = year - 1900;
  2622. *tmt = mktime(&tmt2);
  2623. return true;
  2624. }
  2625. std::string SystemTools::GetLastSystemError()
  2626. {
  2627. int e = errno;
  2628. return strerror(e);
  2629. }
  2630. #ifdef _WIN32
  2631. static bool IsJunction(const std::wstring& source)
  2632. {
  2633. #ifdef FSCTL_GET_REPARSE_POINT
  2634. const DWORD JUNCTION_ATTRS = FILE_ATTRIBUTE_DIRECTORY |
  2635. FILE_ATTRIBUTE_REPARSE_POINT;
  2636. DWORD attrs = GetFileAttributesW(source.c_str());
  2637. if (attrs == INVALID_FILE_ATTRIBUTES)
  2638. {
  2639. return false;
  2640. }
  2641. if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS)
  2642. {
  2643. return false;
  2644. }
  2645. // Adjust privileges so that we can succefully open junction points.
  2646. HANDLE token;
  2647. TOKEN_PRIVILEGES privs;
  2648. OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token);
  2649. LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &privs.Privileges[0].Luid);
  2650. privs.PrivilegeCount = 1;
  2651. privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2652. AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
  2653. CloseHandle(token);
  2654. HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ,
  2655. 0, NULL, OPEN_EXISTING,
  2656. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2657. if (dir == INVALID_HANDLE_VALUE)
  2658. {
  2659. return false;
  2660. }
  2661. // Query whether this is a reparse point or not.
  2662. BYTE buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
  2663. REPARSE_GUID_DATA_BUFFER *reparse_buffer =
  2664. (REPARSE_GUID_DATA_BUFFER*) buffer;
  2665. DWORD sentinel;
  2666. BOOL success = DeviceIoControl(
  2667. dir, FSCTL_GET_REPARSE_POINT,
  2668. NULL, 0,
  2669. reparse_buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
  2670. &sentinel, NULL);
  2671. CloseHandle(dir);
  2672. return (success && (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT));
  2673. #else
  2674. return false;
  2675. #endif
  2676. }
  2677. static bool DeleteJunction(const std::wstring& source)
  2678. {
  2679. #ifdef FSCTL_DELETE_REPARSE_POINT
  2680. // Adjust privileges so that we can succefully open junction points as
  2681. // read/write.
  2682. HANDLE token;
  2683. TOKEN_PRIVILEGES privs;
  2684. OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token);
  2685. LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &privs.Privileges[0].Luid);
  2686. privs.PrivilegeCount = 1;
  2687. privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2688. AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
  2689. CloseHandle(token);
  2690. HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ | GENERIC_WRITE,
  2691. 0, NULL, OPEN_EXISTING,
  2692. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
  2693. if (dir == INVALID_HANDLE_VALUE)
  2694. {
  2695. return false;
  2696. }
  2697. // Set up the structure so that we can delete the junction.
  2698. std::vector<BYTE> buffer(REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, 0);
  2699. REPARSE_GUID_DATA_BUFFER *reparse_buffer =
  2700. (REPARSE_GUID_DATA_BUFFER*) &buffer[0];
  2701. DWORD sentinel;
  2702. reparse_buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
  2703. BOOL success = DeviceIoControl(
  2704. dir, FSCTL_DELETE_REPARSE_POINT,
  2705. reparse_buffer, REPARSE_GUID_DATA_BUFFER_HEADER_SIZE,
  2706. NULL, 0,
  2707. &sentinel, NULL);
  2708. CloseHandle(dir);
  2709. return !!success;
  2710. #else
  2711. return false;
  2712. #endif
  2713. }
  2714. #endif
  2715. bool SystemTools::RemoveFile(const std::string& source)
  2716. {
  2717. #ifdef _WIN32
  2718. std::wstring const& ws =
  2719. SystemTools::ConvertToWindowsExtendedPath(source);
  2720. if (DeleteFileW(ws.c_str()))
  2721. {
  2722. return true;
  2723. }
  2724. DWORD err = GetLastError();
  2725. if (err == ERROR_FILE_NOT_FOUND ||
  2726. err == ERROR_PATH_NOT_FOUND)
  2727. {
  2728. return true;
  2729. }
  2730. if (err != ERROR_ACCESS_DENIED)
  2731. {
  2732. return false;
  2733. }
  2734. /* The file may be read-only. Try adding write permission. */
  2735. mode_t mode;
  2736. if (!SystemTools::GetPermissions(source, mode) ||
  2737. !SystemTools::SetPermissions(source, S_IWRITE))
  2738. {
  2739. SetLastError(err);
  2740. return false;
  2741. }
  2742. if (IsJunction(ws) && DeleteJunction(ws))
  2743. {
  2744. return true;
  2745. }
  2746. if (DeleteFileW(ws.c_str()) ||
  2747. GetLastError() == ERROR_FILE_NOT_FOUND ||
  2748. GetLastError() == ERROR_PATH_NOT_FOUND)
  2749. {
  2750. return true;
  2751. }
  2752. /* Try to restore the original permissions. */
  2753. SystemTools::SetPermissions(source, mode);
  2754. SetLastError(err);
  2755. return false;
  2756. #else
  2757. return unlink(source.c_str()) == 0 || errno == ENOENT;
  2758. #endif
  2759. }
  2760. bool SystemTools::RemoveADirectory(const std::string& source)
  2761. {
  2762. // Add write permission to the directory so we can modify its
  2763. // content to remove files and directories from it.
  2764. mode_t mode;
  2765. if(SystemTools::GetPermissions(source, mode))
  2766. {
  2767. #if defined(_WIN32) && !defined(__CYGWIN__)
  2768. mode |= S_IWRITE;
  2769. #else
  2770. mode |= S_IWUSR;
  2771. #endif
  2772. SystemTools::SetPermissions(source, mode);
  2773. }
  2774. Directory dir;
  2775. #ifdef _WIN32
  2776. dir.Load(Encoding::ToNarrow(
  2777. SystemTools::ConvertToWindowsExtendedPath(source)));
  2778. #else
  2779. dir.Load(source);
  2780. #endif
  2781. size_t fileNum;
  2782. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  2783. {
  2784. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  2785. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  2786. {
  2787. std::string fullPath = source;
  2788. fullPath += "/";
  2789. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2790. if(SystemTools::FileIsDirectory(fullPath) &&
  2791. !SystemTools::FileIsSymlink(fullPath))
  2792. {
  2793. if (!SystemTools::RemoveADirectory(fullPath))
  2794. {
  2795. return false;
  2796. }
  2797. }
  2798. else
  2799. {
  2800. if(!SystemTools::RemoveFile(fullPath))
  2801. {
  2802. return false;
  2803. }
  2804. }
  2805. }
  2806. }
  2807. return (Rmdir(source) == 0);
  2808. }
  2809. /**
  2810. */
  2811. size_t SystemTools::GetMaximumFilePathLength()
  2812. {
  2813. return KWSYS_SYSTEMTOOLS_MAXPATH;
  2814. }
  2815. /**
  2816. * Find the file the given name. Searches the given path and then
  2817. * the system search path. Returns the full path to the file if it is
  2818. * found. Otherwise, the empty string is returned.
  2819. */
  2820. std::string SystemTools
  2821. ::FindName(const std::string& name,
  2822. const std::vector<std::string>& userPaths,
  2823. bool no_system_path)
  2824. {
  2825. // Add the system search path to our path first
  2826. std::vector<std::string> path;
  2827. if (!no_system_path)
  2828. {
  2829. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  2830. SystemTools::GetPath(path);
  2831. }
  2832. // now add the additional paths
  2833. {
  2834. for(std::vector<std::string>::const_iterator i = userPaths.begin();
  2835. i != userPaths.end(); ++i)
  2836. {
  2837. path.push_back(*i);
  2838. }
  2839. }
  2840. // Add a trailing slash to all paths to aid the search process.
  2841. {
  2842. for(std::vector<std::string>::iterator i = path.begin();
  2843. i != path.end(); ++i)
  2844. {
  2845. std::string& p = *i;
  2846. if(p.empty() || *p.rbegin() != '/')
  2847. {
  2848. p += "/";
  2849. }
  2850. }
  2851. }
  2852. // now look for the file
  2853. std::string tryPath;
  2854. for(std::vector<std::string>::const_iterator p = path.begin();
  2855. p != path.end(); ++p)
  2856. {
  2857. tryPath = *p;
  2858. tryPath += name;
  2859. if(SystemTools::FileExists(tryPath))
  2860. {
  2861. return tryPath;
  2862. }
  2863. }
  2864. // Couldn't find the file.
  2865. return "";
  2866. }
  2867. /**
  2868. * Find the file the given name. Searches the given path and then
  2869. * the system search path. Returns the full path to the file if it is
  2870. * found. Otherwise, the empty string is returned.
  2871. */
  2872. std::string SystemTools
  2873. ::FindFile(const std::string& name,
  2874. const std::vector<std::string>& userPaths,
  2875. bool no_system_path)
  2876. {
  2877. std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  2878. if(!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath))
  2879. {
  2880. return SystemTools::CollapseFullPath(tryPath);
  2881. }
  2882. // Couldn't find the file.
  2883. return "";
  2884. }
  2885. /**
  2886. * Find the directory the given name. Searches the given path and then
  2887. * the system search path. Returns the full path to the directory if it is
  2888. * found. Otherwise, the empty string is returned.
  2889. */
  2890. std::string SystemTools
  2891. ::FindDirectory(const std::string& name,
  2892. const std::vector<std::string>& userPaths,
  2893. bool no_system_path)
  2894. {
  2895. std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  2896. if(!tryPath.empty() && SystemTools::FileIsDirectory(tryPath))
  2897. {
  2898. return SystemTools::CollapseFullPath(tryPath);
  2899. }
  2900. // Couldn't find the file.
  2901. return "";
  2902. }
  2903. /**
  2904. * Find the executable with the given name. Searches the given path and then
  2905. * the system search path. Returns the full path to the executable if it is
  2906. * found. Otherwise, the empty string is returned.
  2907. */
  2908. std::string SystemTools::FindProgram(
  2909. const char* nameIn,
  2910. const std::vector<std::string>& userPaths,
  2911. bool no_system_path)
  2912. {
  2913. if(!nameIn || !*nameIn)
  2914. {
  2915. return "";
  2916. }
  2917. return SystemTools::FindProgram(std::string(nameIn), userPaths, no_system_path);
  2918. }
  2919. std::string SystemTools::FindProgram(
  2920. const std::string& name,
  2921. const std::vector<std::string>& userPaths,
  2922. bool no_system_path)
  2923. {
  2924. std::string tryPath;
  2925. #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  2926. std::vector<std::string> extensions;
  2927. // check to see if the name already has a .xxx at
  2928. // the end of it
  2929. // on windows try .com then .exe
  2930. if(name.size() <= 3 || name[name.size()-4] != '.')
  2931. {
  2932. extensions.push_back(".com");
  2933. extensions.push_back(".exe");
  2934. // first try with extensions if the os supports them
  2935. for(std::vector<std::string>::iterator i =
  2936. extensions.begin(); i != extensions.end(); ++i)
  2937. {
  2938. tryPath = name;
  2939. tryPath += *i;
  2940. if(SystemTools::FileExists(tryPath, true))
  2941. {
  2942. return SystemTools::CollapseFullPath(tryPath);
  2943. }
  2944. }
  2945. }
  2946. #endif
  2947. // now try just the name
  2948. if(SystemTools::FileExists(name, true))
  2949. {
  2950. return SystemTools::CollapseFullPath(name);
  2951. }
  2952. // now construct the path
  2953. std::vector<std::string> path;
  2954. // Add the system search path to our path.
  2955. if (!no_system_path)
  2956. {
  2957. SystemTools::GetPath(path);
  2958. }
  2959. // now add the additional paths
  2960. {
  2961. for(std::vector<std::string>::const_iterator i =
  2962. userPaths.begin(); i != userPaths.end(); ++i)
  2963. {
  2964. path.push_back(*i);
  2965. }
  2966. }
  2967. // Add a trailing slash to all paths to aid the search process.
  2968. {
  2969. for(std::vector<std::string>::iterator i = path.begin();
  2970. i != path.end(); ++i)
  2971. {
  2972. std::string& p = *i;
  2973. if(p.empty() || *p.rbegin() != '/')
  2974. {
  2975. p += "/";
  2976. }
  2977. }
  2978. }
  2979. // Try each path
  2980. for(std::vector<std::string>::iterator p = path.begin();
  2981. p != path.end(); ++p)
  2982. {
  2983. #ifdef _WIN32
  2984. // Remove double quotes from the path on windows
  2985. SystemTools::ReplaceString(*p, "\"", "");
  2986. #endif
  2987. #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  2988. // first try with extensions
  2989. for(std::vector<std::string>::iterator ext
  2990. = extensions.begin(); ext != extensions.end(); ++ext)
  2991. {
  2992. tryPath = *p;
  2993. tryPath += name;
  2994. tryPath += *ext;
  2995. if(SystemTools::FileExists(tryPath, true))
  2996. {
  2997. return SystemTools::CollapseFullPath(tryPath);
  2998. }
  2999. }
  3000. #endif
  3001. // now try it without them
  3002. tryPath = *p;
  3003. tryPath += name;
  3004. if(SystemTools::FileExists(tryPath, true))
  3005. {
  3006. return SystemTools::CollapseFullPath(tryPath);
  3007. }
  3008. }
  3009. // Couldn't find the program.
  3010. return "";
  3011. }
  3012. std::string SystemTools::FindProgram(
  3013. const std::vector<std::string>& names,
  3014. const std::vector<std::string>& path,
  3015. bool noSystemPath)
  3016. {
  3017. for(std::vector<std::string>::const_iterator it = names.begin();
  3018. it != names.end() ; ++it)
  3019. {
  3020. // Try to find the program.
  3021. std::string result = SystemTools::FindProgram(*it,
  3022. path,
  3023. noSystemPath);
  3024. if ( !result.empty() )
  3025. {
  3026. return result;
  3027. }
  3028. }
  3029. return "";
  3030. }
  3031. /**
  3032. * Find the library with the given name. Searches the given path and then
  3033. * the system search path. Returns the full path to the library if it is
  3034. * found. Otherwise, the empty string is returned.
  3035. */
  3036. std::string SystemTools
  3037. ::FindLibrary(const std::string& name,
  3038. const std::vector<std::string>& userPaths)
  3039. {
  3040. // See if the executable exists as written.
  3041. if(SystemTools::FileExists(name, true))
  3042. {
  3043. return SystemTools::CollapseFullPath(name);
  3044. }
  3045. // Add the system search path to our path.
  3046. std::vector<std::string> path;
  3047. SystemTools::GetPath(path);
  3048. // now add the additional paths
  3049. {
  3050. for(std::vector<std::string>::const_iterator i = userPaths.begin();
  3051. i != userPaths.end(); ++i)
  3052. {
  3053. path.push_back(*i);
  3054. }
  3055. }
  3056. // Add a trailing slash to all paths to aid the search process.
  3057. {
  3058. for(std::vector<std::string>::iterator i = path.begin();
  3059. i != path.end(); ++i)
  3060. {
  3061. std::string& p = *i;
  3062. if(p.empty() || *p.rbegin() != '/')
  3063. {
  3064. p += "/";
  3065. }
  3066. }
  3067. }
  3068. std::string tryPath;
  3069. for(std::vector<std::string>::const_iterator p = path.begin();
  3070. p != path.end(); ++p)
  3071. {
  3072. #if defined(__APPLE__)
  3073. tryPath = *p;
  3074. tryPath += name;
  3075. tryPath += ".framework";
  3076. if(SystemTools::FileIsDirectory(tryPath))
  3077. {
  3078. return SystemTools::CollapseFullPath(tryPath);
  3079. }
  3080. #endif
  3081. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  3082. tryPath = *p;
  3083. tryPath += name;
  3084. tryPath += ".lib";
  3085. if(SystemTools::FileExists(tryPath, true))
  3086. {
  3087. return SystemTools::CollapseFullPath(tryPath);
  3088. }
  3089. #else
  3090. tryPath = *p;
  3091. tryPath += "lib";
  3092. tryPath += name;
  3093. tryPath += ".so";
  3094. if(SystemTools::FileExists(tryPath, true))
  3095. {
  3096. return SystemTools::CollapseFullPath(tryPath);
  3097. }
  3098. tryPath = *p;
  3099. tryPath += "lib";
  3100. tryPath += name;
  3101. tryPath += ".a";
  3102. if(SystemTools::FileExists(tryPath, true))
  3103. {
  3104. return SystemTools::CollapseFullPath(tryPath);
  3105. }
  3106. tryPath = *p;
  3107. tryPath += "lib";
  3108. tryPath += name;
  3109. tryPath += ".sl";
  3110. if(SystemTools::FileExists(tryPath, true))
  3111. {
  3112. return SystemTools::CollapseFullPath(tryPath);
  3113. }
  3114. tryPath = *p;
  3115. tryPath += "lib";
  3116. tryPath += name;
  3117. tryPath += ".dylib";
  3118. if(SystemTools::FileExists(tryPath, true))
  3119. {
  3120. return SystemTools::CollapseFullPath(tryPath);
  3121. }
  3122. tryPath = *p;
  3123. tryPath += "lib";
  3124. tryPath += name;
  3125. tryPath += ".dll";
  3126. if(SystemTools::FileExists(tryPath, true))
  3127. {
  3128. return SystemTools::CollapseFullPath(tryPath);
  3129. }
  3130. #endif
  3131. }
  3132. // Couldn't find the library.
  3133. return "";
  3134. }
  3135. std::string SystemTools::GetRealPath(const std::string& path,
  3136. std::string* errorMessage)
  3137. {
  3138. std::string ret;
  3139. Realpath(path, ret, errorMessage);
  3140. return ret;
  3141. }
  3142. bool SystemTools::FileIsDirectory(const std::string& inName)
  3143. {
  3144. if (inName.empty())
  3145. {
  3146. return false;
  3147. }
  3148. size_t length = inName.size();
  3149. const char* name = inName.c_str();
  3150. // Remove any trailing slash from the name except in a root component.
  3151. char local_buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
  3152. std::string string_buffer;
  3153. size_t last = length-1;
  3154. if(last > 0 && (name[last] == '/' || name[last] == '\\')
  3155. && strcmp(name, "/") != 0 && name[last-1] != ':')
  3156. {
  3157. if (last < sizeof(local_buffer))
  3158. {
  3159. memcpy(local_buffer, name, last);
  3160. local_buffer[last] = '\0';
  3161. name = local_buffer;
  3162. }
  3163. else
  3164. {
  3165. string_buffer.append(name, last);
  3166. name = string_buffer.c_str();
  3167. }
  3168. }
  3169. // Now check the file node type.
  3170. #if defined( _WIN32 )
  3171. DWORD attr = GetFileAttributesW(
  3172. SystemTools::ConvertToWindowsExtendedPath(name).c_str());
  3173. if (attr != INVALID_FILE_ATTRIBUTES)
  3174. {
  3175. return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
  3176. #else
  3177. struct stat fs;
  3178. if(stat(name, &fs) == 0)
  3179. {
  3180. return S_ISDIR(fs.st_mode);
  3181. #endif
  3182. }
  3183. else
  3184. {
  3185. return false;
  3186. }
  3187. }
  3188. bool SystemTools::FileIsSymlink(const std::string& name)
  3189. {
  3190. #if defined( _WIN32 )
  3191. DWORD attr = GetFileAttributesW(
  3192. SystemTools::ConvertToWindowsExtendedPath(name).c_str());
  3193. if (attr != INVALID_FILE_ATTRIBUTES)
  3194. {
  3195. return (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
  3196. }
  3197. else
  3198. {
  3199. return false;
  3200. }
  3201. #else
  3202. struct stat fs;
  3203. if(lstat(name.c_str(), &fs) == 0)
  3204. {
  3205. return S_ISLNK(fs.st_mode);
  3206. }
  3207. else
  3208. {
  3209. return false;
  3210. }
  3211. #endif
  3212. }
  3213. #if defined(_WIN32) && !defined(__CYGWIN__)
  3214. bool SystemTools::CreateSymlink(const std::string&, const std::string&)
  3215. {
  3216. return false;
  3217. }
  3218. #else
  3219. bool SystemTools::CreateSymlink(const std::string& origName, const std::string& newName)
  3220. {
  3221. return symlink(origName.c_str(), newName.c_str()) >= 0;
  3222. }
  3223. #endif
  3224. #if defined(_WIN32) && !defined(__CYGWIN__)
  3225. bool SystemTools::ReadSymlink(const std::string&, std::string&)
  3226. {
  3227. return false;
  3228. }
  3229. #else
  3230. bool SystemTools::ReadSymlink(const std::string& newName,
  3231. std::string& origName)
  3232. {
  3233. char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1];
  3234. int count =
  3235. static_cast<int>(readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH));
  3236. if(count >= 0)
  3237. {
  3238. // Add null-terminator.
  3239. buf[count] = 0;
  3240. origName = buf;
  3241. return true;
  3242. }
  3243. else
  3244. {
  3245. return false;
  3246. }
  3247. }
  3248. #endif
  3249. int SystemTools::ChangeDirectory(const std::string& dir)
  3250. {
  3251. return Chdir(dir);
  3252. }
  3253. std::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  3254. {
  3255. char buf[2048];
  3256. const char* cwd = Getcwd(buf, 2048);
  3257. std::string path;
  3258. if ( cwd )
  3259. {
  3260. path = cwd;
  3261. }
  3262. if(collapse)
  3263. {
  3264. return SystemTools::CollapseFullPath(path);
  3265. }
  3266. return path;
  3267. }
  3268. std::string SystemTools::GetProgramPath(const std::string& in_name)
  3269. {
  3270. std::string dir, file;
  3271. SystemTools::SplitProgramPath(in_name, dir, file);
  3272. return dir;
  3273. }
  3274. bool SystemTools::SplitProgramPath(const std::string& in_name,
  3275. std::string& dir,
  3276. std::string& file,
  3277. bool)
  3278. {
  3279. dir = in_name;
  3280. file = "";
  3281. SystemTools::ConvertToUnixSlashes(dir);
  3282. if(!SystemTools::FileIsDirectory(dir))
  3283. {
  3284. std::string::size_type slashPos = dir.rfind("/");
  3285. if(slashPos != std::string::npos)
  3286. {
  3287. file = dir.substr(slashPos+1);
  3288. dir = dir.substr(0, slashPos);
  3289. }
  3290. else
  3291. {
  3292. file = dir;
  3293. dir = "";
  3294. }
  3295. }
  3296. if(!(dir.empty()) && !SystemTools::FileIsDirectory(dir))
  3297. {
  3298. std::string oldDir = in_name;
  3299. SystemTools::ConvertToUnixSlashes(oldDir);
  3300. dir = in_name;
  3301. return false;
  3302. }
  3303. return true;
  3304. }
  3305. bool SystemTools::FindProgramPath(const char* argv0,
  3306. std::string& pathOut,
  3307. std::string& errorMsg,
  3308. const char* exeName,
  3309. const char* buildDir,
  3310. const char* installPrefix )
  3311. {
  3312. std::vector<std::string> failures;
  3313. std::string self = argv0 ? argv0 : "";
  3314. failures.push_back(self);
  3315. SystemTools::ConvertToUnixSlashes(self);
  3316. self = SystemTools::FindProgram(self);
  3317. if(!SystemTools::FileExists(self))
  3318. {
  3319. if(buildDir)
  3320. {
  3321. std::string intdir = ".";
  3322. #ifdef CMAKE_INTDIR
  3323. intdir = CMAKE_INTDIR;
  3324. #endif
  3325. self = buildDir;
  3326. self += "/bin/";
  3327. self += intdir;
  3328. self += "/";
  3329. self += exeName;
  3330. self += SystemTools::GetExecutableExtension();
  3331. }
  3332. }
  3333. if(installPrefix)
  3334. {
  3335. if(!SystemTools::FileExists(self))
  3336. {
  3337. failures.push_back(self);
  3338. self = installPrefix;
  3339. self += "/bin/";
  3340. self += exeName;
  3341. }
  3342. }
  3343. if(!SystemTools::FileExists(self))
  3344. {
  3345. failures.push_back(self);
  3346. std::ostringstream msg;
  3347. msg << "Can not find the command line program ";
  3348. if (exeName)
  3349. {
  3350. msg << exeName;
  3351. }
  3352. msg << "\n";
  3353. if (argv0)
  3354. {
  3355. msg << " argv[0] = \"" << argv0 << "\"\n";
  3356. }
  3357. msg << " Attempted paths:\n";
  3358. std::vector<std::string>::iterator i;
  3359. for(i=failures.begin(); i != failures.end(); ++i)
  3360. {
  3361. msg << " \"" << *i << "\"\n";
  3362. }
  3363. errorMsg = msg.str();
  3364. return false;
  3365. }
  3366. pathOut = self;
  3367. return true;
  3368. }
  3369. std::string SystemTools::CollapseFullPath(const std::string& in_relative)
  3370. {
  3371. return SystemTools::CollapseFullPath(in_relative, 0);
  3372. }
  3373. void SystemTools::AddTranslationPath(const std::string& a, const std::string& b)
  3374. {
  3375. std::string path_a = a;
  3376. std::string path_b = b;
  3377. SystemTools::ConvertToUnixSlashes(path_a);
  3378. SystemTools::ConvertToUnixSlashes(path_b);
  3379. // First check this is a directory path, since we don't want the table to
  3380. // grow too fat
  3381. if( SystemTools::FileIsDirectory( path_a ) )
  3382. {
  3383. // Make sure the path is a full path and does not contain no '..'
  3384. // Ken--the following code is incorrect. .. can be in a valid path
  3385. // for example /home/martink/MyHubba...Hubba/Src
  3386. if( SystemTools::FileIsFullPath(path_b) && path_b.find("..")
  3387. == std::string::npos )
  3388. {
  3389. // Before inserting make sure path ends with '/'
  3390. if(!path_a.empty() && *path_a.rbegin() != '/')
  3391. {
  3392. path_a += '/';
  3393. }
  3394. if(!path_b.empty() && *path_b.rbegin() != '/')
  3395. {
  3396. path_b += '/';
  3397. }
  3398. if( !(path_a == path_b) )
  3399. {
  3400. SystemTools::TranslationMap->insert(
  3401. SystemToolsTranslationMap::value_type(path_a, path_b));
  3402. }
  3403. }
  3404. }
  3405. }
  3406. void SystemTools::AddKeepPath(const std::string& dir)
  3407. {
  3408. std::string cdir;
  3409. Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir);
  3410. SystemTools::AddTranslationPath(cdir, dir);
  3411. }
  3412. void SystemTools::CheckTranslationPath(std::string & path)
  3413. {
  3414. // Do not translate paths that are too short to have meaningful
  3415. // translations.
  3416. if(path.size() < 2)
  3417. {
  3418. return;
  3419. }
  3420. // Always add a trailing slash before translation. It does not
  3421. // matter if this adds an extra slash, but we do not want to
  3422. // translate part of a directory (like the foo part of foo-dir).
  3423. path += "/";
  3424. // In case a file was specified we still have to go through this:
  3425. // Now convert any path found in the table back to the one desired:
  3426. std::map<std::string,std::string>::const_iterator it;
  3427. for(it = SystemTools::TranslationMap->begin();
  3428. it != SystemTools::TranslationMap->end();
  3429. ++it )
  3430. {
  3431. // We need to check of the path is a substring of the other path
  3432. if(path.find( it->first ) == 0)
  3433. {
  3434. path = path.replace( 0, it->first.size(), it->second);
  3435. }
  3436. }
  3437. // Remove the trailing slash we added before.
  3438. path.erase(path.end()-1, path.end());
  3439. }
  3440. static void
  3441. SystemToolsAppendComponents(
  3442. std::vector<std::string>& out_components,
  3443. std::vector<std::string>::const_iterator first,
  3444. std::vector<std::string>::const_iterator last)
  3445. {
  3446. static const std::string up = "..";
  3447. static const std::string cur = ".";
  3448. for(std::vector<std::string>::const_iterator i = first;
  3449. i != last; ++i)
  3450. {
  3451. if(*i == up)
  3452. {
  3453. if(out_components.size() > 1)
  3454. {
  3455. out_components.resize(out_components.size()-1);
  3456. }
  3457. }
  3458. else if(!i->empty() && *i != cur)
  3459. {
  3460. out_components.push_back(*i);
  3461. }
  3462. }
  3463. }
  3464. std::string SystemTools::CollapseFullPath(const std::string& in_path,
  3465. const char* in_base)
  3466. {
  3467. // Collect the output path components.
  3468. std::vector<std::string> out_components;
  3469. // Split the input path components.
  3470. std::vector<std::string> path_components;
  3471. SystemTools::SplitPath(in_path, path_components);
  3472. // If the input path is relative, start with a base path.
  3473. if(path_components[0].length() == 0)
  3474. {
  3475. std::vector<std::string> base_components;
  3476. if(in_base)
  3477. {
  3478. // Use the given base path.
  3479. SystemTools::SplitPath(in_base, base_components);
  3480. }
  3481. else
  3482. {
  3483. // Use the current working directory as a base path.
  3484. char buf[2048];
  3485. if(const char* cwd = Getcwd(buf, 2048))
  3486. {
  3487. SystemTools::SplitPath(cwd, base_components);
  3488. }
  3489. else
  3490. {
  3491. base_components.push_back("");
  3492. }
  3493. }
  3494. // Append base path components to the output path.
  3495. out_components.push_back(base_components[0]);
  3496. SystemToolsAppendComponents(out_components,
  3497. base_components.begin()+1,
  3498. base_components.end());
  3499. }
  3500. // Append input path components to the output path.
  3501. SystemToolsAppendComponents(out_components,
  3502. path_components.begin(),
  3503. path_components.end());
  3504. // Transform the path back to a string.
  3505. std::string newPath = SystemTools::JoinPath(out_components);
  3506. // Update the translation table with this potentially new path. I am not
  3507. // sure why this line is here, it seems really questionable, but yet I
  3508. // would put good money that if I remove it something will break, basically
  3509. // from what I can see it created a mapping from the collapsed path, to be
  3510. // replaced by the input path, which almost completely does the opposite of
  3511. // this function, the only thing preventing this from happening a lot is
  3512. // that if the in_path has a .. in it, then it is not added to the
  3513. // translation table. So for most calls this either does nothing due to the
  3514. // .. or it adds a translation between identical paths as nothing was
  3515. // collapsed, so I am going to try to comment it out, and see what hits the
  3516. // fan, hopefully quickly.
  3517. // Commented out line below:
  3518. //SystemTools::AddTranslationPath(newPath, in_path);
  3519. SystemTools::CheckTranslationPath(newPath);
  3520. #ifdef _WIN32
  3521. newPath = SystemTools::GetActualCaseForPath(newPath);
  3522. SystemTools::ConvertToUnixSlashes(newPath);
  3523. #endif
  3524. // Return the reconstructed path.
  3525. return newPath;
  3526. }
  3527. std::string SystemTools::CollapseFullPath(const std::string& in_path,
  3528. const std::string& in_base)
  3529. {
  3530. // Collect the output path components.
  3531. std::vector<std::string> out_components;
  3532. // Split the input path components.
  3533. std::vector<std::string> path_components;
  3534. SystemTools::SplitPath(in_path, path_components);
  3535. // If the input path is relative, start with a base path.
  3536. if(path_components[0].length() == 0)
  3537. {
  3538. std::vector<std::string> base_components;
  3539. // Use the given base path.
  3540. SystemTools::SplitPath(in_base, base_components);
  3541. // Append base path components to the output path.
  3542. out_components.push_back(base_components[0]);
  3543. SystemToolsAppendComponents(out_components,
  3544. base_components.begin()+1,
  3545. base_components.end());
  3546. }
  3547. // Append input path components to the output path.
  3548. SystemToolsAppendComponents(out_components,
  3549. path_components.begin(),
  3550. path_components.end());
  3551. // Transform the path back to a string.
  3552. std::string newPath = SystemTools::JoinPath(out_components);
  3553. // Update the translation table with this potentially new path. I am not
  3554. // sure why this line is here, it seems really questionable, but yet I
  3555. // would put good money that if I remove it something will break, basically
  3556. // from what I can see it created a mapping from the collapsed path, to be
  3557. // replaced by the input path, which almost completely does the opposite of
  3558. // this function, the only thing preventing this from happening a lot is
  3559. // that if the in_path has a .. in it, then it is not added to the
  3560. // translation table. So for most calls this either does nothing due to the
  3561. // .. or it adds a translation between identical paths as nothing was
  3562. // collapsed, so I am going to try to comment it out, and see what hits the
  3563. // fan, hopefully quickly.
  3564. // Commented out line below:
  3565. //SystemTools::AddTranslationPath(newPath, in_path);
  3566. SystemTools::CheckTranslationPath(newPath);
  3567. #ifdef _WIN32
  3568. newPath = SystemTools::GetActualCaseForPath(newPath);
  3569. SystemTools::ConvertToUnixSlashes(newPath);
  3570. #endif
  3571. // Return the reconstructed path.
  3572. return newPath;
  3573. }
  3574. // compute the relative path from here to there
  3575. std::string SystemTools::RelativePath(const std::string& local, const std::string& remote)
  3576. {
  3577. if(!SystemTools::FileIsFullPath(local))
  3578. {
  3579. return "";
  3580. }
  3581. if(!SystemTools::FileIsFullPath(remote))
  3582. {
  3583. return "";
  3584. }
  3585. std::string l = SystemTools::CollapseFullPath(local);
  3586. std::string r = SystemTools::CollapseFullPath(remote);
  3587. // split up both paths into arrays of strings using / as a separator
  3588. std::vector<kwsys::String> localSplit = SystemTools::SplitString(l, '/', true);
  3589. std::vector<kwsys::String> remoteSplit = SystemTools::SplitString(r, '/', true);
  3590. std::vector<kwsys::String> commonPath; // store shared parts of path in this array
  3591. std::vector<kwsys::String> finalPath; // store the final relative path here
  3592. // count up how many matching directory names there are from the start
  3593. unsigned int sameCount = 0;
  3594. while(
  3595. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  3596. &&
  3597. // for windows and apple do a case insensitive string compare
  3598. #if defined(_WIN32) || defined(__APPLE__)
  3599. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  3600. remoteSplit[sameCount].c_str()) == 0
  3601. #else
  3602. localSplit[sameCount] == remoteSplit[sameCount]
  3603. #endif
  3604. )
  3605. {
  3606. // put the common parts of the path into the commonPath array
  3607. commonPath.push_back(localSplit[sameCount]);
  3608. // erase the common parts of the path from the original path arrays
  3609. localSplit[sameCount] = "";
  3610. remoteSplit[sameCount] = "";
  3611. sameCount++;
  3612. }
  3613. // If there is nothing in common at all then just return the full
  3614. // path. This is the case only on windows when the paths have
  3615. // different drive letters. On unix two full paths always at least
  3616. // have the root "/" in common so we will return a relative path
  3617. // that passes through the root directory.
  3618. if(sameCount == 0)
  3619. {
  3620. return remote;
  3621. }
  3622. // for each entry that is not common in the local path
  3623. // add a ../ to the finalpath array, this gets us out of the local
  3624. // path into the remote dir
  3625. for(unsigned int i = 0; i < localSplit.size(); ++i)
  3626. {
  3627. if(!localSplit[i].empty())
  3628. {
  3629. finalPath.push_back("../");
  3630. }
  3631. }
  3632. // for each entry that is not common in the remote path add it
  3633. // to the final path.
  3634. for(std::vector<String>::iterator vit = remoteSplit.begin();
  3635. vit != remoteSplit.end(); ++vit)
  3636. {
  3637. if(!vit->empty())
  3638. {
  3639. finalPath.push_back(*vit);
  3640. }
  3641. }
  3642. std::string relativePath; // result string
  3643. // now turn the array of directories into a unix path by puttint /
  3644. // between each entry that does not already have one
  3645. for(std::vector<String>::iterator vit1 = finalPath.begin();
  3646. vit1 != finalPath.end(); ++vit1)
  3647. {
  3648. if(!relativePath.empty() && *relativePath.rbegin() != '/')
  3649. {
  3650. relativePath += "/";
  3651. }
  3652. relativePath += *vit1;
  3653. }
  3654. return relativePath;
  3655. }
  3656. #ifdef _WIN32
  3657. static std::string GetCasePathName(std::string const& pathIn)
  3658. {
  3659. std::string casePath;
  3660. std::vector<std::string> path_components;
  3661. SystemTools::SplitPath(pathIn, path_components);
  3662. if(path_components[0].empty()) // First component always exists.
  3663. {
  3664. // Relative paths cannot be converted.
  3665. casePath = pathIn;
  3666. return casePath;
  3667. }
  3668. // Start with root component.
  3669. std::vector<std::string>::size_type idx = 0;
  3670. casePath = path_components[idx++];
  3671. // make sure drive letter is always upper case
  3672. if(casePath.size() > 1 && casePath[1] == ':')
  3673. {
  3674. casePath[0] = toupper(casePath[0]);
  3675. }
  3676. const char* sep = "";
  3677. // If network path, fill casePath with server/share so FindFirstFile
  3678. // will work after that. Maybe someday call other APIs to get
  3679. // actual case of servers and shares.
  3680. if(path_components.size() > 2 && path_components[0] == "//")
  3681. {
  3682. casePath += path_components[idx++];
  3683. casePath += "/";
  3684. casePath += path_components[idx++];
  3685. sep = "/";
  3686. }
  3687. // Convert case of all components that exist.
  3688. bool converting = true;
  3689. for(; idx < path_components.size(); idx++)
  3690. {
  3691. casePath += sep;
  3692. sep = "/";
  3693. if (converting)
  3694. {
  3695. // If path component contains wildcards, we skip matching
  3696. // because these filenames are not allowed on windows,
  3697. // and we do not want to match a different file.
  3698. if(path_components[idx].find('*') != std::string::npos ||
  3699. path_components[idx].find('?') != std::string::npos)
  3700. {
  3701. converting = false;
  3702. }
  3703. else
  3704. {
  3705. std::string test_str = casePath;
  3706. test_str += path_components[idx];
  3707. WIN32_FIND_DATAW findData;
  3708. HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
  3709. &findData);
  3710. if (INVALID_HANDLE_VALUE != hFind)
  3711. {
  3712. path_components[idx] = Encoding::ToNarrow(findData.cFileName);
  3713. ::FindClose(hFind);
  3714. }
  3715. else
  3716. {
  3717. converting = false;
  3718. }
  3719. }
  3720. }
  3721. casePath += path_components[idx];
  3722. }
  3723. return casePath;
  3724. }
  3725. #endif
  3726. //----------------------------------------------------------------------------
  3727. std::string SystemTools::GetActualCaseForPath(const std::string& p)
  3728. {
  3729. #ifndef _WIN32
  3730. return p;
  3731. #else
  3732. // Check to see if actual case has already been called
  3733. // for this path, and the result is stored in the PathCaseMap
  3734. SystemToolsPathCaseMap::iterator i =
  3735. SystemTools::PathCaseMap->find(p);
  3736. if(i != SystemTools::PathCaseMap->end())
  3737. {
  3738. return i->second;
  3739. }
  3740. std::string casePath = GetCasePathName(p);
  3741. if (casePath.size() > MAX_PATH)
  3742. {
  3743. return casePath;
  3744. }
  3745. (*SystemTools::PathCaseMap)[p] = casePath;
  3746. return casePath;
  3747. #endif
  3748. }
  3749. //----------------------------------------------------------------------------
  3750. const char* SystemTools::SplitPathRootComponent(const std::string& p,
  3751. std::string* root)
  3752. {
  3753. // Identify the root component.
  3754. const char* c = p.c_str();
  3755. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  3756. {
  3757. // Network path.
  3758. if(root)
  3759. {
  3760. *root = "//";
  3761. }
  3762. c += 2;
  3763. }
  3764. else if(c[0] == '/' || c[0] == '\\')
  3765. {
  3766. // Unix path (or Windows path w/out drive letter).
  3767. if(root)
  3768. {
  3769. *root = "/";
  3770. }
  3771. c += 1;
  3772. }
  3773. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  3774. {
  3775. // Windows path.
  3776. if(root)
  3777. {
  3778. (*root) = "_:/";
  3779. (*root)[0] = c[0];
  3780. }
  3781. c += 3;
  3782. }
  3783. else if(c[0] && c[1] == ':')
  3784. {
  3785. // Path relative to a windows drive working directory.
  3786. if(root)
  3787. {
  3788. (*root) = "_:";
  3789. (*root)[0] = c[0];
  3790. }
  3791. c += 2;
  3792. }
  3793. else if(c[0] == '~')
  3794. {
  3795. // Home directory. The returned root should always have a
  3796. // trailing slash so that appending components as
  3797. // c[0]c[1]/c[2]/... works. The remaining path returned should
  3798. // skip the first slash if it exists:
  3799. //
  3800. // "~" : root = "~/" , return ""
  3801. // "~/ : root = "~/" , return ""
  3802. // "~/x : root = "~/" , return "x"
  3803. // "~u" : root = "~u/", return ""
  3804. // "~u/" : root = "~u/", return ""
  3805. // "~u/x" : root = "~u/", return "x"
  3806. size_t n = 1;
  3807. while(c[n] && c[n] != '/')
  3808. {
  3809. ++n;
  3810. }
  3811. if(root)
  3812. {
  3813. root->assign(c, n);
  3814. *root += '/';
  3815. }
  3816. if(c[n] == '/')
  3817. {
  3818. ++n;
  3819. }
  3820. c += n;
  3821. }
  3822. else
  3823. {
  3824. // Relative path.
  3825. if(root)
  3826. {
  3827. *root = "";
  3828. }
  3829. }
  3830. // Return the remaining path.
  3831. return c;
  3832. }
  3833. //----------------------------------------------------------------------------
  3834. void SystemTools::SplitPath(const std::string& p,
  3835. std::vector<std::string>& components,
  3836. bool expand_home_dir)
  3837. {
  3838. const char* c;
  3839. components.clear();
  3840. // Identify the root component.
  3841. {
  3842. std::string root;
  3843. c = SystemTools::SplitPathRootComponent(p, &root);
  3844. // Expand home directory references if requested.
  3845. if(expand_home_dir && !root.empty() && root[0] == '~')
  3846. {
  3847. std::string homedir;
  3848. root = root.substr(0, root.size()-1);
  3849. if(root.size() == 1)
  3850. {
  3851. #if defined(_WIN32) && !defined(__CYGWIN__)
  3852. if (!SystemTools::GetEnv("USERPROFILE", homedir))
  3853. #endif
  3854. SystemTools::GetEnv("HOME", homedir);
  3855. }
  3856. #ifdef HAVE_GETPWNAM
  3857. else if(passwd* pw = getpwnam(root.c_str()+1))
  3858. {
  3859. if(pw->pw_dir)
  3860. {
  3861. homedir = pw->pw_dir;
  3862. }
  3863. }
  3864. #endif
  3865. if(!homedir.empty() && (*homedir.rbegin() == '/' ||
  3866. *homedir.rbegin() == '\\'))
  3867. {
  3868. homedir.resize(homedir.size() - 1);
  3869. }
  3870. SystemTools::SplitPath(homedir, components);
  3871. }
  3872. else
  3873. {
  3874. components.push_back(root);
  3875. }
  3876. }
  3877. // Parse the remaining components.
  3878. const char* first = c;
  3879. const char* last = first;
  3880. for(;*last; ++last)
  3881. {
  3882. if(*last == '/' || *last == '\\')
  3883. {
  3884. // End of a component. Save it.
  3885. components.push_back(std::string(first, last));
  3886. first = last+1;
  3887. }
  3888. }
  3889. // Save the last component unless there were no components.
  3890. if(last != c)
  3891. {
  3892. components.push_back(std::string(first, last));
  3893. }
  3894. }
  3895. //----------------------------------------------------------------------------
  3896. std::string
  3897. SystemTools::JoinPath(const std::vector<std::string>& components)
  3898. {
  3899. return SystemTools::JoinPath(components.begin(), components.end());
  3900. }
  3901. //----------------------------------------------------------------------------
  3902. std::string
  3903. SystemTools
  3904. ::JoinPath(std::vector<std::string>::const_iterator first,
  3905. std::vector<std::string>::const_iterator last)
  3906. {
  3907. // Construct result in a single string.
  3908. std::string result;
  3909. size_t len = 0;
  3910. std::vector<std::string>::const_iterator i;
  3911. for(i = first; i != last; ++i)
  3912. {
  3913. len += 1 + i->size();
  3914. }
  3915. result.reserve(len);
  3916. // The first two components do not add a slash.
  3917. if(first != last)
  3918. {
  3919. result.append(*first++);
  3920. }
  3921. if(first != last)
  3922. {
  3923. result.append(*first++);
  3924. }
  3925. // All remaining components are always separated with a slash.
  3926. while(first != last)
  3927. {
  3928. result.append("/");
  3929. result.append((*first++));
  3930. }
  3931. // Return the concatenated result.
  3932. return result;
  3933. }
  3934. //----------------------------------------------------------------------------
  3935. bool SystemTools::ComparePath(const std::string& c1, const std::string& c2)
  3936. {
  3937. #if defined(_WIN32) || defined(__APPLE__)
  3938. # ifdef _MSC_VER
  3939. return _stricmp(c1.c_str(), c2.c_str()) == 0;
  3940. # elif defined(__APPLE__) || defined(__GNUC__)
  3941. return strcasecmp(c1.c_str(), c2.c_str()) == 0;
  3942. #else
  3943. return SystemTools::Strucmp(c1.c_str(), c2.c_str()) == 0;
  3944. # endif
  3945. #else
  3946. return c1 == c2;
  3947. #endif
  3948. }
  3949. //----------------------------------------------------------------------------
  3950. bool SystemTools::Split(const std::string& str, std::vector<std::string>& lines, char separator)
  3951. {
  3952. std::string data(str);
  3953. std::string::size_type lpos = 0;
  3954. while(lpos < data.length())
  3955. {
  3956. std::string::size_type rpos = data.find_first_of(separator, lpos);
  3957. if(rpos == std::string::npos)
  3958. {
  3959. // Line ends at end of string without a newline.
  3960. lines.push_back(data.substr(lpos));
  3961. return false;
  3962. }
  3963. else
  3964. {
  3965. // Line ends in a "\n", remove the character.
  3966. lines.push_back(data.substr(lpos, rpos-lpos));
  3967. }
  3968. lpos = rpos+1;
  3969. }
  3970. return true;
  3971. }
  3972. //----------------------------------------------------------------------------
  3973. bool SystemTools::Split(const std::string& str, std::vector<std::string>& lines)
  3974. {
  3975. std::string data(str);
  3976. std::string::size_type lpos = 0;
  3977. while(lpos < data.length())
  3978. {
  3979. std::string::size_type rpos = data.find_first_of("\n", lpos);
  3980. if(rpos == std::string::npos)
  3981. {
  3982. // Line ends at end of string without a newline.
  3983. lines.push_back(data.substr(lpos));
  3984. return false;
  3985. }
  3986. if((rpos > lpos) && (data[rpos-1] == '\r'))
  3987. {
  3988. // Line ends in a "\r\n" pair, remove both characters.
  3989. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  3990. }
  3991. else
  3992. {
  3993. // Line ends in a "\n", remove the character.
  3994. lines.push_back(data.substr(lpos, rpos-lpos));
  3995. }
  3996. lpos = rpos+1;
  3997. }
  3998. return true;
  3999. }
  4000. /**
  4001. * Return path of a full filename (no trailing slashes).
  4002. * Warning: returned path is converted to Unix slashes format.
  4003. */
  4004. std::string SystemTools::GetFilenamePath(const std::string& filename)
  4005. {
  4006. std::string fn = filename;
  4007. SystemTools::ConvertToUnixSlashes(fn);
  4008. std::string::size_type slash_pos = fn.rfind("/");
  4009. if(slash_pos != std::string::npos)
  4010. {
  4011. std::string ret = fn.substr(0, slash_pos);
  4012. if(ret.size() == 2 && ret[1] == ':')
  4013. {
  4014. return ret + '/';
  4015. }
  4016. if(ret.empty())
  4017. {
  4018. return "/";
  4019. }
  4020. return ret;
  4021. }
  4022. else
  4023. {
  4024. return "";
  4025. }
  4026. }
  4027. /**
  4028. * Return file name of a full filename (i.e. file name without path).
  4029. */
  4030. std::string SystemTools::GetFilenameName(const std::string& filename)
  4031. {
  4032. #if defined(_WIN32)
  4033. std::string::size_type slash_pos = filename.find_last_of("/\\");
  4034. #else
  4035. std::string::size_type slash_pos = filename.rfind('/');
  4036. #endif
  4037. if(slash_pos != std::string::npos)
  4038. {
  4039. return filename.substr(slash_pos + 1);
  4040. }
  4041. else
  4042. {
  4043. return filename;
  4044. }
  4045. }
  4046. /**
  4047. * Return file extension of a full filename (dot included).
  4048. * Warning: this is the longest extension (for example: .tar.gz)
  4049. */
  4050. std::string SystemTools::GetFilenameExtension(const std::string& filename)
  4051. {
  4052. std::string name = SystemTools::GetFilenameName(filename);
  4053. std::string::size_type dot_pos = name.find('.');
  4054. if(dot_pos != std::string::npos)
  4055. {
  4056. return name.substr(dot_pos);
  4057. }
  4058. else
  4059. {
  4060. return "";
  4061. }
  4062. }
  4063. /**
  4064. * Return file extension of a full filename (dot included).
  4065. * Warning: this is the shortest extension (for example: .gz of .tar.gz)
  4066. */
  4067. std::string SystemTools::GetFilenameLastExtension(const std::string& filename)
  4068. {
  4069. std::string name = SystemTools::GetFilenameName(filename);
  4070. std::string::size_type dot_pos = name.rfind('.');
  4071. if(dot_pos != std::string::npos)
  4072. {
  4073. return name.substr(dot_pos);
  4074. }
  4075. else
  4076. {
  4077. return "";
  4078. }
  4079. }
  4080. /**
  4081. * Return file name without extension of a full filename (i.e. without path).
  4082. * Warning: it considers the longest extension (for example: .tar.gz)
  4083. */
  4084. std::string SystemTools::GetFilenameWithoutExtension(const std::string& filename)
  4085. {
  4086. std::string name = SystemTools::GetFilenameName(filename);
  4087. std::string::size_type dot_pos = name.find('.');
  4088. if(dot_pos != std::string::npos)
  4089. {
  4090. return name.substr(0, dot_pos);
  4091. }
  4092. else
  4093. {
  4094. return name;
  4095. }
  4096. }
  4097. /**
  4098. * Return file name without extension of a full filename (i.e. without path).
  4099. * Warning: it considers the last extension (for example: removes .gz
  4100. * from .tar.gz)
  4101. */
  4102. std::string
  4103. SystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
  4104. {
  4105. std::string name = SystemTools::GetFilenameName(filename);
  4106. std::string::size_type dot_pos = name.rfind('.');
  4107. if(dot_pos != std::string::npos)
  4108. {
  4109. return name.substr(0, dot_pos);
  4110. }
  4111. else
  4112. {
  4113. return name;
  4114. }
  4115. }
  4116. bool SystemTools::FileHasSignature(const char *filename,
  4117. const char *signature,
  4118. long offset)
  4119. {
  4120. if (!filename || !signature)
  4121. {
  4122. return false;
  4123. }
  4124. FILE *fp = Fopen(filename, "rb");
  4125. if (!fp)
  4126. {
  4127. return false;
  4128. }
  4129. fseek(fp, offset, SEEK_SET);
  4130. bool res = false;
  4131. size_t signature_len = strlen(signature);
  4132. char *buffer = new char [signature_len];
  4133. if (fread(buffer, 1, signature_len, fp) == signature_len)
  4134. {
  4135. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  4136. }
  4137. delete [] buffer;
  4138. fclose(fp);
  4139. return res;
  4140. }
  4141. SystemTools::FileTypeEnum
  4142. SystemTools::DetectFileType(const char *filename,
  4143. unsigned long length,
  4144. double percent_bin)
  4145. {
  4146. if (!filename || percent_bin < 0)
  4147. {
  4148. return SystemTools::FileTypeUnknown;
  4149. }
  4150. if (SystemTools::FileIsDirectory(filename))
  4151. {
  4152. return SystemTools::FileTypeUnknown;
  4153. }
  4154. FILE *fp = Fopen(filename, "rb");
  4155. if (!fp)
  4156. {
  4157. return SystemTools::FileTypeUnknown;
  4158. }
  4159. // Allocate buffer and read bytes
  4160. unsigned char *buffer = new unsigned char [length];
  4161. size_t read_length = fread(buffer, 1, length, fp);
  4162. fclose(fp);
  4163. if (read_length == 0)
  4164. {
  4165. delete [] buffer;
  4166. return SystemTools::FileTypeUnknown;
  4167. }
  4168. // Loop over contents and count
  4169. size_t text_count = 0;
  4170. const unsigned char *ptr = buffer;
  4171. const unsigned char *buffer_end = buffer + read_length;
  4172. while (ptr != buffer_end)
  4173. {
  4174. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  4175. *ptr == '\n' ||
  4176. *ptr == '\r' ||
  4177. *ptr == '\t')
  4178. {
  4179. text_count++;
  4180. }
  4181. ptr++;
  4182. }
  4183. delete [] buffer;
  4184. double current_percent_bin =
  4185. (static_cast<double>(read_length - text_count) /
  4186. static_cast<double>(read_length));
  4187. if (current_percent_bin >= percent_bin)
  4188. {
  4189. return SystemTools::FileTypeBinary;
  4190. }
  4191. return SystemTools::FileTypeText;
  4192. }
  4193. bool SystemTools::LocateFileInDir(const char *filename,
  4194. const char *dir,
  4195. std::string& filename_found,
  4196. int try_filename_dirs)
  4197. {
  4198. if (!filename || !dir)
  4199. {
  4200. return false;
  4201. }
  4202. // Get the basename of 'filename'
  4203. std::string filename_base = SystemTools::GetFilenameName(filename);
  4204. // Check if 'dir' is really a directory
  4205. // If win32 and matches something like C:, accept it as a dir
  4206. std::string real_dir;
  4207. if (!SystemTools::FileIsDirectory(dir))
  4208. {
  4209. #if defined( _WIN32 )
  4210. size_t dir_len = strlen(dir);
  4211. if (dir_len < 2 || dir[dir_len - 1] != ':')
  4212. {
  4213. #endif
  4214. real_dir = SystemTools::GetFilenamePath(dir);
  4215. dir = real_dir.c_str();
  4216. #if defined( _WIN32 )
  4217. }
  4218. #endif
  4219. }
  4220. // Try to find the file in 'dir'
  4221. bool res = false;
  4222. if (!filename_base.empty() && dir)
  4223. {
  4224. size_t dir_len = strlen(dir);
  4225. int need_slash =
  4226. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  4227. std::string temp = dir;
  4228. if (need_slash)
  4229. {
  4230. temp += "/";
  4231. }
  4232. temp += filename_base;
  4233. if (SystemTools::FileExists(temp))
  4234. {
  4235. res = true;
  4236. filename_found = temp;
  4237. }
  4238. // If not found, we can try harder by appending part of the file to
  4239. // to the directory to look inside.
  4240. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  4241. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  4242. else if (try_filename_dirs)
  4243. {
  4244. std::string filename_dir(filename);
  4245. std::string filename_dir_base;
  4246. std::string filename_dir_bases;
  4247. do
  4248. {
  4249. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  4250. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  4251. #if defined( _WIN32 )
  4252. if (filename_dir_base.empty() ||
  4253. *filename_dir_base.rbegin() == ':')
  4254. #else
  4255. if (filename_dir_base.empty())
  4256. #endif
  4257. {
  4258. break;
  4259. }
  4260. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  4261. temp = dir;
  4262. if (need_slash)
  4263. {
  4264. temp += "/";
  4265. }
  4266. temp += filename_dir_bases;
  4267. res = SystemTools::LocateFileInDir(
  4268. filename_base.c_str(), temp.c_str(), filename_found, 0);
  4269. } while (!res && !filename_dir_base.empty());
  4270. }
  4271. }
  4272. return res;
  4273. }
  4274. bool SystemTools::FileIsFullPath(const std::string& in_name)
  4275. {
  4276. return SystemTools::FileIsFullPath(in_name.c_str(), in_name.size());
  4277. }
  4278. bool SystemTools::FileIsFullPath(const char* in_name)
  4279. {
  4280. return SystemTools::FileIsFullPath(in_name, in_name[0] ? (in_name[1] ? 2 : 1) : 0);
  4281. }
  4282. bool SystemTools::FileIsFullPath(const char* in_name, size_t len)
  4283. {
  4284. #if defined(_WIN32) || defined(__CYGWIN__)
  4285. // On Windows, the name must be at least two characters long.
  4286. if(len < 2)
  4287. {
  4288. return false;
  4289. }
  4290. if(in_name[1] == ':')
  4291. {
  4292. return true;
  4293. }
  4294. if(in_name[0] == '\\')
  4295. {
  4296. return true;
  4297. }
  4298. #else
  4299. // On UNIX, the name must be at least one character long.
  4300. if(len < 1)
  4301. {
  4302. return false;
  4303. }
  4304. #endif
  4305. #if !defined(_WIN32)
  4306. if(in_name[0] == '~')
  4307. {
  4308. return true;
  4309. }
  4310. #endif
  4311. // On UNIX, the name must begin in a '/'.
  4312. // On Windows, if the name begins in a '/', then it is a full
  4313. // network path.
  4314. if(in_name[0] == '/')
  4315. {
  4316. return true;
  4317. }
  4318. return false;
  4319. }
  4320. bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath)
  4321. {
  4322. #if defined(_WIN32) && !defined(__CYGWIN__)
  4323. std::string tempPath = path; // create a buffer
  4324. // if the path passed in has quotes around it, first remove the quotes
  4325. if (!path.empty() && path[0] == '"' && *path.rbegin() == '"')
  4326. {
  4327. tempPath = path.substr(1, path.length()-2);
  4328. }
  4329. std::wstring wtempPath = Encoding::ToWide(tempPath);
  4330. DWORD ret = GetShortPathNameW(wtempPath.c_str(), NULL, 0);
  4331. std::vector<wchar_t> buffer(ret);
  4332. if (ret != 0)
  4333. {
  4334. ret = GetShortPathNameW(wtempPath.c_str(),
  4335. &buffer[0], static_cast<DWORD>(buffer.size()));
  4336. }
  4337. if (ret == 0)
  4338. {
  4339. return false;
  4340. }
  4341. else
  4342. {
  4343. shortPath = Encoding::ToNarrow(&buffer[0]);
  4344. return true;
  4345. }
  4346. #else
  4347. shortPath = path;
  4348. return true;
  4349. #endif
  4350. }
  4351. void SystemTools::SplitProgramFromArgs(const std::string& path,
  4352. std::string& program, std::string& args)
  4353. {
  4354. // see if this is a full path to a program
  4355. // if so then set program to path and args to nothing
  4356. if(SystemTools::FileExists(path))
  4357. {
  4358. program = path;
  4359. args = "";
  4360. return;
  4361. }
  4362. // Try to find the program in the path, note the program
  4363. // may have spaces in its name so we have to look for it
  4364. std::vector<std::string> e;
  4365. std::string findProg = SystemTools::FindProgram(path, e);
  4366. if(!findProg.empty())
  4367. {
  4368. program = findProg;
  4369. args = "";
  4370. return;
  4371. }
  4372. // Now try and peel off space separated chunks from the end of the string
  4373. // so the largest path possible is found allowing for spaces in the path
  4374. std::string dir = path;
  4375. std::string::size_type spacePos = dir.rfind(' ');
  4376. while(spacePos != std::string::npos)
  4377. {
  4378. std::string tryProg = dir.substr(0, spacePos);
  4379. // See if the file exists
  4380. if(SystemTools::FileExists(tryProg))
  4381. {
  4382. program = tryProg;
  4383. // remove trailing spaces from program
  4384. std::string::size_type pos = program.size()-1;
  4385. while(program[pos] == ' ')
  4386. {
  4387. program.erase(pos);
  4388. pos--;
  4389. }
  4390. args = dir.substr(spacePos, dir.size()-spacePos);
  4391. return;
  4392. }
  4393. // Now try and find the program in the path
  4394. findProg = SystemTools::FindProgram(tryProg, e);
  4395. if(!findProg.empty())
  4396. {
  4397. program = findProg;
  4398. // remove trailing spaces from program
  4399. std::string::size_type pos = program.size()-1;
  4400. while(program[pos] == ' ')
  4401. {
  4402. program.erase(pos);
  4403. pos--;
  4404. }
  4405. args = dir.substr(spacePos, dir.size()-spacePos);
  4406. return;
  4407. }
  4408. // move past the space for the next search
  4409. spacePos--;
  4410. spacePos = dir.rfind(' ', spacePos);
  4411. }
  4412. program = "";
  4413. args = "";
  4414. }
  4415. std::string SystemTools::GetCurrentDateTime(const char* format)
  4416. {
  4417. char buf[1024];
  4418. time_t t;
  4419. time(&t);
  4420. strftime(buf, sizeof(buf), format, localtime(&t));
  4421. return std::string(buf);
  4422. }
  4423. std::string SystemTools::MakeCidentifier(const std::string& s)
  4424. {
  4425. std::string str(s);
  4426. if (str.find_first_of("0123456789") == 0)
  4427. {
  4428. str = "_" + str;
  4429. }
  4430. std::string permited_chars("_"
  4431. "abcdefghijklmnopqrstuvwxyz"
  4432. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  4433. "0123456789");
  4434. std::string::size_type pos = 0;
  4435. while ((pos = str.find_first_not_of(permited_chars, pos)) != std::string::npos)
  4436. {
  4437. str[pos] = '_';
  4438. }
  4439. return str;
  4440. }
  4441. // Due to a buggy stream library on the HP and another on Mac OS X, we
  4442. // need this very carefully written version of getline. Returns true
  4443. // if any data were read before the end-of-file was reached.
  4444. bool SystemTools::GetLineFromStream(std::istream& is,
  4445. std::string& line,
  4446. bool* has_newline /* = 0 */,
  4447. long sizeLimit /* = -1 */)
  4448. {
  4449. const int bufferSize = 1024;
  4450. char buffer[bufferSize];
  4451. bool haveData = false;
  4452. bool haveNewline = false;
  4453. // Start with an empty line.
  4454. line = "";
  4455. long leftToRead = sizeLimit;
  4456. // Early short circuit return if stream is no good. Just return
  4457. // false and the empty line. (Probably means caller tried to
  4458. // create a file stream with a non-existent file name...)
  4459. //
  4460. if(!is)
  4461. {
  4462. if(has_newline)
  4463. {
  4464. *has_newline = false;
  4465. }
  4466. return false;
  4467. }
  4468. // If no characters are read from the stream, the end of file has
  4469. // been reached. Clear the fail bit just before reading.
  4470. while(!haveNewline &&
  4471. leftToRead != 0 &&
  4472. (static_cast<void>(is.clear(is.rdstate() & ~std::ios::failbit)),
  4473. static_cast<void>(is.getline(buffer, bufferSize)),
  4474. is.gcount() > 0))
  4475. {
  4476. // We have read at least one byte.
  4477. haveData = true;
  4478. // If newline character was read the gcount includes the character
  4479. // but the buffer does not: the end of line has been reached.
  4480. size_t length = strlen(buffer);
  4481. if(length < static_cast<size_t>(is.gcount()))
  4482. {
  4483. haveNewline = true;
  4484. }
  4485. // Avoid storing a carriage return character.
  4486. if(length > 0 && buffer[length-1] == '\r')
  4487. {
  4488. buffer[length-1] = 0;
  4489. }
  4490. // if we read too much then truncate the buffer
  4491. if (leftToRead > 0)
  4492. {
  4493. if (static_cast<long>(length) > leftToRead)
  4494. {
  4495. buffer[leftToRead-1] = 0;
  4496. leftToRead = 0;
  4497. }
  4498. else
  4499. {
  4500. leftToRead -= static_cast<long>(length);
  4501. }
  4502. }
  4503. // Append the data read to the line.
  4504. line.append(buffer);
  4505. }
  4506. // Return the results.
  4507. if(has_newline)
  4508. {
  4509. *has_newline = haveNewline;
  4510. }
  4511. return haveData;
  4512. }
  4513. int SystemTools::GetTerminalWidth()
  4514. {
  4515. int width = -1;
  4516. #ifdef HAVE_TTY_INFO
  4517. struct winsize ws;
  4518. std::string columns; /* Unix98 environment variable */
  4519. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  4520. {
  4521. width = ws.ws_col;
  4522. }
  4523. if(!isatty(STDOUT_FILENO))
  4524. {
  4525. width = -1;
  4526. }
  4527. if(SystemTools::GetEnv("COLUMNS", columns) && !columns.empty())
  4528. {
  4529. long t;
  4530. char *endptr;
  4531. t = strtol(columns.c_str(), &endptr, 0);
  4532. if(endptr && !*endptr && (t>0) && (t<1000))
  4533. {
  4534. width = static_cast<int>(t);
  4535. }
  4536. }
  4537. if ( width < 9 )
  4538. {
  4539. width = -1;
  4540. }
  4541. #endif
  4542. return width;
  4543. }
  4544. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  4545. {
  4546. if ( !file )
  4547. {
  4548. return false;
  4549. }
  4550. return SystemTools::GetPermissions(std::string(file), mode);
  4551. }
  4552. bool SystemTools::GetPermissions(const std::string& file, mode_t& mode)
  4553. {
  4554. #if defined(_WIN32)
  4555. DWORD attr = GetFileAttributesW(
  4556. SystemTools::ConvertToWindowsExtendedPath(file).c_str());
  4557. if(attr == INVALID_FILE_ATTRIBUTES)
  4558. {
  4559. return false;
  4560. }
  4561. if((attr & FILE_ATTRIBUTE_READONLY) != 0)
  4562. {
  4563. mode = (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
  4564. }
  4565. else
  4566. {
  4567. mode = (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6)) |
  4568. (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
  4569. }
  4570. if((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
  4571. {
  4572. mode |= S_IFDIR | (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
  4573. }
  4574. else
  4575. {
  4576. mode |= S_IFREG;
  4577. }
  4578. size_t dotPos = file.rfind('.');
  4579. const char* ext = dotPos == file.npos ? 0 : (file.c_str() + dotPos);
  4580. if(ext && (Strucmp(ext, ".exe") == 0 ||
  4581. Strucmp(ext, ".com") == 0 ||
  4582. Strucmp(ext, ".cmd") == 0 ||
  4583. Strucmp(ext, ".bat") == 0))
  4584. {
  4585. mode |= (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
  4586. }
  4587. #else
  4588. struct stat st;
  4589. if ( stat(file.c_str(), &st) < 0 )
  4590. {
  4591. return false;
  4592. }
  4593. mode = st.st_mode;
  4594. #endif
  4595. return true;
  4596. }
  4597. bool SystemTools::SetPermissions(const char* file,
  4598. mode_t mode,
  4599. bool honor_umask)
  4600. {
  4601. if ( !file )
  4602. {
  4603. return false;
  4604. }
  4605. return SystemTools::SetPermissions(
  4606. std::string(file), mode, honor_umask);
  4607. }
  4608. bool SystemTools::SetPermissions(const std::string& file,
  4609. mode_t mode,
  4610. bool honor_umask)
  4611. {
  4612. // TEMPORARY / TODO: After FileExists calls lstat() instead of
  4613. // access(), change this call to FileExists instead of
  4614. // TestFileAccess so that we don't follow symlinks.
  4615. if ( !SystemTools::TestFileAccess(file, TEST_FILE_OK) )
  4616. {
  4617. return false;
  4618. }
  4619. if (honor_umask)
  4620. {
  4621. mode_t currentMask = umask(0);
  4622. umask(currentMask);
  4623. mode &= ~currentMask;
  4624. }
  4625. #ifdef _WIN32
  4626. if ( _wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
  4627. mode) < 0 )
  4628. #else
  4629. if ( chmod(file.c_str(), mode) < 0 )
  4630. #endif
  4631. {
  4632. return false;
  4633. }
  4634. return true;
  4635. }
  4636. std::string SystemTools::GetParentDirectory(const std::string& fileOrDir)
  4637. {
  4638. return SystemTools::GetFilenamePath(fileOrDir);
  4639. }
  4640. bool SystemTools::IsSubDirectory(const std::string& cSubdir, const std::string& cDir)
  4641. {
  4642. if(cDir.empty())
  4643. {
  4644. return false;
  4645. }
  4646. std::string subdir = cSubdir;
  4647. std::string dir = cDir;
  4648. SystemTools::ConvertToUnixSlashes(subdir);
  4649. SystemTools::ConvertToUnixSlashes(dir);
  4650. if(subdir.size() > dir.size() && subdir[dir.size()] == '/')
  4651. {
  4652. std::string s = subdir.substr(0, dir.size());
  4653. return SystemTools::ComparePath(s, dir);
  4654. }
  4655. return false;
  4656. }
  4657. void SystemTools::Delay(unsigned int msec)
  4658. {
  4659. #ifdef _WIN32
  4660. Sleep(msec);
  4661. #else
  4662. // The sleep function gives 1 second resolution and the usleep
  4663. // function gives 1e-6 second resolution but on some platforms has a
  4664. // maximum sleep time of 1 second. This could be re-implemented to
  4665. // use select with masked signals or pselect to mask signals
  4666. // atomically. If select is given empty sets and zero as the max
  4667. // file descriptor but a non-zero timeout it can be used to block
  4668. // for a precise amount of time.
  4669. if(msec >= 1000)
  4670. {
  4671. sleep(msec / 1000);
  4672. usleep((msec % 1000) * 1000);
  4673. }
  4674. else
  4675. {
  4676. usleep(msec * 1000);
  4677. }
  4678. #endif
  4679. }
  4680. std::string SystemTools::GetOperatingSystemNameAndVersion()
  4681. {
  4682. std::string res;
  4683. #ifdef _WIN32
  4684. char buffer[256];
  4685. OSVERSIONINFOEXA osvi;
  4686. BOOL bOsVersionInfoEx;
  4687. ZeroMemory(&osvi, sizeof(osvi));
  4688. osvi.dwOSVersionInfoSize = sizeof(osvi);
  4689. #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  4690. # pragma warning (push)
  4691. # ifdef __INTEL_COMPILER
  4692. # pragma warning (disable:1478)
  4693. # else
  4694. # pragma warning (disable:4996)
  4695. # endif
  4696. #endif
  4697. bOsVersionInfoEx = GetVersionExA((OSVERSIONINFOA *)&osvi);
  4698. if (!bOsVersionInfoEx)
  4699. {
  4700. return 0;
  4701. }
  4702. #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  4703. # pragma warning (pop)
  4704. #endif
  4705. switch (osvi.dwPlatformId)
  4706. {
  4707. // Test for the Windows NT product family.
  4708. case VER_PLATFORM_WIN32_NT:
  4709. // Test for the specific product family.
  4710. if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0)
  4711. {
  4712. if (osvi.wProductType == VER_NT_WORKSTATION)
  4713. {
  4714. res += "Microsoft Windows 10";
  4715. }
  4716. else
  4717. {
  4718. res += "Microsoft Windows Server 2016 family";
  4719. }
  4720. }
  4721. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3)
  4722. {
  4723. if (osvi.wProductType == VER_NT_WORKSTATION)
  4724. {
  4725. res += "Microsoft Windows 8.1";
  4726. }
  4727. else
  4728. {
  4729. res += "Microsoft Windows Server 2012 R2 family";
  4730. }
  4731. }
  4732. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2)
  4733. {
  4734. if (osvi.wProductType == VER_NT_WORKSTATION)
  4735. {
  4736. res += "Microsoft Windows 8";
  4737. }
  4738. else
  4739. {
  4740. res += "Microsoft Windows Server 2012 family";
  4741. }
  4742. }
  4743. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
  4744. {
  4745. if (osvi.wProductType == VER_NT_WORKSTATION)
  4746. {
  4747. res += "Microsoft Windows 7";
  4748. }
  4749. else
  4750. {
  4751. res += "Microsoft Windows Server 2008 R2 family";
  4752. }
  4753. }
  4754. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
  4755. {
  4756. if (osvi.wProductType == VER_NT_WORKSTATION)
  4757. {
  4758. res += "Microsoft Windows Vista";
  4759. }
  4760. else
  4761. {
  4762. res += "Microsoft Windows Server 2008 family";
  4763. }
  4764. }
  4765. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  4766. {
  4767. res += "Microsoft Windows Server 2003 family";
  4768. }
  4769. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4770. {
  4771. res += "Microsoft Windows XP";
  4772. }
  4773. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  4774. {
  4775. res += "Microsoft Windows 2000";
  4776. }
  4777. if (osvi.dwMajorVersion <= 4)
  4778. {
  4779. res += "Microsoft Windows NT";
  4780. }
  4781. // Test for specific product on Windows NT 4.0 SP6 and later.
  4782. if (bOsVersionInfoEx)
  4783. {
  4784. // Test for the workstation type.
  4785. if (osvi.wProductType == VER_NT_WORKSTATION)
  4786. {
  4787. if (osvi.dwMajorVersion == 4)
  4788. {
  4789. res += " Workstation 4.0";
  4790. }
  4791. else if (osvi.dwMajorVersion == 5)
  4792. {
  4793. if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  4794. {
  4795. res += " Home Edition";
  4796. }
  4797. else
  4798. {
  4799. res += " Professional";
  4800. }
  4801. }
  4802. }
  4803. // Test for the server type.
  4804. else if (osvi.wProductType == VER_NT_SERVER)
  4805. {
  4806. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  4807. {
  4808. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  4809. {
  4810. res += " Datacenter Edition";
  4811. }
  4812. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4813. {
  4814. res += " Enterprise Edition";
  4815. }
  4816. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  4817. {
  4818. res += " Web Edition";
  4819. }
  4820. else
  4821. {
  4822. res += " Standard Edition";
  4823. }
  4824. }
  4825. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  4826. {
  4827. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  4828. {
  4829. res += " Datacenter Server";
  4830. }
  4831. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4832. {
  4833. res += " Advanced Server";
  4834. }
  4835. else
  4836. {
  4837. res += " Server";
  4838. }
  4839. }
  4840. else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
  4841. {
  4842. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4843. {
  4844. res += " Server 4.0, Enterprise Edition";
  4845. }
  4846. else
  4847. {
  4848. res += " Server 4.0";
  4849. }
  4850. }
  4851. }
  4852. }
  4853. // Test for specific product on Windows NT 4.0 SP5 and earlier
  4854. else
  4855. {
  4856. HKEY hKey;
  4857. #define BUFSIZE 80
  4858. wchar_t szProductType[BUFSIZE];
  4859. DWORD dwBufLen=BUFSIZE;
  4860. LONG lRet;
  4861. lRet = RegOpenKeyExW(
  4862. HKEY_LOCAL_MACHINE,
  4863. L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  4864. 0, KEY_QUERY_VALUE, &hKey);
  4865. if (lRet != ERROR_SUCCESS)
  4866. {
  4867. return 0;
  4868. }
  4869. lRet = RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
  4870. (LPBYTE) szProductType, &dwBufLen);
  4871. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  4872. {
  4873. return 0;
  4874. }
  4875. RegCloseKey(hKey);
  4876. if (lstrcmpiW(L"WINNT", szProductType) == 0)
  4877. {
  4878. res += " Workstation";
  4879. }
  4880. if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
  4881. {
  4882. res += " Server";
  4883. }
  4884. if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
  4885. {
  4886. res += " Advanced Server";
  4887. }
  4888. res += " ";
  4889. sprintf(buffer, "%ld", osvi.dwMajorVersion);
  4890. res += buffer;
  4891. res += ".";
  4892. sprintf(buffer, "%ld", osvi.dwMinorVersion);
  4893. res += buffer;
  4894. }
  4895. // Display service pack (if any) and build number.
  4896. if (osvi.dwMajorVersion == 4 &&
  4897. lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0)
  4898. {
  4899. HKEY hKey;
  4900. LONG lRet;
  4901. // Test for SP6 versus SP6a.
  4902. lRet = RegOpenKeyExW(
  4903. HKEY_LOCAL_MACHINE,
  4904. L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  4905. 0, KEY_QUERY_VALUE, &hKey);
  4906. if (lRet == ERROR_SUCCESS)
  4907. {
  4908. res += " Service Pack 6a (Build ";
  4909. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4910. res += buffer;
  4911. res += ")";
  4912. }
  4913. else // Windows NT 4.0 prior to SP6a
  4914. {
  4915. res += " ";
  4916. res += osvi.szCSDVersion;
  4917. res += " (Build ";
  4918. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4919. res += buffer;
  4920. res += ")";
  4921. }
  4922. RegCloseKey(hKey);
  4923. }
  4924. else // Windows NT 3.51 and earlier or Windows 2000 and later
  4925. {
  4926. res += " ";
  4927. res += osvi.szCSDVersion;
  4928. res += " (Build ";
  4929. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4930. res += buffer;
  4931. res += ")";
  4932. }
  4933. break;
  4934. // Test for the Windows 95 product family.
  4935. case VER_PLATFORM_WIN32_WINDOWS:
  4936. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  4937. {
  4938. res += "Microsoft Windows 95";
  4939. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  4940. {
  4941. res += " OSR2";
  4942. }
  4943. }
  4944. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  4945. {
  4946. res += "Microsoft Windows 98";
  4947. if (osvi.szCSDVersion[1] == 'A')
  4948. {
  4949. res += " SE";
  4950. }
  4951. }
  4952. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  4953. {
  4954. res += "Microsoft Windows Millennium Edition";
  4955. }
  4956. break;
  4957. case VER_PLATFORM_WIN32s:
  4958. res += "Microsoft Win32s";
  4959. break;
  4960. }
  4961. #endif
  4962. return res;
  4963. }
  4964. // ----------------------------------------------------------------------
  4965. bool SystemTools::ParseURLProtocol( const std::string& URL,
  4966. std::string& protocol,
  4967. std::string& dataglom )
  4968. {
  4969. // match 0 entire url
  4970. // match 1 protocol
  4971. // match 2 dataglom following protocol://
  4972. kwsys::RegularExpression urlRe( VTK_URL_PROTOCOL_REGEX );
  4973. if ( ! urlRe.find( URL ) ) return false;
  4974. protocol = urlRe.match( 1 );
  4975. dataglom = urlRe.match( 2 );
  4976. return true;
  4977. }
  4978. // ----------------------------------------------------------------------
  4979. bool SystemTools::ParseURL( const std::string& URL,
  4980. std::string& protocol,
  4981. std::string& username,
  4982. std::string& password,
  4983. std::string& hostname,
  4984. std::string& dataport,
  4985. std::string& database )
  4986. {
  4987. kwsys::RegularExpression urlRe( VTK_URL_REGEX );
  4988. if ( ! urlRe.find( URL ) ) return false;
  4989. // match 0 URL
  4990. // match 1 protocol
  4991. // match 2 mangled user
  4992. // match 3 username
  4993. // match 4 mangled password
  4994. // match 5 password
  4995. // match 6 hostname
  4996. // match 7 mangled port
  4997. // match 8 dataport
  4998. // match 9 database name
  4999. protocol = urlRe.match( 1 );
  5000. username = urlRe.match( 3 );
  5001. password = urlRe.match( 5 );
  5002. hostname = urlRe.match( 6 );
  5003. dataport = urlRe.match( 8 );
  5004. database = urlRe.match( 9 );
  5005. return true;
  5006. }
  5007. // ----------------------------------------------------------------------
  5008. // These must NOT be initialized. Default initialization to zero is
  5009. // necessary.
  5010. static unsigned int SystemToolsManagerCount;
  5011. SystemToolsTranslationMap *SystemTools::TranslationMap;
  5012. #ifdef _WIN32
  5013. SystemToolsPathCaseMap *SystemTools::PathCaseMap;
  5014. SystemToolsEnvMap *SystemTools::EnvMap;
  5015. #endif
  5016. #ifdef __CYGWIN__
  5017. SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
  5018. #endif
  5019. // SystemToolsManager manages the SystemTools singleton.
  5020. // SystemToolsManager should be included in any translation unit
  5021. // that will use SystemTools or that implements the singleton
  5022. // pattern. It makes sure that the SystemTools singleton is created
  5023. // before and destroyed after all other singletons in CMake.
  5024. SystemToolsManager::SystemToolsManager()
  5025. {
  5026. if(++SystemToolsManagerCount == 1)
  5027. {
  5028. SystemTools::ClassInitialize();
  5029. }
  5030. }
  5031. SystemToolsManager::~SystemToolsManager()
  5032. {
  5033. if(--SystemToolsManagerCount == 0)
  5034. {
  5035. SystemTools::ClassFinalize();
  5036. }
  5037. }
  5038. #if defined(__VMS)
  5039. // On VMS we configure the run time C library to be more UNIX like.
  5040. // http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html
  5041. extern "C" int decc$feature_get_index(char *name);
  5042. extern "C" int decc$feature_set_value(int index, int mode, int value);
  5043. static int SetVMSFeature(char* name, int value)
  5044. {
  5045. int i;
  5046. errno = 0;
  5047. i = decc$feature_get_index(name);
  5048. return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
  5049. }
  5050. #endif
  5051. void SystemTools::ClassInitialize()
  5052. {
  5053. #ifdef __VMS
  5054. SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1);
  5055. #endif
  5056. // Allocate the translation map first.
  5057. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  5058. #ifdef _WIN32
  5059. SystemTools::PathCaseMap = new SystemToolsPathCaseMap;
  5060. SystemTools::EnvMap = new SystemToolsEnvMap;
  5061. #endif
  5062. #ifdef __CYGWIN__
  5063. SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
  5064. #endif
  5065. // Add some special translation paths for unix. These are not added
  5066. // for windows because drive letters need to be maintained. Also,
  5067. // there are not sym-links and mount points on windows anyway.
  5068. #if !defined(_WIN32) || defined(__CYGWIN__)
  5069. // The tmp path is frequently a logical path so always keep it:
  5070. SystemTools::AddKeepPath("/tmp/");
  5071. // If the current working directory is a logical path then keep the
  5072. // logical name.
  5073. std::string pwd_str;
  5074. if(SystemTools::GetEnv("PWD", pwd_str))
  5075. {
  5076. char buf[2048];
  5077. if(const char* cwd = Getcwd(buf, 2048))
  5078. {
  5079. // The current working directory may be a logical path. Find
  5080. // the shortest logical path that still produces the correct
  5081. // physical path.
  5082. std::string cwd_changed;
  5083. std::string pwd_changed;
  5084. // Test progressively shorter logical-to-physical mappings.
  5085. std::string cwd_str = cwd;
  5086. std::string pwd_path;
  5087. Realpath(pwd_str.c_str(), pwd_path);
  5088. while(cwd_str == pwd_path && cwd_str != pwd_str)
  5089. {
  5090. // The current pair of paths is a working logical mapping.
  5091. cwd_changed = cwd_str;
  5092. pwd_changed = pwd_str;
  5093. // Strip off one directory level and see if the logical
  5094. // mapping still works.
  5095. pwd_str = SystemTools::GetFilenamePath(pwd_str);
  5096. cwd_str = SystemTools::GetFilenamePath(cwd_str);
  5097. Realpath(pwd_str.c_str(), pwd_path);
  5098. }
  5099. // Add the translation to keep the logical path name.
  5100. if(!cwd_changed.empty() && !pwd_changed.empty())
  5101. {
  5102. SystemTools::AddTranslationPath(cwd_changed,
  5103. pwd_changed);
  5104. }
  5105. }
  5106. }
  5107. #endif
  5108. }
  5109. void SystemTools::ClassFinalize()
  5110. {
  5111. delete SystemTools::TranslationMap;
  5112. #ifdef _WIN32
  5113. delete SystemTools::PathCaseMap;
  5114. delete SystemTools::EnvMap;
  5115. #endif
  5116. #ifdef __CYGWIN__
  5117. delete SystemTools::Cyg2Win32Map;
  5118. #endif
  5119. }
  5120. } // namespace KWSYS_NAMESPACE
  5121. #if defined(_MSC_VER) && defined(_DEBUG)
  5122. # include <crtdbg.h>
  5123. # include <stdio.h>
  5124. # include <stdlib.h>
  5125. namespace KWSYS_NAMESPACE
  5126. {
  5127. static int SystemToolsDebugReport(int, char* message, int*)
  5128. {
  5129. fprintf(stderr, "%s", message);
  5130. fflush(stderr);
  5131. return 1; // no further reporting required
  5132. }
  5133. void SystemTools::EnableMSVCDebugHook()
  5134. {
  5135. if (SystemTools::HasEnv("DART_TEST_FROM_DART") ||
  5136. SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST"))
  5137. {
  5138. _CrtSetReportHook(SystemToolsDebugReport);
  5139. }
  5140. }
  5141. } // namespace KWSYS_NAMESPACE
  5142. #else
  5143. namespace KWSYS_NAMESPACE
  5144. {
  5145. void SystemTools::EnableMSVCDebugHook() {}
  5146. } // namespace KWSYS_NAMESPACE
  5147. #endif