SystemTools.cxx 140 KB

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