SystemTools.cxx 134 KB

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