SystemTools.cxx 94 KB

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