SystemTools.cxx 106 KB

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