SystemTools.cxx 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323
  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. // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
  57. // same for TIOCGWINSZ
  58. #if defined(_WIN32) || defined (__LIBCATAMOUNT__)
  59. # undef HAVE_GETPWNAM
  60. # undef HAVE_TTY_INFO
  61. #else
  62. # define HAVE_GETPWNAM 1
  63. # define HAVE_TTY_INFO 1
  64. #endif
  65. // This is a hack to prevent warnings about these functions being
  66. // declared but not referenced.
  67. #if defined(__sgi) && !defined(__GNUC__)
  68. # include <sys/termios.h>
  69. namespace KWSYS_NAMESPACE
  70. {
  71. class SystemToolsHack
  72. {
  73. public:
  74. enum
  75. {
  76. Ref1 = sizeof(cfgetospeed(0)),
  77. Ref2 = sizeof(cfgetispeed(0)),
  78. Ref3 = sizeof(tcgetattr(0, 0)),
  79. Ref4 = sizeof(tcsetattr(0, 0, 0)),
  80. Ref5 = sizeof(cfsetospeed(0,0)),
  81. Ref6 = sizeof(cfsetispeed(0,0))
  82. };
  83. };
  84. }
  85. #endif
  86. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
  87. #include <io.h>
  88. #include <direct.h>
  89. #define _unlink unlink
  90. #endif
  91. /* The maximum length of a file name. */
  92. #if defined(PATH_MAX)
  93. # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
  94. #elif defined(MAXPATHLEN)
  95. # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
  96. #else
  97. # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
  98. #endif
  99. #if defined(__WATCOMC__)
  100. #include <direct.h>
  101. #define _mkdir mkdir
  102. #define _rmdir rmdir
  103. #define _getcwd getcwd
  104. #define _chdir chdir
  105. #endif
  106. #if defined(__BEOS__) && !defined(__ZETA__)
  107. #include <be/kernel/OS.h>
  108. #include <be/storage/Path.h>
  109. // BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
  110. static inline void usleep(unsigned int msec)
  111. {
  112. ::snooze(msec);
  113. }
  114. // BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
  115. static inline char *realpath(const char *path, char *resolved_path)
  116. {
  117. const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
  118. snprintf(resolved_path, maxlen, "%s", path);
  119. BPath normalized(resolved_path, NULL, true);
  120. const char *resolved = normalized.Path();
  121. if (resolved != NULL) // NULL == No such file.
  122. {
  123. if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
  124. {
  125. return resolved_path;
  126. }
  127. }
  128. return NULL; // something went wrong.
  129. }
  130. #endif
  131. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
  132. inline int Mkdir(const char* dir)
  133. {
  134. return _mkdir(dir);
  135. }
  136. inline int Rmdir(const char* dir)
  137. {
  138. return _rmdir(dir);
  139. }
  140. inline const char* Getcwd(char* buf, unsigned int len)
  141. {
  142. const char* ret = _getcwd(buf, len);
  143. if(!ret)
  144. {
  145. fprintf(stderr, "No current working directory.\n");
  146. abort();
  147. }
  148. // make sure the drive letter is capital
  149. if(strlen(buf) > 1 && buf[1] == ':')
  150. {
  151. buf[0] = toupper(buf[0]);
  152. }
  153. return ret;
  154. }
  155. inline int Chdir(const char* dir)
  156. {
  157. #if defined(__BORLANDC__)
  158. return chdir(dir);
  159. #else
  160. return _chdir(dir);
  161. #endif
  162. }
  163. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  164. {
  165. char *ptemp;
  166. char fullpath[MAX_PATH];
  167. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  168. {
  169. resolved_path = fullpath;
  170. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  171. }
  172. }
  173. #else
  174. #include <sys/types.h>
  175. #include <fcntl.h>
  176. #include <unistd.h>
  177. inline int Mkdir(const char* dir)
  178. {
  179. return mkdir(dir, 00777);
  180. }
  181. inline int Rmdir(const char* dir)
  182. {
  183. return rmdir(dir);
  184. }
  185. inline const char* Getcwd(char* buf, unsigned int len)
  186. {
  187. const char* ret = getcwd(buf, len);
  188. if(!ret)
  189. {
  190. fprintf(stderr, "No current working directory\n");
  191. abort();
  192. }
  193. return ret;
  194. }
  195. inline int Chdir(const char* dir)
  196. {
  197. return chdir(dir);
  198. }
  199. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  200. {
  201. char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
  202. realpath(path, resolved_name);
  203. resolved_path = resolved_name;
  204. }
  205. #endif
  206. #if !defined(_WIN32) && defined(__COMO__)
  207. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  208. extern "C"
  209. {
  210. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  211. extern int pclose (FILE *__stream) __THROW;
  212. extern char *realpath (__const char *__restrict __name,
  213. char *__restrict __resolved) __THROW;
  214. extern char *strdup (__const char *__s) __THROW;
  215. extern int putenv (char *__string) __THROW;
  216. }
  217. #endif
  218. /* Implement floattime() for various platforms */
  219. // Taken from Python 2.1.3
  220. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  221. # include <sys/timeb.h>
  222. # define HAVE_FTIME
  223. # if defined( __BORLANDC__)
  224. # define FTIME ftime
  225. # define TIMEB timeb
  226. # else // Visual studio?
  227. # define FTIME _ftime
  228. # define TIMEB _timeb
  229. # endif
  230. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  231. # include <sys/time.h>
  232. # include <time.h>
  233. # define HAVE_GETTIMEOFDAY
  234. #endif
  235. namespace KWSYS_NAMESPACE
  236. {
  237. class SystemToolsTranslationMap :
  238. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  239. {
  240. };
  241. double
  242. SystemTools::GetTime(void)
  243. {
  244. /* There are three ways to get the time:
  245. (1) gettimeofday() -- resolution in microseconds
  246. (2) ftime() -- resolution in milliseconds
  247. (3) time() -- resolution in seconds
  248. In all cases the return value is a float in seconds.
  249. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  250. fail, so we fall back on ftime() or time().
  251. Note: clock resolution does not imply clock accuracy! */
  252. #ifdef HAVE_GETTIMEOFDAY
  253. {
  254. struct timeval t;
  255. #ifdef GETTIMEOFDAY_NO_TZ
  256. if (gettimeofday(&t) == 0)
  257. return static_cast<double>(t.tv_sec) + t.tv_usec*0.000001;
  258. #else /* !GETTIMEOFDAY_NO_TZ */
  259. if (gettimeofday(&t, static_cast<struct timezone *>(NULL)) == 0)
  260. return static_cast<double>(t.tv_sec) + t.tv_usec*0.000001;
  261. #endif /* !GETTIMEOFDAY_NO_TZ */
  262. }
  263. #endif /* !HAVE_GETTIMEOFDAY */
  264. {
  265. #if defined(HAVE_FTIME)
  266. struct TIMEB t;
  267. ::FTIME(&t);
  268. return static_cast<double>(t.time) +
  269. static_cast<double>(t.millitm) * static_cast<double>(0.001);
  270. #else /* !HAVE_FTIME */
  271. time_t secs;
  272. time(&secs);
  273. return static_cast<double>(secs);
  274. #endif /* !HAVE_FTIME */
  275. }
  276. }
  277. // adds the elements of the env variable path to the arg passed in
  278. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  279. {
  280. #if defined(_WIN32) && !defined(__CYGWIN__)
  281. const char* pathSep = ";";
  282. #else
  283. const char* pathSep = ":";
  284. #endif
  285. if(!env)
  286. {
  287. env = "PATH";
  288. }
  289. const char* cpathEnv = SystemTools::GetEnv(env);
  290. if ( !cpathEnv )
  291. {
  292. return;
  293. }
  294. kwsys_stl::string pathEnv = cpathEnv;
  295. // A hack to make the below algorithm work.
  296. if(pathEnv[pathEnv.length()-1] != ':')
  297. {
  298. pathEnv += pathSep;
  299. }
  300. kwsys_stl::string::size_type start =0;
  301. bool done = false;
  302. while(!done)
  303. {
  304. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  305. if(endpos != kwsys_stl::string::npos)
  306. {
  307. kwsys_stl::string convertedPath;
  308. Realpath(pathEnv.substr(start, endpos-start).c_str(), convertedPath);
  309. path.push_back(convertedPath);
  310. start = endpos+1;
  311. }
  312. else
  313. {
  314. done = true;
  315. }
  316. }
  317. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  318. i != path.end(); ++i)
  319. {
  320. SystemTools::ConvertToUnixSlashes(*i);
  321. }
  322. }
  323. const char* SystemTools::GetEnv(const char* key)
  324. {
  325. return getenv(key);
  326. }
  327. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  328. {
  329. const char* v = getenv(key);
  330. if(v)
  331. {
  332. result = v;
  333. return true;
  334. }
  335. else
  336. {
  337. return false;
  338. }
  339. }
  340. const char* SystemTools::GetExecutableExtension()
  341. {
  342. #if defined(_WIN32) || defined(__CYGWIN__)
  343. return ".exe";
  344. #else
  345. return "";
  346. #endif
  347. }
  348. bool SystemTools::MakeDirectory(const char* path)
  349. {
  350. if(!path)
  351. {
  352. return false;
  353. }
  354. if(SystemTools::FileExists(path))
  355. {
  356. return true;
  357. }
  358. kwsys_stl::string dir = path;
  359. if(dir.size() == 0)
  360. {
  361. return false;
  362. }
  363. SystemTools::ConvertToUnixSlashes(dir);
  364. kwsys_stl::string::size_type pos = dir.find(':');
  365. if(pos == kwsys_stl::string::npos)
  366. {
  367. pos = 0;
  368. }
  369. kwsys_stl::string topdir;
  370. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  371. {
  372. topdir = dir.substr(0, pos);
  373. Mkdir(topdir.c_str());
  374. pos++;
  375. }
  376. if(dir[dir.size()-1] == '/')
  377. {
  378. topdir = dir.substr(0, dir.size());
  379. }
  380. else
  381. {
  382. topdir = dir;
  383. }
  384. if(Mkdir(topdir.c_str()) != 0)
  385. {
  386. // There is a bug in the Borland Run time library which makes MKDIR
  387. // return EACCES when it should return EEXISTS
  388. // if it is some other error besides directory exists
  389. // then return false
  390. if( (errno != EEXIST)
  391. #ifdef __BORLANDC__
  392. && (errno != EACCES)
  393. #endif
  394. )
  395. {
  396. return false;
  397. }
  398. }
  399. return true;
  400. }
  401. // replace replace with with as many times as it shows up in source.
  402. // write the result into source.
  403. void SystemTools::ReplaceString(kwsys_stl::string& source,
  404. const char* replace,
  405. const char* with)
  406. {
  407. const char *src = source.c_str();
  408. char *searchPos = const_cast<char *>(strstr(src,replace));
  409. // get out quick if string is not found
  410. if (!searchPos)
  411. {
  412. return;
  413. }
  414. // perform replacements until done
  415. size_t replaceSize = strlen(replace);
  416. char *orig = strdup(src);
  417. char *currentPos = orig;
  418. searchPos = searchPos - src + orig;
  419. // initialize the result
  420. source.erase(source.begin(),source.end());
  421. do
  422. {
  423. *searchPos = '\0';
  424. source += currentPos;
  425. currentPos = searchPos + replaceSize;
  426. // replace
  427. source += with;
  428. searchPos = strstr(currentPos,replace);
  429. }
  430. while (searchPos);
  431. // copy any trailing text
  432. source += currentPos;
  433. free(orig);
  434. }
  435. // Read a registry value.
  436. // Example :
  437. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  438. // => will return the data of the "default" value of the key
  439. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  440. // => will return the data of the "Root" value of the key
  441. #if defined(_WIN32) && !defined(__CYGWIN__)
  442. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
  443. {
  444. kwsys_stl::string primary = key;
  445. kwsys_stl::string second;
  446. kwsys_stl::string valuename;
  447. size_t start = primary.find("\\");
  448. if (start == kwsys_stl::string::npos)
  449. {
  450. return false;
  451. }
  452. size_t valuenamepos = primary.find(";");
  453. if (valuenamepos != kwsys_stl::string::npos)
  454. {
  455. valuename = primary.substr(valuenamepos+1);
  456. }
  457. second = primary.substr(start+1, valuenamepos-start-1);
  458. primary = primary.substr(0, start);
  459. HKEY primaryKey = HKEY_CURRENT_USER;
  460. if (primary == "HKEY_CURRENT_USER")
  461. {
  462. primaryKey = HKEY_CURRENT_USER;
  463. }
  464. if (primary == "HKEY_CURRENT_CONFIG")
  465. {
  466. primaryKey = HKEY_CURRENT_CONFIG;
  467. }
  468. if (primary == "HKEY_CLASSES_ROOT")
  469. {
  470. primaryKey = HKEY_CLASSES_ROOT;
  471. }
  472. if (primary == "HKEY_LOCAL_MACHINE")
  473. {
  474. primaryKey = HKEY_LOCAL_MACHINE;
  475. }
  476. if (primary == "HKEY_USERS")
  477. {
  478. primaryKey = HKEY_USERS;
  479. }
  480. HKEY hKey;
  481. if(RegOpenKeyEx(primaryKey,
  482. second.c_str(),
  483. 0,
  484. KEY_READ,
  485. &hKey) != ERROR_SUCCESS)
  486. {
  487. return false;
  488. }
  489. else
  490. {
  491. DWORD dwType, dwSize;
  492. dwSize = 1023;
  493. char data[1024];
  494. if(RegQueryValueEx(hKey,
  495. (LPTSTR)valuename.c_str(),
  496. NULL,
  497. &dwType,
  498. (BYTE *)data,
  499. &dwSize) == ERROR_SUCCESS)
  500. {
  501. if (dwType == REG_SZ)
  502. {
  503. value = data;
  504. RegCloseKey(hKey);
  505. return true;
  506. }
  507. }
  508. }
  509. return false;
  510. }
  511. #else
  512. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
  513. {
  514. return false;
  515. }
  516. #endif
  517. // Write a registry value.
  518. // Example :
  519. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  520. // => will set the data of the "default" value of the key
  521. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  522. // => will set the data of the "Root" value of the key
  523. #if defined(_WIN32) && !defined(__CYGWIN__)
  524. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  525. {
  526. kwsys_stl::string primary = key;
  527. kwsys_stl::string second;
  528. kwsys_stl::string valuename;
  529. size_t start = primary.find("\\");
  530. if (start == kwsys_stl::string::npos)
  531. {
  532. return false;
  533. }
  534. size_t valuenamepos = primary.find(";");
  535. if (valuenamepos != kwsys_stl::string::npos)
  536. {
  537. valuename = primary.substr(valuenamepos+1);
  538. }
  539. second = primary.substr(start+1, valuenamepos-start-1);
  540. primary = primary.substr(0, start);
  541. HKEY primaryKey = HKEY_CURRENT_USER;
  542. if (primary == "HKEY_CURRENT_USER")
  543. {
  544. primaryKey = HKEY_CURRENT_USER;
  545. }
  546. if (primary == "HKEY_CURRENT_CONFIG")
  547. {
  548. primaryKey = HKEY_CURRENT_CONFIG;
  549. }
  550. if (primary == "HKEY_CLASSES_ROOT")
  551. {
  552. primaryKey = HKEY_CLASSES_ROOT;
  553. }
  554. if (primary == "HKEY_LOCAL_MACHINE")
  555. {
  556. primaryKey = HKEY_LOCAL_MACHINE;
  557. }
  558. if (primary == "HKEY_USERS")
  559. {
  560. primaryKey = HKEY_USERS;
  561. }
  562. HKEY hKey;
  563. DWORD dwDummy;
  564. if(RegCreateKeyEx(primaryKey,
  565. second.c_str(),
  566. 0,
  567. "",
  568. REG_OPTION_NON_VOLATILE,
  569. KEY_WRITE,
  570. NULL,
  571. &hKey,
  572. &dwDummy) != ERROR_SUCCESS)
  573. {
  574. return false;
  575. }
  576. if(RegSetValueEx(hKey,
  577. (LPTSTR)valuename.c_str(),
  578. 0,
  579. REG_SZ,
  580. (CONST BYTE *)value,
  581. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  582. {
  583. return true;
  584. }
  585. return false;
  586. }
  587. #else
  588. bool SystemTools::WriteRegistryValue(const char *, const char *)
  589. {
  590. return false;
  591. }
  592. #endif
  593. // Delete a registry value.
  594. // Example :
  595. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  596. // => will delete the data of the "default" value of the key
  597. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  598. // => will delete the data of the "Root" value of the key
  599. #if defined(_WIN32) && !defined(__CYGWIN__)
  600. bool SystemTools::DeleteRegistryValue(const char *key)
  601. {
  602. kwsys_stl::string primary = key;
  603. kwsys_stl::string second;
  604. kwsys_stl::string valuename;
  605. size_t start = primary.find("\\");
  606. if (start == kwsys_stl::string::npos)
  607. {
  608. return false;
  609. }
  610. size_t valuenamepos = primary.find(";");
  611. if (valuenamepos != kwsys_stl::string::npos)
  612. {
  613. valuename = primary.substr(valuenamepos+1);
  614. }
  615. second = primary.substr(start+1, valuenamepos-start-1);
  616. primary = primary.substr(0, start);
  617. HKEY primaryKey = HKEY_CURRENT_USER;
  618. if (primary == "HKEY_CURRENT_USER")
  619. {
  620. primaryKey = HKEY_CURRENT_USER;
  621. }
  622. if (primary == "HKEY_CURRENT_CONFIG")
  623. {
  624. primaryKey = HKEY_CURRENT_CONFIG;
  625. }
  626. if (primary == "HKEY_CLASSES_ROOT")
  627. {
  628. primaryKey = HKEY_CLASSES_ROOT;
  629. }
  630. if (primary == "HKEY_LOCAL_MACHINE")
  631. {
  632. primaryKey = HKEY_LOCAL_MACHINE;
  633. }
  634. if (primary == "HKEY_USERS")
  635. {
  636. primaryKey = HKEY_USERS;
  637. }
  638. HKEY hKey;
  639. if(RegOpenKeyEx(primaryKey,
  640. second.c_str(),
  641. 0,
  642. KEY_WRITE,
  643. &hKey) != ERROR_SUCCESS)
  644. {
  645. return false;
  646. }
  647. else
  648. {
  649. if(RegDeleteValue(hKey,
  650. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  651. {
  652. RegCloseKey(hKey);
  653. return true;
  654. }
  655. }
  656. return false;
  657. }
  658. #else
  659. bool SystemTools::DeleteRegistryValue(const char *)
  660. {
  661. return false;
  662. }
  663. #endif
  664. bool SystemTools::SameFile(const char* file1, const char* file2)
  665. {
  666. #ifdef _WIN32
  667. HANDLE hFile1, hFile2;
  668. hFile1 = CreateFile( file1,
  669. GENERIC_READ,
  670. FILE_SHARE_READ ,
  671. NULL,
  672. OPEN_EXISTING,
  673. FILE_FLAG_BACKUP_SEMANTICS,
  674. NULL
  675. );
  676. hFile2 = CreateFile( file2,
  677. GENERIC_READ,
  678. FILE_SHARE_READ,
  679. NULL,
  680. OPEN_EXISTING,
  681. FILE_FLAG_BACKUP_SEMANTICS,
  682. NULL
  683. );
  684. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  685. {
  686. if(hFile1 != INVALID_HANDLE_VALUE)
  687. {
  688. CloseHandle(hFile1);
  689. }
  690. if(hFile2 != INVALID_HANDLE_VALUE)
  691. {
  692. CloseHandle(hFile2);
  693. }
  694. return false;
  695. }
  696. BY_HANDLE_FILE_INFORMATION fiBuf1;
  697. BY_HANDLE_FILE_INFORMATION fiBuf2;
  698. GetFileInformationByHandle( hFile1, &fiBuf1 );
  699. GetFileInformationByHandle( hFile2, &fiBuf2 );
  700. CloseHandle(hFile1);
  701. CloseHandle(hFile2);
  702. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  703. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  704. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  705. #else
  706. struct stat fileStat1, fileStat2;
  707. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  708. {
  709. // see if the files are the same file
  710. // check the device inode and size
  711. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  712. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  713. fileStat2.st_size == fileStat1.st_size
  714. )
  715. {
  716. return true;
  717. }
  718. }
  719. return false;
  720. #endif
  721. }
  722. // return true if the file exists
  723. bool SystemTools::FileExists(const char* filename)
  724. {
  725. #ifdef _MSC_VER
  726. # define access _access
  727. #endif
  728. #ifndef R_OK
  729. # define R_OK 04
  730. #endif
  731. if ( access(filename, R_OK) != 0 )
  732. {
  733. return false;
  734. }
  735. else
  736. {
  737. return true;
  738. }
  739. }
  740. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  741. int* result)
  742. {
  743. // Default to same time.
  744. *result = 0;
  745. #if !defined(_WIN32) || defined(__CYGWIN__)
  746. // POSIX version. Use stat function to get file modification time.
  747. struct stat s1;
  748. if(stat(f1, &s1) != 0)
  749. {
  750. return false;
  751. }
  752. struct stat s2;
  753. if(stat(f2, &s2) != 0)
  754. {
  755. return false;
  756. }
  757. # if KWSYS_STAT_HAS_ST_MTIM
  758. // Compare using nanosecond resolution.
  759. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  760. {
  761. *result = -1;
  762. }
  763. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  764. {
  765. *result = 1;
  766. }
  767. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  768. {
  769. *result = -1;
  770. }
  771. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  772. {
  773. *result = 1;
  774. }
  775. # else
  776. // Compare using 1 second resolution.
  777. if(s1.st_mtime < s2.st_mtime)
  778. {
  779. *result = -1;
  780. }
  781. else if(s1.st_mtime > s2.st_mtime)
  782. {
  783. *result = 1;
  784. }
  785. # endif
  786. #else
  787. // Windows version. Get the modification time from extended file attributes.
  788. WIN32_FILE_ATTRIBUTE_DATA f1d;
  789. WIN32_FILE_ATTRIBUTE_DATA f2d;
  790. if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
  791. {
  792. return false;
  793. }
  794. if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
  795. {
  796. return false;
  797. }
  798. // Compare the file times using resolution provided by system call.
  799. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  800. #endif
  801. return true;
  802. }
  803. // Return a capitalized string (i.e the first letter is uppercased, all other
  804. // are lowercased)
  805. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  806. {
  807. kwsys_stl::string n;
  808. if(s.size() == 0)
  809. {
  810. return n;
  811. }
  812. n.resize(s.size());
  813. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  814. for (size_t i = 1; i < s.size(); i++)
  815. {
  816. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  817. }
  818. return n;
  819. }
  820. // Return capitalized words
  821. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  822. {
  823. kwsys_stl::string n(s);
  824. for (size_t i = 0; i < s.size(); i++)
  825. {
  826. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  827. // MS has an assert that will fail if s[i] < 0; setting
  828. // LC_CTYPE using setlocale() does *not* help. Painful.
  829. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  830. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  831. #else
  832. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  833. #endif
  834. {
  835. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  836. }
  837. }
  838. return n;
  839. }
  840. // Return uncapitalized words
  841. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  842. {
  843. kwsys_stl::string n(s);
  844. for (size_t i = 0; i < s.size(); i++)
  845. {
  846. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  847. // MS has an assert that will fail if s[i] < 0; setting
  848. // LC_CTYPE using setlocale() does *not* help. Painful.
  849. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  850. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  851. #else
  852. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  853. #endif
  854. {
  855. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  856. }
  857. }
  858. return n;
  859. }
  860. // only works for words with at least two letters
  861. kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  862. const kwsys_stl::string& s)
  863. {
  864. kwsys_stl::string n;
  865. if (s.size())
  866. {
  867. n.reserve(s.size());
  868. n += s[0];
  869. for (size_t i = 1; i < s.size(); i++)
  870. {
  871. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  872. {
  873. n += ' ';
  874. }
  875. n += s[i];
  876. }
  877. }
  878. return n;
  879. }
  880. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  881. {
  882. if (!str1)
  883. {
  884. return SystemTools::DuplicateString(str2);
  885. }
  886. if (!str2)
  887. {
  888. return SystemTools::DuplicateString(str1);
  889. }
  890. size_t len1 = strlen(str1);
  891. char *newstr = new char[len1 + strlen(str2) + 1];
  892. if (!newstr)
  893. {
  894. return 0;
  895. }
  896. strcpy(newstr, str1);
  897. strcat(newstr + len1, str2);
  898. return newstr;
  899. }
  900. char* SystemTools::AppendStrings(
  901. const char* str1, const char* str2, const char* str3)
  902. {
  903. if (!str1)
  904. {
  905. return SystemTools::AppendStrings(str2, str3);
  906. }
  907. if (!str2)
  908. {
  909. return SystemTools::AppendStrings(str1, str3);
  910. }
  911. if (!str3)
  912. {
  913. return SystemTools::AppendStrings(str1, str2);
  914. }
  915. size_t len1 = strlen(str1), len2 = strlen(str2);
  916. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  917. if (!newstr)
  918. {
  919. return 0;
  920. }
  921. strcpy(newstr, str1);
  922. strcat(newstr + len1, str2);
  923. strcat(newstr + len1 + len2, str3);
  924. return newstr;
  925. }
  926. // Return a lower case string
  927. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  928. {
  929. kwsys_stl::string n;
  930. n.resize(s.size());
  931. for (size_t i = 0; i < s.size(); i++)
  932. {
  933. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  934. }
  935. return n;
  936. }
  937. // Return a lower case string
  938. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  939. {
  940. kwsys_stl::string n;
  941. n.resize(s.size());
  942. for (size_t i = 0; i < s.size(); i++)
  943. {
  944. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  945. }
  946. return n;
  947. }
  948. // Count char in string
  949. size_t SystemTools::CountChar(const char* str, char c)
  950. {
  951. size_t count = 0;
  952. if (str)
  953. {
  954. while (*str)
  955. {
  956. if (*str == c)
  957. {
  958. ++count;
  959. }
  960. ++str;
  961. }
  962. }
  963. return count;
  964. }
  965. // Remove chars in string
  966. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  967. {
  968. if (!str)
  969. {
  970. return NULL;
  971. }
  972. char *clean_str = new char [strlen(str) + 1];
  973. char *ptr = clean_str;
  974. while (*str)
  975. {
  976. const char *str2 = toremove;
  977. while (*str2 && *str != *str2)
  978. {
  979. ++str2;
  980. }
  981. if (!*str2)
  982. {
  983. *ptr++ = *str;
  984. }
  985. ++str;
  986. }
  987. *ptr = '\0';
  988. return clean_str;
  989. }
  990. // Remove chars in string
  991. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  992. {
  993. if (!str)
  994. {
  995. return 0;
  996. }
  997. char *clean_str = new char [strlen(str) + 1];
  998. char *ptr = clean_str;
  999. while (*str)
  1000. {
  1001. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
  1002. {
  1003. *ptr++ = *str;
  1004. }
  1005. ++str;
  1006. }
  1007. *ptr = '\0';
  1008. return clean_str;
  1009. }
  1010. // Replace chars in string
  1011. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  1012. {
  1013. if (str)
  1014. {
  1015. char *ptr = str;
  1016. while (*ptr)
  1017. {
  1018. const char *ptr2 = toreplace;
  1019. while (*ptr2)
  1020. {
  1021. if (*ptr == *ptr2)
  1022. {
  1023. *ptr = replacement;
  1024. }
  1025. ++ptr2;
  1026. }
  1027. ++ptr;
  1028. }
  1029. }
  1030. return str;
  1031. }
  1032. // Returns if string starts with another string
  1033. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  1034. {
  1035. if (!str1 || !str2)
  1036. {
  1037. return false;
  1038. }
  1039. size_t len1 = strlen(str1), len2 = strlen(str2);
  1040. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  1041. }
  1042. // Returns if string ends with another string
  1043. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  1044. {
  1045. if (!str1 || !str2)
  1046. {
  1047. return false;
  1048. }
  1049. size_t len1 = strlen(str1), len2 = strlen(str2);
  1050. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  1051. }
  1052. // Returns a pointer to the last occurence of str2 in str1
  1053. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  1054. {
  1055. if (!str1 || !str2)
  1056. {
  1057. return NULL;
  1058. }
  1059. size_t len1 = strlen(str1), len2 = strlen(str2);
  1060. if (len1 >= len2)
  1061. {
  1062. const char *ptr = str1 + len1 - len2;
  1063. do
  1064. {
  1065. if (!strncmp(ptr, str2, len2))
  1066. {
  1067. return ptr;
  1068. }
  1069. } while (ptr-- != str1);
  1070. }
  1071. return NULL;
  1072. }
  1073. // Duplicate string
  1074. char* SystemTools::DuplicateString(const char* str)
  1075. {
  1076. if (str)
  1077. {
  1078. char *newstr = new char [strlen(str) + 1];
  1079. return strcpy(newstr, str);
  1080. }
  1081. return NULL;
  1082. }
  1083. // Return a cropped string
  1084. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  1085. size_t max_len)
  1086. {
  1087. if (!s.size() || max_len == 0 || max_len >= s.size())
  1088. {
  1089. return s;
  1090. }
  1091. kwsys_stl::string n;
  1092. n.reserve(max_len);
  1093. size_t middle = max_len / 2;
  1094. n += s.substr(0, middle);
  1095. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  1096. if (max_len > 2)
  1097. {
  1098. n[middle] = '.';
  1099. if (max_len > 3)
  1100. {
  1101. n[middle - 1] = '.';
  1102. if (max_len > 4)
  1103. {
  1104. n[middle + 1] = '.';
  1105. }
  1106. }
  1107. }
  1108. return n;
  1109. }
  1110. //----------------------------------------------------------------------------
  1111. kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
  1112. {
  1113. kwsys_stl::string path = p;
  1114. kwsys_stl::vector<kwsys::String> paths;
  1115. if(isPath && path[0] == '/')
  1116. {
  1117. path.erase(path.begin());
  1118. paths.push_back("/");
  1119. }
  1120. kwsys_stl::string::size_type pos1 = 0;
  1121. kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  1122. while(pos2 != kwsys_stl::string::npos)
  1123. {
  1124. paths.push_back(path.substr(pos1, pos2-pos1));
  1125. pos1 = pos2+1;
  1126. pos2 = path.find(sep, pos1+1);
  1127. }
  1128. paths.push_back(path.substr(pos1, pos2-pos1));
  1129. return paths;
  1130. }
  1131. //----------------------------------------------------------------------------
  1132. int SystemTools::EstimateFormatLength(const char *format, va_list ap)
  1133. {
  1134. if (!format)
  1135. {
  1136. return 0;
  1137. }
  1138. // Quick-hack attempt at estimating the length of the string.
  1139. // Should never under-estimate.
  1140. // Start with the length of the format string itself.
  1141. size_t length = strlen(format);
  1142. // Increase the length for every argument in the format.
  1143. const char* cur = format;
  1144. while(*cur)
  1145. {
  1146. if(*cur++ == '%')
  1147. {
  1148. // Skip "%%" since it doesn't correspond to a va_arg.
  1149. if(*cur != '%')
  1150. {
  1151. while(!int(isalpha(*cur)))
  1152. {
  1153. ++cur;
  1154. }
  1155. switch (*cur)
  1156. {
  1157. case 's':
  1158. {
  1159. // Check the length of the string.
  1160. char* s = va_arg(ap, char*);
  1161. if(s)
  1162. {
  1163. length += strlen(s);
  1164. }
  1165. } break;
  1166. case 'e':
  1167. case 'f':
  1168. case 'g':
  1169. {
  1170. // Assume the argument contributes no more than 64 characters.
  1171. length += 64;
  1172. // Eat the argument.
  1173. static_cast<void>(va_arg(ap, double));
  1174. } break;
  1175. default:
  1176. {
  1177. // Assume the argument contributes no more than 64 characters.
  1178. length += 64;
  1179. // Eat the argument.
  1180. static_cast<void>(va_arg(ap, int));
  1181. } break;
  1182. }
  1183. }
  1184. // Move past the characters just tested.
  1185. ++cur;
  1186. }
  1187. }
  1188. return static_cast<int>(length);
  1189. }
  1190. kwsys_stl::string SystemTools::EscapeChars(
  1191. const char *str,
  1192. const char *chars_to_escape,
  1193. char escape_char)
  1194. {
  1195. kwsys_stl::string n;
  1196. if (str)
  1197. {
  1198. if (!chars_to_escape | !*chars_to_escape)
  1199. {
  1200. n.append(str);
  1201. }
  1202. else
  1203. {
  1204. n.reserve(strlen(str));
  1205. while (*str)
  1206. {
  1207. const char *ptr = chars_to_escape;
  1208. while (*ptr)
  1209. {
  1210. if (*str == *ptr)
  1211. {
  1212. n += escape_char;
  1213. break;
  1214. }
  1215. ++ptr;
  1216. }
  1217. n += *str;
  1218. ++str;
  1219. }
  1220. }
  1221. }
  1222. return n;
  1223. }
  1224. // convert windows slashes to unix slashes
  1225. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  1226. {
  1227. const char* pathCString = path.c_str();
  1228. bool hasDoubleSlash = false;
  1229. const char* pos0 = pathCString;
  1230. const char* pos1 = pathCString+1;
  1231. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1232. {
  1233. // make sure we don't convert an escaped space to a unix slash
  1234. if ( *pos0 == '\\' && *pos1 != ' ' )
  1235. {
  1236. path[pos] = '/';
  1237. }
  1238. // Also, reuse the loop to check for slash followed by another slash
  1239. if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
  1240. {
  1241. #ifdef _WIN32
  1242. // However, on windows if the first characters are both slashes,
  1243. // then keep them that way, so that network paths can be handled.
  1244. if ( pos > 0)
  1245. {
  1246. hasDoubleSlash = true;
  1247. }
  1248. #else
  1249. hasDoubleSlash = true;
  1250. #endif
  1251. }
  1252. pos0 ++;
  1253. pos1 ++;
  1254. }
  1255. if ( hasDoubleSlash )
  1256. {
  1257. SystemTools::ReplaceString(path, "//", "/");
  1258. }
  1259. // remove any trailing slash
  1260. if(!path.empty())
  1261. {
  1262. // if there is a tilda ~ then replace it with HOME
  1263. pathCString = path.c_str();
  1264. if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
  1265. {
  1266. const char* homeEnv = SystemTools::GetEnv("HOME");
  1267. if (homeEnv)
  1268. {
  1269. path.replace(0,1,homeEnv);
  1270. }
  1271. }
  1272. #ifdef HAVE_GETPWNAM
  1273. else if(pathCString[0] == '~')
  1274. {
  1275. kwsys_stl::string::size_type idx = path.find_first_of("/\0");
  1276. kwsys_stl::string user = path.substr(1, idx-1);
  1277. passwd* pw = getpwnam(user.c_str());
  1278. if(pw)
  1279. {
  1280. path.replace(0, idx, pw->pw_dir);
  1281. }
  1282. }
  1283. #endif
  1284. // remove trailing slash if the path is more than
  1285. // a single /
  1286. pathCString = path.c_str();
  1287. if(path.size() > 1 && *(pathCString+(path.size()-1)) == '/')
  1288. {
  1289. // if it is c:/ then do not remove the trailing slash
  1290. if(!((path.size() == 3 && pathCString[1] == ':')))
  1291. {
  1292. path = path.substr(0, path.size()-1);
  1293. }
  1294. }
  1295. }
  1296. }
  1297. // change // to /, and escape any spaces in the path
  1298. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  1299. {
  1300. kwsys_stl::string ret = path;
  1301. // remove // except at the beginning might be a cygwin drive
  1302. kwsys_stl::string::size_type pos=0;
  1303. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  1304. {
  1305. ret.erase(pos, 1);
  1306. }
  1307. // escape spaces and () in the path
  1308. if(ret.find_first_of(" ") != kwsys_stl::string::npos)
  1309. {
  1310. kwsys_stl::string result = "";
  1311. char lastch = 1;
  1312. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1313. {
  1314. // if it is already escaped then don't try to escape it again
  1315. if((*ch == ' ') && lastch != '\\')
  1316. {
  1317. result += '\\';
  1318. }
  1319. result += *ch;
  1320. lastch = *ch;
  1321. }
  1322. ret = result;
  1323. }
  1324. return ret;
  1325. }
  1326. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1327. {
  1328. #if defined(_WIN32) && !defined(__CYGWIN__)
  1329. return SystemTools::ConvertToWindowsOutputPath(path);
  1330. #else
  1331. return SystemTools::ConvertToUnixOutputPath(path);
  1332. #endif
  1333. }
  1334. // remove double slashes not at the start
  1335. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1336. {
  1337. kwsys_stl::string ret;
  1338. // make it big enough for all of path and double quotes
  1339. ret.reserve(strlen(path)+3);
  1340. // put path into the string
  1341. ret.assign(path);
  1342. ret = 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. #if defined(_WIN32) && !defined(__CYGWIN__)
  2176. bool SystemTools::CreateSymlink(const char*, const char*)
  2177. {
  2178. return false;
  2179. }
  2180. #else
  2181. bool SystemTools::CreateSymlink(const char* origName, const char* newName)
  2182. {
  2183. return symlink(origName, newName) >= 0;
  2184. }
  2185. #endif
  2186. #if defined(_WIN32) && !defined(__CYGWIN__)
  2187. bool SystemTools::ReadSymlink(const char*, kwsys_stl::string&)
  2188. {
  2189. return false;
  2190. }
  2191. #else
  2192. bool SystemTools::ReadSymlink(const char* newName,
  2193. kwsys_stl::string& origName)
  2194. {
  2195. char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1];
  2196. int count =
  2197. static_cast<int>(readlink(newName, buf, KWSYS_SYSTEMTOOLS_MAXPATH));
  2198. if(count >= 0)
  2199. {
  2200. // Add null-terminator.
  2201. buf[count] = 0;
  2202. origName = buf;
  2203. return true;
  2204. }
  2205. else
  2206. {
  2207. return false;
  2208. }
  2209. }
  2210. #endif
  2211. int SystemTools::ChangeDirectory(const char *dir)
  2212. {
  2213. return Chdir(dir);
  2214. }
  2215. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  2216. {
  2217. char buf[2048];
  2218. const char* cwd = Getcwd(buf, 2048);
  2219. kwsys_stl::string path;
  2220. if ( cwd )
  2221. {
  2222. path = cwd;
  2223. }
  2224. if(collapse)
  2225. {
  2226. return SystemTools::CollapseFullPath(path.c_str());
  2227. }
  2228. return path;
  2229. }
  2230. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  2231. {
  2232. kwsys_stl::string dir, file;
  2233. SystemTools::SplitProgramPath(in_name, dir, file);
  2234. return dir;
  2235. }
  2236. bool SystemTools::SplitProgramPath(const char* in_name,
  2237. kwsys_stl::string& dir,
  2238. kwsys_stl::string& file,
  2239. bool)
  2240. {
  2241. dir = in_name;
  2242. file = "";
  2243. SystemTools::ConvertToUnixSlashes(dir);
  2244. if(!SystemTools::FileIsDirectory(dir.c_str()))
  2245. {
  2246. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  2247. if(slashPos != kwsys_stl::string::npos)
  2248. {
  2249. file = dir.substr(slashPos+1);
  2250. dir = dir.substr(0, slashPos);
  2251. }
  2252. else
  2253. {
  2254. file = dir;
  2255. dir = "";
  2256. }
  2257. }
  2258. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  2259. {
  2260. kwsys_stl::string oldDir = in_name;
  2261. SystemTools::ConvertToUnixSlashes(oldDir);
  2262. dir = in_name;
  2263. return false;
  2264. }
  2265. return true;
  2266. }
  2267. bool SystemTools::FindProgramPath(const char* argv0,
  2268. kwsys_stl::string& pathOut,
  2269. kwsys_stl::string& errorMsg,
  2270. const char* exeName,
  2271. const char* buildDir,
  2272. const char* installPrefix )
  2273. {
  2274. kwsys_stl::vector<kwsys_stl::string> failures;
  2275. kwsys_stl::string self = argv0 ? argv0 : "";
  2276. failures.push_back(self);
  2277. SystemTools::ConvertToUnixSlashes(self);
  2278. self = SystemTools::FindProgram(self.c_str());
  2279. if(!SystemTools::FileExists(self.c_str()))
  2280. {
  2281. if(buildDir)
  2282. {
  2283. kwsys_stl::string intdir = ".";
  2284. #ifdef CMAKE_INTDIR
  2285. intdir = CMAKE_INTDIR;
  2286. #endif
  2287. self = buildDir;
  2288. self += "/bin/";
  2289. self += intdir;
  2290. self += "/";
  2291. self += exeName;
  2292. self += SystemTools::GetExecutableExtension();
  2293. }
  2294. }
  2295. if(installPrefix)
  2296. {
  2297. if(!SystemTools::FileExists(self.c_str()))
  2298. {
  2299. failures.push_back(self);
  2300. self = installPrefix;
  2301. self += "/bin/";
  2302. self += exeName;
  2303. }
  2304. }
  2305. if(!SystemTools::FileExists(self.c_str()))
  2306. {
  2307. failures.push_back(self);
  2308. kwsys_ios::ostringstream msg;
  2309. msg << "Can not find the command line program ";
  2310. if (exeName)
  2311. {
  2312. msg << exeName;
  2313. }
  2314. msg << "\n";
  2315. if (argv0)
  2316. {
  2317. msg << " argv[0] = \"" << argv0 << "\"\n";
  2318. }
  2319. msg << " Attempted paths:\n";
  2320. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2321. for(i=failures.begin(); i != failures.end(); ++i)
  2322. {
  2323. msg << " \"" << i->c_str() << "\"\n";
  2324. }
  2325. errorMsg = msg.str();
  2326. return false;
  2327. }
  2328. pathOut = self;
  2329. return true;
  2330. }
  2331. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2332. {
  2333. return SystemTools::CollapseFullPath(in_relative, 0);
  2334. }
  2335. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2336. {
  2337. kwsys_stl::string path_a = a;
  2338. kwsys_stl::string path_b = b;
  2339. SystemTools::ConvertToUnixSlashes(path_a);
  2340. SystemTools::ConvertToUnixSlashes(path_b);
  2341. // First check this is a directory path, since we don't want the table to
  2342. // grow too fat
  2343. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2344. {
  2345. // Make sure the path is a full path and does not contain no '..'
  2346. // Ken--the following code is incorrect. .. can be in a valid path
  2347. // for example /home/martink/MyHubba...Hubba/Src
  2348. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2349. == kwsys_stl::string::npos )
  2350. {
  2351. // Before inserting make sure path ends with '/'
  2352. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2353. {
  2354. path_a += '/';
  2355. }
  2356. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2357. {
  2358. path_b += '/';
  2359. }
  2360. if( !(path_a == path_b) )
  2361. {
  2362. SystemTools::TranslationMap->insert(
  2363. SystemToolsTranslationMap::value_type(path_a, path_b));
  2364. }
  2365. }
  2366. }
  2367. }
  2368. void SystemTools::AddKeepPath(const char* dir)
  2369. {
  2370. kwsys_stl::string cdir;
  2371. Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir);
  2372. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2373. }
  2374. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2375. {
  2376. // Do not translate paths that are too short to have meaningful
  2377. // translations.
  2378. if(path.size() < 2)
  2379. {
  2380. return;
  2381. }
  2382. // Always add a trailing slash before translation. It does not
  2383. // matter if this adds an extra slash, but we do not want to
  2384. // translate part of a directory (like the foo part of foo-dir).
  2385. path += "/";
  2386. // In case a file was specified we still have to go through this:
  2387. // Now convert any path found in the table back to the one desired:
  2388. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2389. for(it = SystemTools::TranslationMap->begin();
  2390. it != SystemTools::TranslationMap->end();
  2391. ++it )
  2392. {
  2393. // We need to check of the path is a substring of the other path
  2394. if(path.find( it->first ) == 0)
  2395. {
  2396. path = path.replace( 0, it->first.size(), it->second);
  2397. }
  2398. }
  2399. // Remove the trailing slash we added before.
  2400. path.erase(path.end()-1, path.end());
  2401. }
  2402. void
  2403. SystemToolsAppendComponents(
  2404. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2405. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2406. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2407. {
  2408. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2409. i != last; ++i)
  2410. {
  2411. if(*i == "..")
  2412. {
  2413. if(out_components.begin() != out_components.end())
  2414. {
  2415. out_components.erase(out_components.end()-1, out_components.end());
  2416. }
  2417. }
  2418. else if(!(*i == ".") && !(*i == ""))
  2419. {
  2420. out_components.push_back(*i);
  2421. }
  2422. }
  2423. }
  2424. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2425. const char* in_base)
  2426. {
  2427. // Collect the output path components.
  2428. kwsys_stl::vector<kwsys_stl::string> out_components;
  2429. // Split the input path components.
  2430. kwsys_stl::vector<kwsys_stl::string> path_components;
  2431. SystemTools::SplitPath(in_path, path_components);
  2432. // If the input path is relative, start with a base path.
  2433. if(path_components[0].length() == 0)
  2434. {
  2435. kwsys_stl::vector<kwsys_stl::string> base_components;
  2436. if(in_base)
  2437. {
  2438. // Use the given base path.
  2439. SystemTools::SplitPath(in_base, base_components);
  2440. }
  2441. else
  2442. {
  2443. // Use the current working directory as a base path.
  2444. char buf[2048];
  2445. if(const char* cwd = Getcwd(buf, 2048))
  2446. {
  2447. SystemTools::SplitPath(cwd, base_components);
  2448. }
  2449. else
  2450. {
  2451. // ??
  2452. }
  2453. }
  2454. // Append base path components to the output path.
  2455. out_components.push_back(base_components[0]);
  2456. SystemToolsAppendComponents(out_components,
  2457. base_components.begin()+1,
  2458. base_components.end());
  2459. }
  2460. // Append input path components to the output path.
  2461. SystemToolsAppendComponents(out_components,
  2462. path_components.begin(),
  2463. path_components.end());
  2464. // Transform the path back to a string.
  2465. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2466. // Update the translation table with this potentially new path. I am not
  2467. // sure why this line is here, it seems really questionable, but yet I
  2468. // would put good money that if I remove it something will break, basically
  2469. // from what I can see it created a mapping from the collapsed path, to be
  2470. // replaced by the input path, which almost completely does the opposite of
  2471. // this function, the only thing preventing this from happening a lot is
  2472. // that if the in_path has a .. in it, then it is not added to the
  2473. // translation table. So for most calls this either does nothing due to the
  2474. // .. or it adds a translation between identical paths as nothing was
  2475. // collapsed, so I am going to try to comment it out, and see what hits the
  2476. // fan, hopefully quickly.
  2477. // Commented out line below:
  2478. //SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2479. SystemTools::CheckTranslationPath(newPath);
  2480. #ifdef _WIN32
  2481. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2482. SystemTools::ConvertToUnixSlashes(newPath);
  2483. #endif
  2484. // Return the reconstructed path.
  2485. return newPath;
  2486. }
  2487. // compute the relative path from here to there
  2488. kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
  2489. {
  2490. if(!SystemTools::FileIsFullPath(local))
  2491. {
  2492. return "";
  2493. }
  2494. if(!SystemTools::FileIsFullPath(remote))
  2495. {
  2496. return "";
  2497. }
  2498. // split up both paths into arrays of strings using / as a separator
  2499. kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
  2500. kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
  2501. kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
  2502. kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here
  2503. // count up how many matching directory names there are from the start
  2504. unsigned int sameCount = 0;
  2505. while(
  2506. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  2507. &&
  2508. // for windows and apple do a case insensitive string compare
  2509. #if defined(_WIN32) || defined(__APPLE__)
  2510. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  2511. remoteSplit[sameCount].c_str()) == 0
  2512. #else
  2513. localSplit[sameCount] == remoteSplit[sameCount]
  2514. #endif
  2515. )
  2516. {
  2517. // put the common parts of the path into the commonPath array
  2518. commonPath.push_back(localSplit[sameCount]);
  2519. // erase the common parts of the path from the original path arrays
  2520. localSplit[sameCount] = "";
  2521. remoteSplit[sameCount] = "";
  2522. sameCount++;
  2523. }
  2524. #if 0
  2525. // NOTE: We did this at one time to prevent relative paths to the
  2526. // compiler from looking like "../../../../../../../usr/bin/gcc".
  2527. // Now however relative paths are only computed for destinations
  2528. // inside the build tree so this is not a problem. This is now a
  2529. // general-purpose method and should not have this hack. I'm
  2530. // leaving it in place in case removing it causes a problem so it is
  2531. // easy to restore:
  2532. //
  2533. // If there is nothing in common but the root directory, then just
  2534. // return the full path.
  2535. if(sameCount <= 1)
  2536. {
  2537. return remote;
  2538. }
  2539. #endif
  2540. // for each entry that is not common in the local path
  2541. // add a ../ to the finalpath array, this gets us out of the local
  2542. // path into the remote dir
  2543. for(unsigned int i = 0; i < localSplit.size(); ++i)
  2544. {
  2545. if(localSplit[i].size())
  2546. {
  2547. finalPath.push_back("../");
  2548. }
  2549. }
  2550. // for each entry that is not common in the remote path add it
  2551. // to the final path.
  2552. for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin();
  2553. vit != remoteSplit.end(); ++vit)
  2554. {
  2555. if(vit->size())
  2556. {
  2557. finalPath.push_back(*vit);
  2558. }
  2559. }
  2560. kwsys_stl::string relativePath; // result string
  2561. // now turn the array of directories into a unix path by puttint /
  2562. // between each entry that does not already have one
  2563. for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin();
  2564. vit1 != finalPath.end(); ++vit1)
  2565. {
  2566. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  2567. {
  2568. relativePath += "/";
  2569. }
  2570. relativePath += *vit1;
  2571. }
  2572. return relativePath;
  2573. }
  2574. // OK, some fun stuff to get the actual case of a given path.
  2575. // Basically, you just need to call ShortPath, then GetLongPathName,
  2576. // However, GetLongPathName is not implemented on windows NT and 95,
  2577. // so we have to simulate it on those versions
  2578. #ifdef _WIN32
  2579. int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
  2580. kwsys_stl::string& longPath )
  2581. {
  2582. kwsys_stl::string::size_type iFound = shortPath.rfind('/');
  2583. if (iFound > 1 && iFound != shortPath.npos)
  2584. {
  2585. // recurse to peel off components
  2586. //
  2587. if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
  2588. {
  2589. longPath += '/';
  2590. if (shortPath[1] != '/')
  2591. {
  2592. WIN32_FIND_DATA findData;
  2593. // append the long component name to the path
  2594. //
  2595. if (INVALID_HANDLE_VALUE != ::FindFirstFile
  2596. (shortPath.c_str(), &findData))
  2597. {
  2598. longPath += findData.cFileName;
  2599. }
  2600. else
  2601. {
  2602. // if FindFirstFile fails, return the error code
  2603. //
  2604. longPath = "";
  2605. return 0;
  2606. }
  2607. }
  2608. }
  2609. }
  2610. else
  2611. {
  2612. longPath = shortPath;
  2613. }
  2614. return (int)longPath.size();
  2615. }
  2616. int PortableGetLongPathName(const char* pathIn,
  2617. kwsys_stl::string & longPath)
  2618. {
  2619. HMODULE lh = LoadLibrary("Kernel32.dll");
  2620. if(lh)
  2621. {
  2622. FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
  2623. if(proc)
  2624. {
  2625. typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
  2626. GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
  2627. char buffer[MAX_PATH+1];
  2628. int len = (*func)(pathIn, buffer, MAX_PATH+1);
  2629. if(len == 0 || len > MAX_PATH+1)
  2630. {
  2631. FreeLibrary(lh);
  2632. return 0;
  2633. }
  2634. longPath = buffer;
  2635. FreeLibrary(lh);
  2636. return len;
  2637. }
  2638. FreeLibrary(lh);
  2639. }
  2640. return OldWindowsGetLongPath(pathIn, longPath);
  2641. }
  2642. #endif
  2643. //----------------------------------------------------------------------------
  2644. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  2645. {
  2646. #ifndef _WIN32
  2647. return p;
  2648. #else
  2649. // Check to see if actual case has already been called
  2650. // for this path, and the result is stored in the LongPathMap
  2651. SystemToolsTranslationMap::iterator i =
  2652. SystemTools::LongPathMap->find(p);
  2653. if(i != SystemTools::LongPathMap->end())
  2654. {
  2655. return i->second;
  2656. }
  2657. kwsys_stl::string shortPath;
  2658. if(!SystemTools::GetShortPath(p, shortPath))
  2659. {
  2660. return p;
  2661. }
  2662. kwsys_stl::string longPath;
  2663. int len = PortableGetLongPathName(shortPath.c_str(), longPath);
  2664. if(len == 0 || len > MAX_PATH+1)
  2665. {
  2666. return p;
  2667. }
  2668. // make sure drive letter is always upper case
  2669. if(longPath.size() > 1 && longPath[1] == ':')
  2670. {
  2671. longPath[0] = toupper(longPath[0]);
  2672. }
  2673. (*SystemTools::LongPathMap)[p] = longPath;
  2674. return longPath;
  2675. #endif
  2676. }
  2677. //----------------------------------------------------------------------------
  2678. void SystemTools::SplitPath(const char* p,
  2679. kwsys_stl::vector<kwsys_stl::string>& components)
  2680. {
  2681. components.clear();
  2682. // Identify the root component.
  2683. const char* c = p;
  2684. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  2685. {
  2686. // Network path.
  2687. components.push_back("//");
  2688. c += 2;
  2689. }
  2690. else if(c[0] == '/')
  2691. {
  2692. // Unix path.
  2693. components.push_back("/");
  2694. c += 1;
  2695. }
  2696. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  2697. {
  2698. // Windows path.
  2699. kwsys_stl::string root = "_:/";
  2700. root[0] = c[0];
  2701. components.push_back(root);
  2702. c += 3;
  2703. }
  2704. else if(c[0] && c[1] == ':')
  2705. {
  2706. // Path relative to a windows drive working directory.
  2707. kwsys_stl::string root = "_:";
  2708. root[0] = c[0];
  2709. components.push_back(root);
  2710. c += 2;
  2711. }
  2712. #ifdef HAVE_GETPWNAM
  2713. else if(c[0] == '~')
  2714. {
  2715. int numChars = 1;
  2716. while(c[numChars] && c[numChars] != '/')
  2717. {
  2718. numChars++;
  2719. }
  2720. const char* homedir;
  2721. if(numChars == 1)
  2722. {
  2723. homedir = getenv("HOME");
  2724. }
  2725. else
  2726. {
  2727. char user[PATH_MAX];
  2728. strncpy(user, c+1, numChars-1);
  2729. user[numChars] = '\0';
  2730. passwd* pw = getpwnam(user);
  2731. if(p)
  2732. {
  2733. homedir = pw->pw_dir;
  2734. }
  2735. else
  2736. {
  2737. homedir = "";
  2738. }
  2739. }
  2740. kwsys_stl::vector<kwsys_stl::string> home_components;
  2741. SystemTools::SplitPath(homedir, home_components);
  2742. components.insert(components.end(),
  2743. home_components.begin(),
  2744. home_components.end());
  2745. c += numChars;
  2746. }
  2747. #endif
  2748. else
  2749. {
  2750. // Relative path.
  2751. components.push_back("");
  2752. }
  2753. // Parse the remaining components.
  2754. const char* first = c;
  2755. const char* last = first;
  2756. for(;*last; ++last)
  2757. {
  2758. if(*last == '/' || *last == '\\')
  2759. {
  2760. // End of a component. Save it.
  2761. components.push_back(kwsys_stl::string(first, last-first));
  2762. first = last+1;
  2763. }
  2764. }
  2765. // Save the last component unless there were no components.
  2766. if(last != c)
  2767. {
  2768. components.push_back(kwsys_stl::string(first, last-first));
  2769. }
  2770. }
  2771. //----------------------------------------------------------------------------
  2772. kwsys_stl::string
  2773. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2774. {
  2775. return SystemTools::JoinPath(components.begin(), components.end());
  2776. }
  2777. //----------------------------------------------------------------------------
  2778. kwsys_stl::string
  2779. SystemTools
  2780. ::JoinPath(kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2781. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2782. {
  2783. // Construct result in a single string.
  2784. kwsys_stl::string result;
  2785. // The first two components do not add a slash.
  2786. if(first != last)
  2787. {
  2788. result += *first++;
  2789. }
  2790. if(first != last)
  2791. {
  2792. result += *first++;
  2793. }
  2794. // All remaining components are always separated with a slash.
  2795. while(first != last)
  2796. {
  2797. result += "/";
  2798. result += *first++;
  2799. }
  2800. // Return the concatenated result.
  2801. return result;
  2802. }
  2803. //----------------------------------------------------------------------------
  2804. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2805. {
  2806. #if defined(_WIN32) || defined(__APPLE__)
  2807. # ifdef _MSC_VER
  2808. return _stricmp(c1, c2) == 0;
  2809. # elif defined(__APPLE__) || defined(__GNUC__)
  2810. return strcasecmp(c1, c2) == 0;
  2811. #else
  2812. return SystemTools::Strucmp(c1, c2) == 0;
  2813. # endif
  2814. #else
  2815. return strcmp(c1, c2) == 0;
  2816. #endif
  2817. }
  2818. //----------------------------------------------------------------------------
  2819. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  2820. {
  2821. kwsys_stl::string data(str);
  2822. kwsys_stl::string::size_type lpos = 0;
  2823. while(lpos < data.length())
  2824. {
  2825. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  2826. if(rpos == kwsys_stl::string::npos)
  2827. {
  2828. // Line ends at end of string without a newline.
  2829. lines.push_back(data.substr(lpos));
  2830. return false;
  2831. }
  2832. else
  2833. {
  2834. // Line ends in a "\n", remove the character.
  2835. lines.push_back(data.substr(lpos, rpos-lpos));
  2836. }
  2837. lpos = rpos+1;
  2838. }
  2839. return true;
  2840. }
  2841. //----------------------------------------------------------------------------
  2842. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2843. {
  2844. kwsys_stl::string data(str);
  2845. kwsys_stl::string::size_type lpos = 0;
  2846. while(lpos < data.length())
  2847. {
  2848. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2849. if(rpos == kwsys_stl::string::npos)
  2850. {
  2851. // Line ends at end of string without a newline.
  2852. lines.push_back(data.substr(lpos));
  2853. return false;
  2854. }
  2855. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2856. {
  2857. // Line ends in a "\r\n" pair, remove both characters.
  2858. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2859. }
  2860. else
  2861. {
  2862. // Line ends in a "\n", remove the character.
  2863. lines.push_back(data.substr(lpos, rpos-lpos));
  2864. }
  2865. lpos = rpos+1;
  2866. }
  2867. return true;
  2868. }
  2869. /**
  2870. * Return path of a full filename (no trailing slashes).
  2871. * Warning: returned path is converted to Unix slashes format.
  2872. */
  2873. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2874. {
  2875. kwsys_stl::string fn = filename;
  2876. SystemTools::ConvertToUnixSlashes(fn);
  2877. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2878. if(slash_pos != kwsys_stl::string::npos)
  2879. {
  2880. kwsys_stl::string ret = fn.substr(0, slash_pos);
  2881. if(ret.size() == 2 && ret[1] == ':')
  2882. {
  2883. return ret + '/';
  2884. }
  2885. if(ret.size() == 0)
  2886. {
  2887. return "/";
  2888. }
  2889. return ret;
  2890. }
  2891. else
  2892. {
  2893. return "";
  2894. }
  2895. }
  2896. /**
  2897. * Return file name of a full filename (i.e. file name without path).
  2898. */
  2899. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2900. {
  2901. #if defined(_WIN32)
  2902. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  2903. #else
  2904. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  2905. #endif
  2906. if(slash_pos != kwsys_stl::string::npos)
  2907. {
  2908. return filename.substr(slash_pos + 1);
  2909. }
  2910. else
  2911. {
  2912. return filename;
  2913. }
  2914. }
  2915. /**
  2916. * Return file extension of a full filename (dot included).
  2917. * Warning: this is the longest extension (for example: .tar.gz)
  2918. */
  2919. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2920. {
  2921. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2922. kwsys_stl::string::size_type dot_pos = name.find(".");
  2923. if(dot_pos != kwsys_stl::string::npos)
  2924. {
  2925. return name.substr(dot_pos);
  2926. }
  2927. else
  2928. {
  2929. return "";
  2930. }
  2931. }
  2932. /**
  2933. * Return file extension of a full filename (dot included).
  2934. * Warning: this is the shortest extension (for example: .tar.gz)
  2935. */
  2936. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2937. {
  2938. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2939. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2940. if(dot_pos != kwsys_stl::string::npos)
  2941. {
  2942. return name.substr(dot_pos);
  2943. }
  2944. else
  2945. {
  2946. return "";
  2947. }
  2948. }
  2949. /**
  2950. * Return file name without extension of a full filename (i.e. without path).
  2951. * Warning: it considers the longest extension (for example: .tar.gz)
  2952. */
  2953. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2954. {
  2955. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2956. kwsys_stl::string::size_type dot_pos = name.find(".");
  2957. if(dot_pos != kwsys_stl::string::npos)
  2958. {
  2959. return name.substr(0, dot_pos);
  2960. }
  2961. else
  2962. {
  2963. return name;
  2964. }
  2965. }
  2966. /**
  2967. * Return file name without extension of a full filename (i.e. without path).
  2968. * Warning: it considers the last extension (for example: removes .gz
  2969. * from .tar.gz)
  2970. */
  2971. kwsys_stl::string
  2972. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2973. {
  2974. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2975. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2976. if(dot_pos != kwsys_stl::string::npos)
  2977. {
  2978. return name.substr(0, dot_pos);
  2979. }
  2980. else
  2981. {
  2982. return name;
  2983. }
  2984. }
  2985. bool SystemTools::FileHasSignature(const char *filename,
  2986. const char *signature,
  2987. long offset)
  2988. {
  2989. if (!filename || !signature)
  2990. {
  2991. return false;
  2992. }
  2993. FILE *fp;
  2994. fp = fopen(filename, "rb");
  2995. if (!fp)
  2996. {
  2997. return false;
  2998. }
  2999. fseek(fp, offset, SEEK_SET);
  3000. bool res = false;
  3001. size_t signature_len = strlen(signature);
  3002. char *buffer = new char [signature_len];
  3003. if (fread(buffer, 1, signature_len, fp) == signature_len)
  3004. {
  3005. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  3006. }
  3007. delete [] buffer;
  3008. fclose(fp);
  3009. return res;
  3010. }
  3011. SystemTools::FileTypeEnum
  3012. SystemTools::DetectFileType(const char *filename,
  3013. unsigned long length,
  3014. double percent_bin)
  3015. {
  3016. if (!filename || percent_bin < 0)
  3017. {
  3018. return SystemTools::FileTypeUnknown;
  3019. }
  3020. FILE *fp;
  3021. fp = fopen(filename, "rb");
  3022. if (!fp)
  3023. {
  3024. return SystemTools::FileTypeUnknown;
  3025. }
  3026. // Allocate buffer and read bytes
  3027. unsigned char *buffer = new unsigned char [length];
  3028. size_t read_length = fread(buffer, 1, length, fp);
  3029. fclose(fp);
  3030. if (read_length == 0)
  3031. {
  3032. return SystemTools::FileTypeUnknown;
  3033. }
  3034. // Loop over contents and count
  3035. size_t text_count = 0;
  3036. const unsigned char *ptr = buffer;
  3037. const unsigned char *buffer_end = buffer + read_length;
  3038. while (ptr != buffer_end)
  3039. {
  3040. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  3041. *ptr == '\n' ||
  3042. *ptr == '\r' ||
  3043. *ptr == '\t')
  3044. {
  3045. text_count++;
  3046. }
  3047. ptr++;
  3048. }
  3049. delete [] buffer;
  3050. double current_percent_bin =
  3051. (static_cast<double>(read_length - text_count) /
  3052. static_cast<double>(read_length));
  3053. if (current_percent_bin >= percent_bin)
  3054. {
  3055. return SystemTools::FileTypeBinary;
  3056. }
  3057. return SystemTools::FileTypeText;
  3058. }
  3059. bool SystemTools::LocateFileInDir(const char *filename,
  3060. const char *dir,
  3061. kwsys_stl::string& filename_found,
  3062. int try_filename_dirs)
  3063. {
  3064. if (!filename || !dir)
  3065. {
  3066. return false;
  3067. }
  3068. // Get the basename of 'filename'
  3069. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  3070. // Check if 'dir' is really a directory
  3071. // If win32 and matches something like C:, accept it as a dir
  3072. kwsys_stl::string real_dir;
  3073. if (!SystemTools::FileIsDirectory(dir))
  3074. {
  3075. #if defined( _WIN32 )
  3076. size_t dir_len = strlen(dir);
  3077. if (dir_len < 2 || dir[dir_len - 1] != ':')
  3078. {
  3079. #endif
  3080. real_dir = SystemTools::GetFilenamePath(dir);
  3081. dir = real_dir.c_str();
  3082. #if defined( _WIN32 )
  3083. }
  3084. #endif
  3085. }
  3086. // Try to find the file in 'dir'
  3087. bool res = false;
  3088. if (filename_base.size() && dir)
  3089. {
  3090. size_t dir_len = strlen(dir);
  3091. int need_slash =
  3092. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  3093. kwsys_stl::string temp = dir;
  3094. if (need_slash)
  3095. {
  3096. temp += "/";
  3097. }
  3098. temp += filename_base;
  3099. if (SystemTools::FileExists(temp.c_str()))
  3100. {
  3101. res = true;
  3102. filename_found = temp;
  3103. }
  3104. // If not found, we can try harder by appending part of the file to
  3105. // to the directory to look inside.
  3106. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  3107. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  3108. else if (try_filename_dirs)
  3109. {
  3110. kwsys_stl::string filename_dir(filename);
  3111. kwsys_stl::string filename_dir_base;
  3112. kwsys_stl::string filename_dir_bases;
  3113. do
  3114. {
  3115. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  3116. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  3117. #if defined( _WIN32 )
  3118. if (!filename_dir_base.size() ||
  3119. filename_dir_base[filename_dir_base.size() - 1] == ':')
  3120. #else
  3121. if (!filename_dir_base.size())
  3122. #endif
  3123. {
  3124. break;
  3125. }
  3126. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  3127. temp = dir;
  3128. if (need_slash)
  3129. {
  3130. temp += "/";
  3131. }
  3132. temp += filename_dir_bases;
  3133. res = SystemTools::LocateFileInDir(
  3134. filename_base.c_str(), temp.c_str(), filename_found, 0);
  3135. } while (!res && filename_dir_base.size());
  3136. }
  3137. }
  3138. return res;
  3139. }
  3140. bool SystemTools::FileIsFullPath(const char* in_name)
  3141. {
  3142. kwsys_stl::string name = in_name;
  3143. #if defined(_WIN32) || defined(__CYGWIN__)
  3144. // On Windows, the name must be at least two characters long.
  3145. if(name.length() < 2)
  3146. {
  3147. return false;
  3148. }
  3149. if(name[1] == ':')
  3150. {
  3151. return true;
  3152. }
  3153. if(name[0] == '\\')
  3154. {
  3155. return true;
  3156. }
  3157. #else
  3158. // On UNIX, the name must be at least one character long.
  3159. if(name.length() < 1)
  3160. {
  3161. return false;
  3162. }
  3163. #endif
  3164. #if !defined(_WIN32)
  3165. if(name[0] == '~')
  3166. {
  3167. return true;
  3168. }
  3169. #endif
  3170. // On UNIX, the name must begin in a '/'.
  3171. // On Windows, if the name begins in a '/', then it is a full
  3172. // network path.
  3173. if(name[0] == '/')
  3174. {
  3175. return true;
  3176. }
  3177. return false;
  3178. }
  3179. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  3180. {
  3181. #if defined(WIN32) && !defined(__CYGWIN__)
  3182. const int size = int(strlen(path)) +1; // size of return
  3183. char *buffer = new char[size]; // create a buffer
  3184. char *tempPath = new char[size]; // create a buffer
  3185. int ret;
  3186. // if the path passed in has quotes around it, first remove the quotes
  3187. if (path[0] == '"' && path[strlen(path)-1] == '"')
  3188. {
  3189. strcpy(tempPath,path+1);
  3190. tempPath[strlen(tempPath)-1] = '\0';
  3191. }
  3192. else
  3193. {
  3194. strcpy(tempPath,path);
  3195. }
  3196. buffer[0] = 0;
  3197. ret = GetShortPathName(tempPath, buffer, size);
  3198. if(buffer[0] == 0 || ret > size)
  3199. {
  3200. delete [] buffer;
  3201. delete [] tempPath;
  3202. return false;
  3203. }
  3204. else
  3205. {
  3206. shortPath = buffer;
  3207. delete [] buffer;
  3208. delete [] tempPath;
  3209. return true;
  3210. }
  3211. #else
  3212. shortPath = path;
  3213. return true;
  3214. #endif
  3215. }
  3216. void SystemTools::SplitProgramFromArgs(const char* path,
  3217. kwsys_stl::string& program, kwsys_stl::string& args)
  3218. {
  3219. // see if this is a full path to a program
  3220. // if so then set program to path and args to nothing
  3221. if(SystemTools::FileExists(path))
  3222. {
  3223. program = path;
  3224. args = "";
  3225. return;
  3226. }
  3227. // Try to find the program in the path, note the program
  3228. // may have spaces in its name so we have to look for it
  3229. kwsys_stl::vector<kwsys_stl::string> e;
  3230. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  3231. if(findProg.size())
  3232. {
  3233. program = findProg;
  3234. args = "";
  3235. return;
  3236. }
  3237. // Now try and peel off space separated chunks from the end of the string
  3238. // so the largest path possible is found allowing for spaces in the path
  3239. kwsys_stl::string dir = path;
  3240. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  3241. while(spacePos != kwsys_stl::string::npos)
  3242. {
  3243. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  3244. // See if the file exists
  3245. if(SystemTools::FileExists(tryProg.c_str()))
  3246. {
  3247. program = tryProg;
  3248. // remove trailing spaces from program
  3249. kwsys_stl::string::size_type pos = program.size()-1;
  3250. while(program[pos] == ' ')
  3251. {
  3252. program.erase(pos);
  3253. pos--;
  3254. }
  3255. args = dir.substr(spacePos, dir.size()-spacePos);
  3256. return;
  3257. }
  3258. // Now try and find the the program in the path
  3259. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  3260. if(findProg.size())
  3261. {
  3262. program = findProg;
  3263. // remove trailing spaces from program
  3264. kwsys_stl::string::size_type pos = program.size()-1;
  3265. while(program[pos] == ' ')
  3266. {
  3267. program.erase(pos);
  3268. pos--;
  3269. }
  3270. args = dir.substr(spacePos, dir.size()-spacePos);
  3271. return;
  3272. }
  3273. // move past the space for the next search
  3274. spacePos--;
  3275. spacePos = dir.rfind(' ', spacePos);
  3276. }
  3277. program = "";
  3278. args = "";
  3279. }
  3280. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  3281. {
  3282. char buf[1024];
  3283. time_t t;
  3284. time(&t);
  3285. strftime(buf, sizeof(buf), format, localtime(&t));
  3286. return kwsys_stl::string(buf);
  3287. }
  3288. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  3289. {
  3290. kwsys_stl::string str(s);
  3291. if (str.find_first_of("0123456789") == 0)
  3292. {
  3293. str = "_" + str;
  3294. }
  3295. kwsys_stl::string permited_chars("_"
  3296. "abcdefghijklmnopqrstuvwxyz"
  3297. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3298. "0123456789");
  3299. kwsys_stl::string::size_type pos = 0;
  3300. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  3301. {
  3302. str[pos] = '_';
  3303. }
  3304. return str;
  3305. }
  3306. // Due to a buggy stream library on the HP and another on Mac OSX, we
  3307. // need this very carefully written version of getline. Returns true
  3308. // if any data were read before the end-of-file was reached.
  3309. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is,
  3310. kwsys_stl::string& line,
  3311. bool* has_newline /* = 0 */,
  3312. long sizeLimit /* = -1 */)
  3313. {
  3314. const int bufferSize = 1024;
  3315. char buffer[bufferSize];
  3316. bool haveData = false;
  3317. bool haveNewline = false;
  3318. // Start with an empty line.
  3319. line = "";
  3320. long leftToRead = sizeLimit;
  3321. // If no characters are read from the stream, the end of file has
  3322. // been reached. Clear the fail bit just before reading.
  3323. while(!haveNewline &&
  3324. leftToRead != 0 &&
  3325. (is.clear(is.rdstate() & ~kwsys_ios::ios::failbit),
  3326. is.getline(buffer, bufferSize), is.gcount() > 0))
  3327. {
  3328. // We have read at least one byte.
  3329. haveData = true;
  3330. // If newline character was read the gcount includes the character
  3331. // but the buffer does not: the end of line has been reached.
  3332. size_t length = strlen(buffer);
  3333. if(length < static_cast<size_t>(is.gcount()))
  3334. {
  3335. haveNewline = true;
  3336. }
  3337. // Avoid storing a carriage return character.
  3338. if(length > 0 && buffer[length-1] == '\r')
  3339. {
  3340. buffer[length-1] = 0;
  3341. }
  3342. // if we read too much then truncate the buffer
  3343. if (leftToRead > 0)
  3344. {
  3345. if (static_cast<long>(length) > leftToRead)
  3346. {
  3347. buffer[leftToRead-1] = 0;
  3348. leftToRead = 0;
  3349. }
  3350. else
  3351. {
  3352. leftToRead -= static_cast<long>(length);
  3353. }
  3354. }
  3355. // Append the data read to the line.
  3356. line.append(buffer);
  3357. sizeLimit = sizeLimit - static_cast<long>(length);
  3358. }
  3359. // Return the results.
  3360. if(has_newline)
  3361. {
  3362. *has_newline = haveNewline;
  3363. }
  3364. return haveData;
  3365. }
  3366. int SystemTools::GetTerminalWidth()
  3367. {
  3368. int width = -1;
  3369. #ifdef HAVE_TTY_INFO
  3370. struct winsize ws;
  3371. char *columns; /* Unix98 environment variable */
  3372. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  3373. {
  3374. width = ws.ws_col;
  3375. }
  3376. if(!isatty(STDOUT_FILENO))
  3377. {
  3378. width = -1;
  3379. }
  3380. columns = getenv("COLUMNS");
  3381. if(columns && *columns)
  3382. {
  3383. long t;
  3384. char *endptr;
  3385. t = strtol(columns, &endptr, 0);
  3386. if(endptr && !*endptr && (t>0) && (t<1000))
  3387. {
  3388. width = static_cast<int>(t);
  3389. }
  3390. }
  3391. if ( width < 9 )
  3392. {
  3393. width = -1;
  3394. }
  3395. #endif
  3396. return width;
  3397. }
  3398. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3399. {
  3400. if ( !file )
  3401. {
  3402. return false;
  3403. }
  3404. struct stat st;
  3405. if ( stat(file, &st) < 0 )
  3406. {
  3407. return false;
  3408. }
  3409. mode = st.st_mode;
  3410. return true;
  3411. }
  3412. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  3413. {
  3414. if ( !file )
  3415. {
  3416. return false;
  3417. }
  3418. if ( !SystemTools::FileExists(file) )
  3419. {
  3420. return false;
  3421. }
  3422. if ( chmod(file, mode) < 0 )
  3423. {
  3424. return false;
  3425. }
  3426. return true;
  3427. }
  3428. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  3429. {
  3430. if ( !fileOrDir || !*fileOrDir )
  3431. {
  3432. return "";
  3433. }
  3434. kwsys_stl::string res = fileOrDir;
  3435. SystemTools::ConvertToUnixSlashes(res);
  3436. kwsys_stl::string::size_type cc = res.size()-1;
  3437. if ( res[cc] == '/' )
  3438. {
  3439. cc --;
  3440. }
  3441. for ( ; cc > 0; cc -- )
  3442. {
  3443. if ( res[cc] == '/' )
  3444. {
  3445. break;
  3446. }
  3447. }
  3448. return res.substr(0, cc);
  3449. }
  3450. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  3451. {
  3452. kwsys_stl::string subdir = cSubdir;
  3453. kwsys_stl::string dir = cDir;
  3454. SystemTools::ConvertToUnixSlashes(dir);
  3455. kwsys_stl::string path = subdir;
  3456. do
  3457. {
  3458. path = SystemTools::GetParentDirectory(path.c_str());
  3459. if(SystemTools::ComparePath(dir.c_str(), path.c_str()))
  3460. {
  3461. return true;
  3462. }
  3463. }
  3464. while ( path.size() > dir.size() );
  3465. return false;
  3466. }
  3467. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  3468. const char* directory, const char* toplevel)
  3469. {
  3470. kwsys_stl::string file = fname;
  3471. SystemTools::ConvertToUnixSlashes(file);
  3472. kwsys_stl::string dir = directory;
  3473. SystemTools::ConvertToUnixSlashes(dir);
  3474. while ( !dir.empty() )
  3475. {
  3476. kwsys_stl::string path = dir + "/" + file;
  3477. if ( SystemTools::FileExists(path.c_str()) )
  3478. {
  3479. return path;
  3480. }
  3481. if ( dir.size() < strlen(toplevel) )
  3482. {
  3483. break;
  3484. }
  3485. dir = SystemTools::GetParentDirectory(dir.c_str());
  3486. }
  3487. return "";
  3488. }
  3489. void SystemTools::Delay(unsigned int msec)
  3490. {
  3491. #ifdef _WIN32
  3492. Sleep(msec);
  3493. #else
  3494. // The sleep function gives 1 second resolution and the usleep
  3495. // function gives 1e-6 second resolution but on some platforms has a
  3496. // maximum sleep time of 1 second. This could be re-implemented to
  3497. // use select with masked signals or pselect to mask signals
  3498. // atomically. If select is given empty sets and zero as the max
  3499. // file descriptor but a non-zero timeout it can be used to block
  3500. // for a precise amount of time.
  3501. if(msec >= 1000)
  3502. {
  3503. sleep(msec / 1000);
  3504. usleep((msec % 1000) * 1000);
  3505. }
  3506. else
  3507. {
  3508. usleep(msec * 1000);
  3509. }
  3510. #endif
  3511. }
  3512. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3513. const char *cmd_line, int *argc, char ***argv)
  3514. {
  3515. if (!cmd_line || !argc || !argv)
  3516. {
  3517. return;
  3518. }
  3519. // A space delimites an argument except when it is inside a quote
  3520. (*argc) = 1;
  3521. size_t cmd_line_len = strlen(cmd_line);
  3522. size_t i;
  3523. for (i = 0; i < cmd_line_len; i++)
  3524. {
  3525. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3526. {
  3527. i++;
  3528. }
  3529. if (i < cmd_line_len)
  3530. {
  3531. if (cmd_line[i] == '\"')
  3532. {
  3533. i++;
  3534. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3535. {
  3536. i++;
  3537. }
  3538. (*argc)++;
  3539. }
  3540. else
  3541. {
  3542. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3543. {
  3544. i++;
  3545. }
  3546. (*argc)++;
  3547. }
  3548. }
  3549. }
  3550. (*argv) = new char* [(*argc) + 1];
  3551. (*argv)[(*argc)] = NULL;
  3552. // Set the first arg to be the exec name
  3553. (*argv)[0] = new char [1024];
  3554. #ifdef _WIN32
  3555. ::GetModuleFileName(0, (*argv)[0], 1024);
  3556. #else
  3557. (*argv)[0][0] = '\0';
  3558. #endif
  3559. // Allocate the others
  3560. int j;
  3561. for (j = 1; j < (*argc); j++)
  3562. {
  3563. (*argv)[j] = new char [cmd_line_len + 10];
  3564. }
  3565. // Grab the args
  3566. size_t pos;
  3567. int argc_idx = 1;
  3568. for (i = 0; i < cmd_line_len; i++)
  3569. {
  3570. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3571. {
  3572. i++;
  3573. }
  3574. if (i < cmd_line_len)
  3575. {
  3576. if (cmd_line[i] == '\"')
  3577. {
  3578. i++;
  3579. pos = i;
  3580. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3581. {
  3582. i++;
  3583. }
  3584. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3585. (*argv)[argc_idx][i - pos] = '\0';
  3586. argc_idx++;
  3587. }
  3588. else
  3589. {
  3590. pos = i;
  3591. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3592. {
  3593. i++;
  3594. }
  3595. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3596. (*argv)[argc_idx][i - pos] = '\0';
  3597. argc_idx++;
  3598. }
  3599. }
  3600. }
  3601. }
  3602. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  3603. {
  3604. kwsys_stl::string res;
  3605. #ifdef _WIN32
  3606. char buffer[256];
  3607. OSVERSIONINFOEX osvi;
  3608. BOOL bOsVersionInfoEx;
  3609. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  3610. // If that fails, try using the OSVERSIONINFO structure.
  3611. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  3612. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  3613. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  3614. if (!bOsVersionInfoEx)
  3615. {
  3616. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3617. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  3618. {
  3619. return 0;
  3620. }
  3621. }
  3622. switch (osvi.dwPlatformId)
  3623. {
  3624. // Test for the Windows NT product family.
  3625. case VER_PLATFORM_WIN32_NT:
  3626. // Test for the specific product family.
  3627. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3628. {
  3629. res += "Microsoft Windows Server 2003 family";
  3630. }
  3631. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  3632. {
  3633. res += "Microsoft Windows XP";
  3634. }
  3635. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3636. {
  3637. res += "Microsoft Windows 2000";
  3638. }
  3639. if (osvi.dwMajorVersion <= 4)
  3640. {
  3641. res += "Microsoft Windows NT";
  3642. }
  3643. // Test for specific product on Windows NT 4.0 SP6 and later.
  3644. if (bOsVersionInfoEx)
  3645. {
  3646. // Test for the workstation type.
  3647. #if (_MSC_VER >= 1300)
  3648. if (osvi.wProductType == VER_NT_WORKSTATION)
  3649. {
  3650. if (osvi.dwMajorVersion == 4)
  3651. {
  3652. res += " Workstation 4.0";
  3653. }
  3654. else if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  3655. {
  3656. res += " Home Edition";
  3657. }
  3658. else
  3659. {
  3660. res += " Professional";
  3661. }
  3662. }
  3663. // Test for the server type.
  3664. else if (osvi.wProductType == VER_NT_SERVER)
  3665. {
  3666. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3667. {
  3668. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3669. {
  3670. res += " Datacenter Edition";
  3671. }
  3672. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3673. {
  3674. res += " Enterprise Edition";
  3675. }
  3676. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  3677. {
  3678. res += " Web Edition";
  3679. }
  3680. else
  3681. {
  3682. res += " Standard Edition";
  3683. }
  3684. }
  3685. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3686. {
  3687. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3688. {
  3689. res += " Datacenter Server";
  3690. }
  3691. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3692. {
  3693. res += " Advanced Server";
  3694. }
  3695. else
  3696. {
  3697. res += " Server";
  3698. }
  3699. }
  3700. else // Windows NT 4.0
  3701. {
  3702. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3703. {
  3704. res += " Server 4.0, Enterprise Edition";
  3705. }
  3706. else
  3707. {
  3708. res += " Server 4.0";
  3709. }
  3710. }
  3711. }
  3712. #endif // Visual Studio 7 and up
  3713. }
  3714. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3715. else
  3716. {
  3717. HKEY hKey;
  3718. #define BUFSIZE 80
  3719. char szProductType[BUFSIZE];
  3720. DWORD dwBufLen=BUFSIZE;
  3721. LONG lRet;
  3722. lRet = RegOpenKeyEx(
  3723. HKEY_LOCAL_MACHINE,
  3724. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3725. 0, KEY_QUERY_VALUE, &hKey);
  3726. if (lRet != ERROR_SUCCESS)
  3727. {
  3728. return 0;
  3729. }
  3730. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  3731. (LPBYTE) szProductType, &dwBufLen);
  3732. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  3733. {
  3734. return 0;
  3735. }
  3736. RegCloseKey(hKey);
  3737. if (lstrcmpi("WINNT", szProductType) == 0)
  3738. {
  3739. res += " Workstation";
  3740. }
  3741. if (lstrcmpi("LANMANNT", szProductType) == 0)
  3742. {
  3743. res += " Server";
  3744. }
  3745. if (lstrcmpi("SERVERNT", szProductType) == 0)
  3746. {
  3747. res += " Advanced Server";
  3748. }
  3749. res += " ";
  3750. sprintf(buffer, "%d", osvi.dwMajorVersion);
  3751. res += buffer;
  3752. res += ".";
  3753. sprintf(buffer, "%d", osvi.dwMinorVersion);
  3754. res += buffer;
  3755. }
  3756. // Display service pack (if any) and build number.
  3757. if (osvi.dwMajorVersion == 4 &&
  3758. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  3759. {
  3760. HKEY hKey;
  3761. LONG lRet;
  3762. // Test for SP6 versus SP6a.
  3763. lRet = RegOpenKeyEx(
  3764. HKEY_LOCAL_MACHINE,
  3765. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  3766. 0, KEY_QUERY_VALUE, &hKey);
  3767. if (lRet == ERROR_SUCCESS)
  3768. {
  3769. res += " Service Pack 6a (Build ";
  3770. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3771. res += buffer;
  3772. res += ")";
  3773. }
  3774. else // Windows NT 4.0 prior to SP6a
  3775. {
  3776. res += " ";
  3777. res += osvi.szCSDVersion;
  3778. res += " (Build ";
  3779. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3780. res += buffer;
  3781. res += ")";
  3782. }
  3783. RegCloseKey(hKey);
  3784. }
  3785. else // Windows NT 3.51 and earlier or Windows 2000 and later
  3786. {
  3787. res += " ";
  3788. res += osvi.szCSDVersion;
  3789. res += " (Build ";
  3790. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3791. res += buffer;
  3792. res += ")";
  3793. }
  3794. break;
  3795. // Test for the Windows 95 product family.
  3796. case VER_PLATFORM_WIN32_WINDOWS:
  3797. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  3798. {
  3799. res += "Microsoft Windows 95";
  3800. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  3801. {
  3802. res += " OSR2";
  3803. }
  3804. }
  3805. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  3806. {
  3807. res += "Microsoft Windows 98";
  3808. if (osvi.szCSDVersion[1] == 'A')
  3809. {
  3810. res += " SE";
  3811. }
  3812. }
  3813. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  3814. {
  3815. res += "Microsoft Windows Millennium Edition";
  3816. }
  3817. break;
  3818. case VER_PLATFORM_WIN32s:
  3819. res += "Microsoft Win32s";
  3820. break;
  3821. }
  3822. #endif
  3823. return res;
  3824. }
  3825. // These must NOT be initialized. Default initialization to zero is
  3826. // necessary.
  3827. unsigned int SystemToolsManagerCount;
  3828. SystemToolsTranslationMap *SystemTools::TranslationMap;
  3829. SystemToolsTranslationMap *SystemTools::LongPathMap;
  3830. // SystemToolsManager manages the SystemTools singleton.
  3831. // SystemToolsManager should be included in any translation unit
  3832. // that will use SystemTools or that implements the singleton
  3833. // pattern. It makes sure that the SystemTools singleton is created
  3834. // before and destroyed after all other singletons in CMake.
  3835. SystemToolsManager::SystemToolsManager()
  3836. {
  3837. if(++SystemToolsManagerCount == 1)
  3838. {
  3839. SystemTools::ClassInitialize();
  3840. }
  3841. }
  3842. SystemToolsManager::~SystemToolsManager()
  3843. {
  3844. if(--SystemToolsManagerCount == 0)
  3845. {
  3846. SystemTools::ClassFinalize();
  3847. }
  3848. }
  3849. void SystemTools::ClassInitialize()
  3850. {
  3851. // Allocate the translation map first.
  3852. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  3853. SystemTools::LongPathMap = new SystemToolsTranslationMap;
  3854. // Add some special translation paths for unix. These are not added
  3855. // for windows because drive letters need to be maintained. Also,
  3856. // there are not sym-links and mount points on windows anyway.
  3857. #if !defined(_WIN32) || defined(__CYGWIN__)
  3858. // Work-around an SGI problem by always adding this mapping:
  3859. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  3860. // The tmp path is frequently a logical path so always keep it:
  3861. SystemTools::AddKeepPath("/tmp/");
  3862. // If the current working directory is a logical path then keep the
  3863. // logical name.
  3864. if(const char* pwd = getenv("PWD"))
  3865. {
  3866. char buf[2048];
  3867. if(const char* cwd = Getcwd(buf, 2048))
  3868. {
  3869. // The current working directory may be a logical path. Find
  3870. // the shortest logical path that still produces the correct
  3871. // physical path.
  3872. kwsys_stl::string cwd_changed;
  3873. kwsys_stl::string pwd_changed;
  3874. // Test progressively shorter logical-to-physical mappings.
  3875. kwsys_stl::string pwd_str = pwd;
  3876. kwsys_stl::string cwd_str = cwd;
  3877. kwsys_stl::string pwd_path;
  3878. Realpath(pwd, pwd_path);
  3879. while(cwd_str == pwd_path && cwd_str != pwd_str)
  3880. {
  3881. // The current pair of paths is a working logical mapping.
  3882. cwd_changed = cwd_str;
  3883. pwd_changed = pwd_str;
  3884. // Strip off one directory level and see if the logical
  3885. // mapping still works.
  3886. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  3887. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  3888. Realpath(pwd_str.c_str(), pwd_path);
  3889. }
  3890. // Add the translation to keep the logical path name.
  3891. if(!cwd_changed.empty() && !pwd_changed.empty())
  3892. {
  3893. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  3894. pwd_changed.c_str());
  3895. }
  3896. }
  3897. }
  3898. #endif
  3899. }
  3900. void SystemTools::ClassFinalize()
  3901. {
  3902. delete SystemTools::TranslationMap;
  3903. delete SystemTools::LongPathMap;
  3904. }
  3905. } // namespace KWSYS_NAMESPACE
  3906. #if defined(_MSC_VER) && defined(_DEBUG)
  3907. # include <crtdbg.h>
  3908. # include <stdio.h>
  3909. # include <stdlib.h>
  3910. namespace KWSYS_NAMESPACE
  3911. {
  3912. static int SystemToolsDebugReport(int, char* message, int*)
  3913. {
  3914. fprintf(stderr, "%s", message);
  3915. fflush(stderr);
  3916. return 1; // no further reporting required
  3917. }
  3918. void SystemTools::EnableMSVCDebugHook()
  3919. {
  3920. if (getenv("DART_TEST_FROM_DART"))
  3921. {
  3922. _CrtSetReportHook(SystemToolsDebugReport);
  3923. }
  3924. }
  3925. } // namespace KWSYS_NAMESPACE
  3926. #else
  3927. namespace KWSYS_NAMESPACE
  3928. {
  3929. void SystemTools::EnableMSVCDebugHook() {}
  3930. } // namespace KWSYS_NAMESPACE
  3931. #endif