SystemTools.cxx 103 KB

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