SystemTools.cxx 115 KB

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