SystemTools.cxx 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890
  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. std::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
  1037. {
  1038. std::string path = p;
  1039. std::vector<kwsys::String> paths;
  1040. if(isPath && path[0] == '/')
  1041. {
  1042. path.erase(path.begin());
  1043. paths.push_back("/");
  1044. }
  1045. std::string::size_type pos1 = 0;
  1046. std::string::size_type pos2 = path.find(sep, pos1+1);
  1047. while(pos2 != std::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. // See if the executable exists as written.
  1741. if(SystemTools::FileExists(name) &&
  1742. !SystemTools::FileIsDirectory(name))
  1743. {
  1744. return SystemTools::CollapseFullPath(name);
  1745. }
  1746. kwsys_stl::string tryPath = name;
  1747. tryPath += SystemTools::GetExecutableExtension();
  1748. if(SystemTools::FileExists(tryPath.c_str()) &&
  1749. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1750. {
  1751. return SystemTools::CollapseFullPath(tryPath.c_str());
  1752. }
  1753. kwsys_stl::vector<kwsys_stl::string> path;
  1754. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1755. // Add the system search path to our path.
  1756. if (!no_system_path)
  1757. {
  1758. SystemTools::GetPath(path);
  1759. }
  1760. // now add the additional paths
  1761. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1762. i != userPaths.end(); ++i)
  1763. {
  1764. path.push_back(*i);
  1765. }
  1766. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1767. p != path.end(); ++p)
  1768. {
  1769. tryPath = *p;
  1770. tryPath += "/";
  1771. tryPath += name;
  1772. if(SystemTools::FileExists(tryPath.c_str()) &&
  1773. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1774. {
  1775. return SystemTools::CollapseFullPath(tryPath.c_str());
  1776. }
  1777. #ifdef _WIN32
  1778. tryPath += ".com";
  1779. if(SystemTools::FileExists(tryPath.c_str()) &&
  1780. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1781. {
  1782. return SystemTools::CollapseFullPath(tryPath.c_str());
  1783. }
  1784. tryPath = *p;
  1785. tryPath += "/";
  1786. tryPath += name;
  1787. #endif
  1788. tryPath += SystemTools::GetExecutableExtension();
  1789. if(SystemTools::FileExists(tryPath.c_str()) &&
  1790. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1791. {
  1792. return SystemTools::CollapseFullPath(tryPath.c_str());
  1793. }
  1794. }
  1795. // Couldn't find the program.
  1796. return "";
  1797. }
  1798. kwsys_stl::string SystemTools::FindProgram(
  1799. const kwsys_stl::vector<kwsys_stl::string>& names,
  1800. const kwsys_stl::vector<kwsys_stl::string>& path,
  1801. bool noSystemPath)
  1802. {
  1803. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin();
  1804. it != names.end() ; ++it)
  1805. {
  1806. // Try to find the program.
  1807. kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
  1808. path,
  1809. noSystemPath);
  1810. if ( !result.empty() )
  1811. {
  1812. return result;
  1813. }
  1814. }
  1815. return "";
  1816. }
  1817. /**
  1818. * Find the library with the given name. Searches the given path and then
  1819. * the system search path. Returns the full path to the library if it is
  1820. * found. Otherwise, the empty string is returned.
  1821. */
  1822. kwsys_stl::string SystemTools
  1823. ::FindLibrary(const char* name,
  1824. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1825. {
  1826. // See if the executable exists as written.
  1827. if(SystemTools::FileExists(name) &&
  1828. !SystemTools::FileIsDirectory(name))
  1829. {
  1830. return SystemTools::CollapseFullPath(name);
  1831. }
  1832. // Add the system search path to our path.
  1833. kwsys_stl::vector<kwsys_stl::string> path;
  1834. SystemTools::GetPath(path);
  1835. // now add the additional paths
  1836. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1837. i != userPaths.end(); ++i)
  1838. {
  1839. path.push_back(*i);
  1840. }
  1841. kwsys_stl::string tryPath;
  1842. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1843. p != path.end(); ++p)
  1844. {
  1845. #if defined(__APPLE__)
  1846. tryPath = *p;
  1847. tryPath += "/";
  1848. tryPath += name;
  1849. tryPath += ".framework";
  1850. if(SystemTools::FileExists(tryPath.c_str())
  1851. && SystemTools::FileIsDirectory(tryPath.c_str()))
  1852. {
  1853. return SystemTools::CollapseFullPath(tryPath.c_str());
  1854. }
  1855. #endif
  1856. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1857. tryPath = *p;
  1858. tryPath += "/";
  1859. tryPath += name;
  1860. tryPath += ".lib";
  1861. if(SystemTools::FileExists(tryPath.c_str())
  1862. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1863. {
  1864. return SystemTools::CollapseFullPath(tryPath.c_str());
  1865. }
  1866. #else
  1867. tryPath = *p;
  1868. tryPath += "/lib";
  1869. tryPath += name;
  1870. tryPath += ".so";
  1871. if(SystemTools::FileExists(tryPath.c_str())
  1872. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1873. {
  1874. return SystemTools::CollapseFullPath(tryPath.c_str());
  1875. }
  1876. tryPath = *p;
  1877. tryPath += "/lib";
  1878. tryPath += name;
  1879. tryPath += ".a";
  1880. if(SystemTools::FileExists(tryPath.c_str())
  1881. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1882. {
  1883. return SystemTools::CollapseFullPath(tryPath.c_str());
  1884. }
  1885. tryPath = *p;
  1886. tryPath += "/lib";
  1887. tryPath += name;
  1888. tryPath += ".sl";
  1889. if(SystemTools::FileExists(tryPath.c_str())
  1890. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1891. {
  1892. return SystemTools::CollapseFullPath(tryPath.c_str());
  1893. }
  1894. tryPath = *p;
  1895. tryPath += "/lib";
  1896. tryPath += name;
  1897. tryPath += ".dylib";
  1898. if(SystemTools::FileExists(tryPath.c_str())
  1899. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1900. {
  1901. return SystemTools::CollapseFullPath(tryPath.c_str());
  1902. }
  1903. tryPath = *p;
  1904. tryPath += "/lib";
  1905. tryPath += name;
  1906. tryPath += ".dll";
  1907. if(SystemTools::FileExists(tryPath.c_str())
  1908. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1909. {
  1910. return SystemTools::CollapseFullPath(tryPath.c_str());
  1911. }
  1912. #endif
  1913. }
  1914. // Couldn't find the library.
  1915. return "";
  1916. }
  1917. bool SystemTools::FileIsDirectory(const char* name)
  1918. {
  1919. struct stat fs;
  1920. if(stat(name, &fs) == 0)
  1921. {
  1922. #if _WIN32
  1923. return ((fs.st_mode & _S_IFDIR) != 0);
  1924. #else
  1925. return S_ISDIR(fs.st_mode);
  1926. #endif
  1927. }
  1928. else
  1929. {
  1930. return false;
  1931. }
  1932. }
  1933. bool SystemTools::FileIsSymlink(const char* name)
  1934. {
  1935. #if _WIN32
  1936. (void)name;
  1937. return false;
  1938. #else
  1939. struct stat fs;
  1940. if(lstat(name, &fs) == 0)
  1941. {
  1942. return S_ISLNK(fs.st_mode);
  1943. }
  1944. else
  1945. {
  1946. return false;
  1947. }
  1948. #endif
  1949. }
  1950. int SystemTools::ChangeDirectory(const char *dir)
  1951. {
  1952. return Chdir(dir);
  1953. }
  1954. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  1955. {
  1956. char buf[2048];
  1957. const char* cwd = Getcwd(buf, 2048);
  1958. kwsys_stl::string path;
  1959. if ( cwd )
  1960. {
  1961. path = cwd;
  1962. }
  1963. if(collapse)
  1964. {
  1965. return SystemTools::CollapseFullPath(path.c_str());
  1966. }
  1967. return path;
  1968. }
  1969. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1970. {
  1971. kwsys_stl::string dir, file;
  1972. SystemTools::SplitProgramPath(in_name, dir, file);
  1973. return dir;
  1974. }
  1975. bool SystemTools::SplitProgramPath(const char* in_name,
  1976. kwsys_stl::string& dir,
  1977. kwsys_stl::string& file,
  1978. bool)
  1979. {
  1980. dir = in_name;
  1981. file = "";
  1982. SystemTools::ConvertToUnixSlashes(dir);
  1983. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1984. {
  1985. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1986. if(slashPos != kwsys_stl::string::npos)
  1987. {
  1988. file = dir.substr(slashPos+1);
  1989. dir = dir.substr(0, slashPos);
  1990. }
  1991. else
  1992. {
  1993. file = dir;
  1994. dir = "";
  1995. }
  1996. }
  1997. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1998. {
  1999. kwsys_stl::string oldDir = in_name;
  2000. SystemTools::ConvertToUnixSlashes(oldDir);
  2001. dir = in_name;
  2002. return false;
  2003. }
  2004. return true;
  2005. }
  2006. bool SystemTools::FindProgramPath(const char* argv0,
  2007. kwsys_stl::string& pathOut,
  2008. kwsys_stl::string& errorMsg,
  2009. const char* exeName,
  2010. const char* buildDir,
  2011. const char* installPrefix )
  2012. {
  2013. kwsys_stl::vector<kwsys_stl::string> failures;
  2014. kwsys_stl::string self = argv0;
  2015. SystemTools::ConvertToUnixSlashes(self);
  2016. failures.push_back(argv0);
  2017. self = SystemTools::FindProgram(self.c_str());
  2018. if(!SystemTools::FileExists(self.c_str()))
  2019. {
  2020. if(buildDir)
  2021. {
  2022. kwsys_stl::string intdir = ".";
  2023. #ifdef CMAKE_INTDIR
  2024. intdir = CMAKE_INTDIR;
  2025. #endif
  2026. self = buildDir;
  2027. self += "/bin/";
  2028. self += intdir;
  2029. self += "/";
  2030. self += exeName;
  2031. self += SystemTools::GetExecutableExtension();
  2032. }
  2033. }
  2034. if(installPrefix)
  2035. {
  2036. if(!SystemTools::FileExists(self.c_str()))
  2037. {
  2038. failures.push_back(self);
  2039. self = installPrefix;
  2040. self += "/bin/";
  2041. self += exeName;
  2042. }
  2043. }
  2044. if(!SystemTools::FileExists(self.c_str()))
  2045. {
  2046. failures.push_back(self);
  2047. kwsys_ios::ostringstream msg;
  2048. msg << "Can not find the command line program " << exeName << "\n";
  2049. msg << " argv[0] = \"" << argv0 << "\"\n";
  2050. msg << " Attempted paths:\n";
  2051. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2052. for(i=failures.begin(); i != failures.end(); ++i)
  2053. {
  2054. msg << " \"" << i->c_str() << "\"\n";
  2055. }
  2056. errorMsg = msg.str();
  2057. return false;
  2058. }
  2059. pathOut = self;
  2060. return true;
  2061. }
  2062. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2063. {
  2064. return SystemTools::CollapseFullPath(in_relative, 0);
  2065. }
  2066. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2067. {
  2068. kwsys_stl::string path_a = a;
  2069. kwsys_stl::string path_b = b;
  2070. SystemTools::ConvertToUnixSlashes(path_a);
  2071. SystemTools::ConvertToUnixSlashes(path_b);
  2072. // First check this is a directory path, since we don't want the table to
  2073. // grow too fat
  2074. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2075. {
  2076. // Make sure the path is a full path and does not contain no '..'
  2077. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2078. == kwsys_stl::string::npos )
  2079. {
  2080. // Before inserting make sure path ends with '/'
  2081. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2082. {
  2083. path_a += '/';
  2084. }
  2085. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2086. {
  2087. path_b += '/';
  2088. }
  2089. if( !(path_a == path_b) )
  2090. {
  2091. SystemTools::TranslationMap->insert(
  2092. SystemToolsTranslationMap::value_type(path_a, path_b));
  2093. }
  2094. }
  2095. }
  2096. }
  2097. void SystemTools::AddKeepPath(const char* dir)
  2098. {
  2099. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  2100. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2101. }
  2102. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2103. {
  2104. // Do not translate paths that are too short to have meaningful
  2105. // translations.
  2106. if(path.size() < 2)
  2107. {
  2108. return;
  2109. }
  2110. // Always add a trailing slash before translation. It does not
  2111. // matter if this adds an extra slash, but we do not want to
  2112. // translate part of a directory (like the foo part of foo-dir).
  2113. path += "/";
  2114. // In case a file was specified we still have to go through this:
  2115. // Now convert any path found in the table back to the one desired:
  2116. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2117. for(it = SystemTools::TranslationMap->begin();
  2118. it != SystemTools::TranslationMap->end();
  2119. ++it )
  2120. {
  2121. // We need to check of the path is a substring of the other path
  2122. if(path.find( it->first ) == 0)
  2123. {
  2124. path = path.replace( 0, it->first.size(), it->second);
  2125. }
  2126. }
  2127. // Remove the trailing slash we added before.
  2128. path.erase(path.end()-1, path.end());
  2129. }
  2130. void
  2131. SystemToolsAppendComponents(
  2132. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2133. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2134. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2135. {
  2136. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2137. i != last; ++i)
  2138. {
  2139. if(*i == "..")
  2140. {
  2141. if(out_components.begin() != out_components.end())
  2142. {
  2143. out_components.erase(out_components.end()-1, out_components.end());
  2144. }
  2145. }
  2146. else if(!(*i == ".") && !(*i == ""))
  2147. {
  2148. out_components.push_back(*i);
  2149. }
  2150. }
  2151. }
  2152. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2153. const char* in_base)
  2154. {
  2155. // Collect the output path components.
  2156. kwsys_stl::vector<kwsys_stl::string> out_components;
  2157. // Split the input path components.
  2158. kwsys_stl::vector<kwsys_stl::string> path_components;
  2159. SystemTools::SplitPath(in_path, path_components);
  2160. // If the input path is relative, start with a base path.
  2161. if(path_components[0].length() == 0)
  2162. {
  2163. kwsys_stl::vector<kwsys_stl::string> base_components;
  2164. if(in_base)
  2165. {
  2166. // Use the given base path.
  2167. SystemTools::SplitPath(in_base, base_components);
  2168. }
  2169. else
  2170. {
  2171. // Use the current working directory as a base path.
  2172. char buf[2048];
  2173. if(const char* cwd = Getcwd(buf, 2048))
  2174. {
  2175. SystemTools::SplitPath(cwd, base_components);
  2176. }
  2177. else
  2178. {
  2179. // ??
  2180. }
  2181. }
  2182. // Append base path components to the output path.
  2183. out_components.push_back(base_components[0]);
  2184. SystemToolsAppendComponents(out_components,
  2185. base_components.begin()+1,
  2186. base_components.end());
  2187. }
  2188. // Append input path components to the output path.
  2189. SystemToolsAppendComponents(out_components,
  2190. path_components.begin(),
  2191. path_components.end());
  2192. // Transform the path back to a string.
  2193. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2194. // Update the translation table with this potentially new path.
  2195. SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2196. SystemTools::CheckTranslationPath(newPath);
  2197. #ifdef _WIN32
  2198. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2199. SystemTools::ConvertToUnixSlashes(newPath);
  2200. #endif
  2201. // Return the reconstructed path.
  2202. return newPath;
  2203. }
  2204. // compute the relative path from here to there
  2205. std::string SystemTools::RelativePath(const char* local, const char* remote)
  2206. {
  2207. if(!SystemTools::FileIsFullPath(local))
  2208. {
  2209. return "";
  2210. }
  2211. if(!SystemTools::FileIsFullPath(remote))
  2212. {
  2213. return "";
  2214. }
  2215. // split up both paths into arrays of strings using / as a separator
  2216. std::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
  2217. std::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
  2218. std::vector<kwsys::String> commonPath; // store shared parts of path in this array
  2219. std::vector<kwsys::String> finalPath; // store the final relative path here
  2220. // count up how many matching directory names there are from the start
  2221. unsigned int sameCount = 0;
  2222. while(
  2223. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  2224. &&
  2225. // for windows and apple do a case insensitive string compare
  2226. #if defined(_WIN32) || defined(__APPLE__)
  2227. cmSystemTools::Strucmp(localSplit[sameCount].c_str(),
  2228. remoteSplit[sameCount].c_str()) == 0
  2229. #else
  2230. localSplit[sameCount] == remoteSplit[sameCount]
  2231. #endif
  2232. )
  2233. {
  2234. // put the common parts of the path into the commonPath array
  2235. commonPath.push_back(localSplit[sameCount]);
  2236. // erase the common parts of the path from the original path arrays
  2237. localSplit[sameCount] = "";
  2238. remoteSplit[sameCount] = "";
  2239. sameCount++;
  2240. }
  2241. // If there is nothing in common but the root directory, then just
  2242. // return the full path.
  2243. if(sameCount <= 1)
  2244. {
  2245. return remote;
  2246. }
  2247. // for each entry that is not common in the local path
  2248. // add a ../ to the finalpath array, this gets us out of the local
  2249. // path into the remote dir
  2250. for(unsigned int i = 0; i < localSplit.size(); ++i)
  2251. {
  2252. if(localSplit[i].size())
  2253. {
  2254. finalPath.push_back("../");
  2255. }
  2256. }
  2257. // for each entry that is not common in the remote path add it
  2258. // to the final path.
  2259. for(std::vector<kwsys_stl::string>::iterator i = remoteSplit.begin();
  2260. i != remoteSplit.end(); ++i)
  2261. {
  2262. if(i->size())
  2263. {
  2264. finalPath.push_back(*i);
  2265. }
  2266. }
  2267. std::string relativePath; // result string
  2268. // now turn the array of directories into a unix path by puttint /
  2269. // between each entry that does not already have one
  2270. for(std::vector<kwsys_stl::string>::iterator i = finalPath.begin();
  2271. i != finalPath.end(); ++i)
  2272. {
  2273. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  2274. {
  2275. relativePath += "/";
  2276. }
  2277. relativePath += *i;
  2278. }
  2279. return relativePath;
  2280. }
  2281. // OK, some fun stuff to get the actual case of a given path.
  2282. // Basically, you just need to call ShortPath, then GetLongPathName,
  2283. // However, GetLongPathName is not implemented on windows NT and 95,
  2284. // so we have to simulate it on those versions
  2285. #ifdef _WIN32
  2286. int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
  2287. kwsys_stl::string& longPath )
  2288. {
  2289. kwsys_stl::string::size_type iFound = shortPath.rfind('/');
  2290. if (iFound > 1 && iFound != shortPath.npos)
  2291. {
  2292. // recurse to peel off components
  2293. //
  2294. if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
  2295. {
  2296. longPath += '/';
  2297. if (shortPath[1] != '/')
  2298. {
  2299. WIN32_FIND_DATA findData;
  2300. // append the long component name to the path
  2301. //
  2302. if (INVALID_HANDLE_VALUE != ::FindFirstFile
  2303. (shortPath.c_str(), &findData))
  2304. {
  2305. longPath += findData.cFileName;
  2306. }
  2307. else
  2308. {
  2309. // if FindFirstFile fails, return the error code
  2310. //
  2311. longPath = "";
  2312. return 0;
  2313. }
  2314. }
  2315. }
  2316. }
  2317. else
  2318. {
  2319. longPath = shortPath;
  2320. }
  2321. return longPath.size();
  2322. }
  2323. int PortableGetLongPathName(const char* pathIn,
  2324. kwsys_stl::string & longPath)
  2325. {
  2326. kwsys_stl::string shortPath;
  2327. if(!SystemTools::GetShortPath(pathIn, shortPath))
  2328. {
  2329. return 0;
  2330. }
  2331. HMODULE lh = LoadLibrary("Kernel32.dll");
  2332. if(lh)
  2333. {
  2334. FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
  2335. if(proc)
  2336. {
  2337. typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
  2338. GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
  2339. char buffer[MAX_PATH+1];
  2340. int len = (*func)(shortPath.c_str(), buffer, MAX_PATH+1);
  2341. if(len == 0 || len > MAX_PATH+1)
  2342. {
  2343. FreeLibrary(lh);
  2344. return 0;
  2345. }
  2346. longPath = buffer;
  2347. FreeLibrary(lh);
  2348. return len;
  2349. }
  2350. FreeLibrary(lh);
  2351. }
  2352. return OldWindowsGetLongPath(shortPath.c_str(), longPath);
  2353. }
  2354. #endif
  2355. //----------------------------------------------------------------------------
  2356. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  2357. {
  2358. #ifndef _WIN32
  2359. return p;
  2360. #else
  2361. kwsys_stl::string shortPath;
  2362. if(!SystemTools::GetShortPath(p, shortPath))
  2363. {
  2364. return p;
  2365. }
  2366. kwsys_stl::string longPath;
  2367. int len = PortableGetLongPathName(shortPath.c_str(), longPath);
  2368. if(len == 0 || len > MAX_PATH+1)
  2369. {
  2370. return p;
  2371. }
  2372. return longPath;
  2373. #endif
  2374. }
  2375. //----------------------------------------------------------------------------
  2376. void SystemTools::SplitPath(const char* p,
  2377. kwsys_stl::vector<kwsys_stl::string>& components)
  2378. {
  2379. components.clear();
  2380. // Identify the root component.
  2381. const char* c = p;
  2382. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  2383. {
  2384. // Network path.
  2385. components.push_back("//");
  2386. c += 2;
  2387. }
  2388. else if(c[0] == '/')
  2389. {
  2390. // Unix path.
  2391. components.push_back("/");
  2392. c += 1;
  2393. }
  2394. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  2395. {
  2396. // Windows path.
  2397. kwsys_stl::string root = "_:/";
  2398. root[0] = c[0];
  2399. components.push_back(root);
  2400. c += 3;
  2401. }
  2402. else if(c[0] && c[1] == ':')
  2403. {
  2404. // Path relative to a windows drive working directory.
  2405. kwsys_stl::string root = "_:";
  2406. root[0] = c[0];
  2407. components.push_back(root);
  2408. c += 2;
  2409. }
  2410. else
  2411. {
  2412. // Relative path.
  2413. components.push_back("");
  2414. }
  2415. // Parse the remaining components.
  2416. const char* first = c;
  2417. const char* last = first;
  2418. for(;*last; ++last)
  2419. {
  2420. if(*last == '/' || *last == '\\')
  2421. {
  2422. // End of a component. Save it.
  2423. components.push_back(kwsys_stl::string(first, last-first));
  2424. first = last+1;
  2425. }
  2426. }
  2427. // Save the last component unless there were no components.
  2428. if(last != c)
  2429. {
  2430. components.push_back(kwsys_stl::string(first, last-first));
  2431. }
  2432. }
  2433. //----------------------------------------------------------------------------
  2434. kwsys_stl::string
  2435. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2436. {
  2437. kwsys_stl::string result;
  2438. if(components.size() > 0)
  2439. {
  2440. result += components[0];
  2441. }
  2442. if(components.size() > 1)
  2443. {
  2444. result += components[1];
  2445. }
  2446. for(unsigned int i=2; i < components.size(); ++i)
  2447. {
  2448. result += "/";
  2449. result += components[i];
  2450. }
  2451. return result;
  2452. }
  2453. //----------------------------------------------------------------------------
  2454. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2455. {
  2456. #if defined(_WIN32) || defined(__APPLE__)
  2457. return SystemTools::Strucmp(c1, c2) == 0;
  2458. #else
  2459. return strcmp(c1, c2) == 0;
  2460. #endif
  2461. }
  2462. //----------------------------------------------------------------------------
  2463. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  2464. {
  2465. kwsys_stl::string data(str);
  2466. kwsys_stl::string::size_type lpos = 0;
  2467. while(lpos < data.length())
  2468. {
  2469. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  2470. if(rpos == kwsys_stl::string::npos)
  2471. {
  2472. // Line ends at end of string without a newline.
  2473. lines.push_back(data.substr(lpos));
  2474. return false;
  2475. }
  2476. else
  2477. {
  2478. // Line ends in a "\n", remove the character.
  2479. lines.push_back(data.substr(lpos, rpos-lpos));
  2480. }
  2481. lpos = rpos+1;
  2482. }
  2483. return true;
  2484. }
  2485. //----------------------------------------------------------------------------
  2486. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2487. {
  2488. kwsys_stl::string data(str);
  2489. kwsys_stl::string::size_type lpos = 0;
  2490. while(lpos < data.length())
  2491. {
  2492. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2493. if(rpos == kwsys_stl::string::npos)
  2494. {
  2495. // Line ends at end of string without a newline.
  2496. lines.push_back(data.substr(lpos));
  2497. return false;
  2498. }
  2499. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2500. {
  2501. // Line ends in a "\r\n" pair, remove both characters.
  2502. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2503. }
  2504. else
  2505. {
  2506. // Line ends in a "\n", remove the character.
  2507. lines.push_back(data.substr(lpos, rpos-lpos));
  2508. }
  2509. lpos = rpos+1;
  2510. }
  2511. return true;
  2512. }
  2513. /**
  2514. * Return path of a full filename (no trailing slashes).
  2515. * Warning: returned path is converted to Unix slashes format.
  2516. */
  2517. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2518. {
  2519. kwsys_stl::string fn = filename;
  2520. SystemTools::ConvertToUnixSlashes(fn);
  2521. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2522. if(slash_pos != kwsys_stl::string::npos)
  2523. {
  2524. return fn.substr(0, slash_pos);
  2525. }
  2526. else
  2527. {
  2528. return "";
  2529. }
  2530. }
  2531. /**
  2532. * Return file name of a full filename (i.e. file name without path).
  2533. */
  2534. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2535. {
  2536. #if defined(_WIN32)
  2537. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  2538. #else
  2539. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  2540. #endif
  2541. if(slash_pos != kwsys_stl::string::npos)
  2542. {
  2543. return filename.substr(slash_pos + 1);
  2544. }
  2545. else
  2546. {
  2547. return filename;
  2548. }
  2549. }
  2550. /**
  2551. * Return file extension of a full filename (dot included).
  2552. * Warning: this is the longest extension (for example: .tar.gz)
  2553. */
  2554. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2555. {
  2556. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2557. kwsys_stl::string::size_type dot_pos = name.find(".");
  2558. if(dot_pos != kwsys_stl::string::npos)
  2559. {
  2560. return name.substr(dot_pos);
  2561. }
  2562. else
  2563. {
  2564. return "";
  2565. }
  2566. }
  2567. /**
  2568. * Return file extension of a full filename (dot included).
  2569. * Warning: this is the shortest extension (for example: .tar.gz)
  2570. */
  2571. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2572. {
  2573. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2574. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2575. if(dot_pos != kwsys_stl::string::npos)
  2576. {
  2577. return name.substr(dot_pos);
  2578. }
  2579. else
  2580. {
  2581. return "";
  2582. }
  2583. }
  2584. /**
  2585. * Return file name without extension of a full filename (i.e. without path).
  2586. * Warning: it considers the longest extension (for example: .tar.gz)
  2587. */
  2588. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2589. {
  2590. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2591. kwsys_stl::string::size_type dot_pos = name.find(".");
  2592. if(dot_pos != kwsys_stl::string::npos)
  2593. {
  2594. return name.substr(0, dot_pos);
  2595. }
  2596. else
  2597. {
  2598. return name;
  2599. }
  2600. }
  2601. /**
  2602. * Return file name without extension of a full filename (i.e. without path).
  2603. * Warning: it considers the last extension (for example: removes .gz
  2604. * from .tar.gz)
  2605. */
  2606. kwsys_stl::string
  2607. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2608. {
  2609. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2610. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2611. if(dot_pos != kwsys_stl::string::npos)
  2612. {
  2613. return name.substr(0, dot_pos);
  2614. }
  2615. else
  2616. {
  2617. return name;
  2618. }
  2619. }
  2620. bool SystemTools::FileHasSignature(const char *filename,
  2621. const char *signature,
  2622. long offset)
  2623. {
  2624. if (!filename || !signature)
  2625. {
  2626. return false;
  2627. }
  2628. FILE *fp;
  2629. fp = fopen(filename, "rb");
  2630. if (!fp)
  2631. {
  2632. return false;
  2633. }
  2634. fseek(fp, offset, SEEK_SET);
  2635. bool res = false;
  2636. size_t signature_len = strlen(signature);
  2637. char *buffer = new char [signature_len];
  2638. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2639. {
  2640. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2641. }
  2642. delete [] buffer;
  2643. fclose(fp);
  2644. return res;
  2645. }
  2646. SystemTools::FileTypeEnum
  2647. SystemTools::DetectFileType(const char *filename,
  2648. unsigned long length,
  2649. double percent_bin)
  2650. {
  2651. if (!filename || percent_bin < 0)
  2652. {
  2653. return SystemTools::FileTypeUnknown;
  2654. }
  2655. FILE *fp;
  2656. fp = fopen(filename, "rb");
  2657. if (!fp)
  2658. {
  2659. return SystemTools::FileTypeUnknown;
  2660. }
  2661. // Allocate buffer and read bytes
  2662. unsigned char *buffer = new unsigned char [length];
  2663. size_t read_length = fread(buffer, 1, length, fp);
  2664. fclose(fp);
  2665. if (read_length == 0)
  2666. {
  2667. return SystemTools::FileTypeUnknown;
  2668. }
  2669. // Loop over contents and count
  2670. size_t text_count = 0;
  2671. const unsigned char *ptr = buffer;
  2672. const unsigned char *buffer_end = buffer + read_length;
  2673. while (ptr != buffer_end)
  2674. {
  2675. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  2676. *ptr == '\n' ||
  2677. *ptr == '\r' ||
  2678. *ptr == '\t')
  2679. {
  2680. text_count++;
  2681. }
  2682. ptr++;
  2683. }
  2684. delete [] buffer;
  2685. double current_percent_bin =
  2686. ((double)(read_length - text_count) / (double)read_length);
  2687. if (current_percent_bin >= percent_bin)
  2688. {
  2689. return SystemTools::FileTypeBinary;
  2690. }
  2691. return SystemTools::FileTypeText;
  2692. }
  2693. bool SystemTools::LocateFileInDir(const char *filename,
  2694. const char *dir,
  2695. kwsys_stl::string& filename_found,
  2696. int try_filename_dirs)
  2697. {
  2698. if (!filename || !dir)
  2699. {
  2700. return false;
  2701. }
  2702. // Get the basename of 'filename'
  2703. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2704. // Check if 'dir' is really a directory
  2705. // If win32 and matches something like C:, accept it as a dir
  2706. kwsys_stl::string real_dir;
  2707. if (!SystemTools::FileIsDirectory(dir))
  2708. {
  2709. #if _WIN32
  2710. size_t dir_len = strlen(dir);
  2711. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2712. {
  2713. #endif
  2714. real_dir = SystemTools::GetFilenamePath(dir);
  2715. dir = real_dir.c_str();
  2716. #if _WIN32
  2717. }
  2718. #endif
  2719. }
  2720. // Try to find the file in 'dir'
  2721. bool res = false;
  2722. if (filename_base.size() && dir)
  2723. {
  2724. size_t dir_len = strlen(dir);
  2725. int need_slash =
  2726. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2727. kwsys_stl::string temp = dir;
  2728. if (need_slash)
  2729. {
  2730. temp += "/";
  2731. }
  2732. temp += filename_base;
  2733. if (SystemTools::FileExists(filename_found.c_str()))
  2734. {
  2735. res = true;
  2736. filename_found = temp;
  2737. }
  2738. // If not found, we can try harder by appending part of the file to
  2739. // to the directory to look inside.
  2740. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2741. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2742. else if (try_filename_dirs)
  2743. {
  2744. kwsys_stl::string filename_dir(filename);
  2745. kwsys_stl::string filename_dir_base;
  2746. kwsys_stl::string filename_dir_bases;
  2747. do
  2748. {
  2749. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2750. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2751. #if _WIN32
  2752. if (!filename_dir_base.size() ||
  2753. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2754. #else
  2755. if (!filename_dir_base.size())
  2756. #endif
  2757. {
  2758. break;
  2759. }
  2760. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2761. temp = dir;
  2762. if (need_slash)
  2763. {
  2764. temp += "/";
  2765. }
  2766. temp += filename_dir_bases;
  2767. res = SystemTools::LocateFileInDir(
  2768. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2769. } while (!res && filename_dir_base.size());
  2770. }
  2771. }
  2772. return res;
  2773. }
  2774. bool SystemTools::FileIsFullPath(const char* in_name)
  2775. {
  2776. kwsys_stl::string name = in_name;
  2777. #if defined(_WIN32) || defined(__CYGWIN__)
  2778. // On Windows, the name must be at least two characters long.
  2779. if(name.length() < 2)
  2780. {
  2781. return false;
  2782. }
  2783. if(name[1] == ':')
  2784. {
  2785. return true;
  2786. }
  2787. if(name[0] == '\\')
  2788. {
  2789. return true;
  2790. }
  2791. #else
  2792. // On UNIX, the name must be at least one character long.
  2793. if(name.length() < 1)
  2794. {
  2795. return false;
  2796. }
  2797. #endif
  2798. // On UNIX, the name must begin in a '/'.
  2799. // On Windows, if the name begins in a '/', then it is a full
  2800. // network path.
  2801. if(name[0] == '/')
  2802. {
  2803. return true;
  2804. }
  2805. return false;
  2806. }
  2807. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2808. {
  2809. #if defined(WIN32) && !defined(__CYGWIN__)
  2810. const int size = int(strlen(path)) +1; // size of return
  2811. char *buffer = new char[size]; // create a buffer
  2812. char *tempPath = new char[size]; // create a buffer
  2813. int ret;
  2814. // if the path passed in has quotes around it, first remove the quotes
  2815. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2816. {
  2817. strcpy(tempPath,path+1);
  2818. tempPath[strlen(tempPath)-1] = '\0';
  2819. }
  2820. else
  2821. {
  2822. strcpy(tempPath,path);
  2823. }
  2824. buffer[0] = 0;
  2825. ret = GetShortPathName(tempPath, buffer, size);
  2826. if(buffer[0] == 0 || ret > size)
  2827. {
  2828. delete [] buffer;
  2829. delete [] tempPath;
  2830. return false;
  2831. }
  2832. else
  2833. {
  2834. shortPath = buffer;
  2835. delete [] buffer;
  2836. delete [] tempPath;
  2837. return true;
  2838. }
  2839. #else
  2840. shortPath = path;
  2841. return true;
  2842. #endif
  2843. }
  2844. void SystemTools::SplitProgramFromArgs(const char* path,
  2845. kwsys_stl::string& program, kwsys_stl::string& args)
  2846. {
  2847. // see if this is a full path to a program
  2848. // if so then set program to path and args to nothing
  2849. if(SystemTools::FileExists(path))
  2850. {
  2851. program = path;
  2852. args = "";
  2853. return;
  2854. }
  2855. // Try to find the program in the path, note the program
  2856. // may have spaces in its name so we have to look for it
  2857. kwsys_stl::vector<kwsys_stl::string> e;
  2858. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  2859. if(findProg.size())
  2860. {
  2861. program = findProg;
  2862. args = "";
  2863. return;
  2864. }
  2865. // Now try and peel off space separated chunks from the end of the string
  2866. // so the largest path possible is found allowing for spaces in the path
  2867. kwsys_stl::string dir = path;
  2868. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  2869. while(spacePos != kwsys_stl::string::npos)
  2870. {
  2871. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  2872. // See if the file exists
  2873. if(SystemTools::FileExists(tryProg.c_str()))
  2874. {
  2875. program = tryProg;
  2876. // remove trailing spaces from program
  2877. kwsys_stl::string::size_type pos = program.size()-1;
  2878. while(program[pos] == ' ')
  2879. {
  2880. program.erase(pos);
  2881. pos--;
  2882. }
  2883. args = dir.substr(spacePos, dir.size()-spacePos);
  2884. return;
  2885. }
  2886. // Now try and find the the program in the path
  2887. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  2888. if(findProg.size())
  2889. {
  2890. program = findProg;
  2891. // remove trailing spaces from program
  2892. kwsys_stl::string::size_type pos = program.size()-1;
  2893. while(program[pos] == ' ')
  2894. {
  2895. program.erase(pos);
  2896. pos--;
  2897. }
  2898. args = dir.substr(spacePos, dir.size()-spacePos);
  2899. return;
  2900. }
  2901. // move past the space for the next search
  2902. spacePos--;
  2903. spacePos = dir.rfind(' ', spacePos);
  2904. }
  2905. program = "";
  2906. args = "";
  2907. }
  2908. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  2909. {
  2910. char buf[1024];
  2911. time_t t;
  2912. time(&t);
  2913. strftime(buf, sizeof(buf), format, localtime(&t));
  2914. return buf;
  2915. }
  2916. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  2917. {
  2918. kwsys_stl::string str(s);
  2919. if (str.find_first_of("0123456789") == 0)
  2920. {
  2921. str = "_" + str;
  2922. }
  2923. kwsys_stl::string permited_chars("_"
  2924. "abcdefghijklmnopqrstuvwxyz"
  2925. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2926. "0123456789");
  2927. kwsys_stl::string::size_type pos = 0;
  2928. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  2929. {
  2930. str[pos] = '_';
  2931. }
  2932. return str;
  2933. }
  2934. // Due to a buggy stream library on the HP and another on Mac OSX, we
  2935. // need this very carefully written version of getline. Returns true
  2936. // if any data were read before the end-of-file was reached.
  2937. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  2938. bool *has_newline /* = 0 */)
  2939. {
  2940. const int bufferSize = 1024;
  2941. char buffer[bufferSize];
  2942. line = "";
  2943. bool haveData = false;
  2944. if ( has_newline )
  2945. {
  2946. *has_newline = false;
  2947. }
  2948. // If no characters are read from the stream, the end of file has
  2949. // been reached.
  2950. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  2951. {
  2952. haveData = true;
  2953. line.append(buffer);
  2954. // If newline character was read, the gcount includes the
  2955. // character, but the buffer does not. The end of line has been
  2956. // reached.
  2957. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  2958. {
  2959. if ( has_newline )
  2960. {
  2961. *has_newline = true;
  2962. }
  2963. break;
  2964. }
  2965. // The fail bit may be set. Clear it.
  2966. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  2967. }
  2968. return haveData;
  2969. }
  2970. int SystemTools::GetTerminalWidth()
  2971. {
  2972. int width = -1;
  2973. #ifndef _WIN32
  2974. struct winsize ws;
  2975. char *columns; /* Unix98 environment variable */
  2976. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  2977. {
  2978. width = ws.ws_col;
  2979. }
  2980. if(!isatty(STDOUT_FILENO))
  2981. {
  2982. width = -1;
  2983. }
  2984. columns = getenv("COLUMNS");
  2985. if(columns && *columns)
  2986. {
  2987. long t;
  2988. char *endptr;
  2989. t = strtol(columns, &endptr, 0);
  2990. if(endptr && !*endptr && (t>0) && (t<1000))
  2991. {
  2992. width = (int)t;
  2993. }
  2994. }
  2995. if ( width < 9 )
  2996. {
  2997. width = -1;
  2998. }
  2999. #endif
  3000. return width;
  3001. }
  3002. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3003. {
  3004. if ( !file )
  3005. {
  3006. return false;
  3007. }
  3008. struct stat st;
  3009. if ( stat(file, &st) < 0 )
  3010. {
  3011. return false;
  3012. }
  3013. mode = st.st_mode;
  3014. return true;
  3015. }
  3016. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  3017. {
  3018. if ( !file )
  3019. {
  3020. return false;
  3021. }
  3022. if ( !SystemTools::FileExists(file) )
  3023. {
  3024. return false;
  3025. }
  3026. if ( chmod(file, mode) < 0 )
  3027. {
  3028. return false;
  3029. }
  3030. return true;
  3031. }
  3032. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  3033. {
  3034. if ( !fileOrDir || !*fileOrDir )
  3035. {
  3036. return "";
  3037. }
  3038. kwsys_stl::string res = fileOrDir;
  3039. SystemTools::ConvertToUnixSlashes(res);
  3040. kwsys_stl::string::size_type cc = res.size()-1;
  3041. if ( res[cc] == '/' )
  3042. {
  3043. cc --;
  3044. }
  3045. for ( ; cc > 0; cc -- )
  3046. {
  3047. if ( res[cc] == '/' )
  3048. {
  3049. break;
  3050. }
  3051. }
  3052. return res.substr(0, cc);
  3053. }
  3054. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  3055. {
  3056. kwsys_stl::string subdir = cSubdir;
  3057. kwsys_stl::string dir = cDir;
  3058. SystemTools::ConvertToUnixSlashes(dir);
  3059. kwsys_stl::string path = subdir;
  3060. do
  3061. {
  3062. path = SystemTools::GetParentDirectory(path.c_str());
  3063. if ( dir == path )
  3064. {
  3065. return true;
  3066. }
  3067. }
  3068. while ( path.size() > dir.size() );
  3069. return false;
  3070. }
  3071. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  3072. const char* directory, const char* toplevel)
  3073. {
  3074. kwsys_stl::string file = fname;
  3075. SystemTools::ConvertToUnixSlashes(file);
  3076. kwsys_stl::string dir = directory;
  3077. SystemTools::ConvertToUnixSlashes(dir);
  3078. while ( !dir.empty() )
  3079. {
  3080. kwsys_stl::string path = dir + "/" + file;
  3081. if ( SystemTools::FileExists(path.c_str()) )
  3082. {
  3083. return path;
  3084. }
  3085. if ( dir.size() < strlen(toplevel) )
  3086. {
  3087. break;
  3088. }
  3089. dir = SystemTools::GetParentDirectory(dir.c_str());
  3090. }
  3091. return "";
  3092. }
  3093. void SystemTools::Delay(unsigned int msec)
  3094. {
  3095. #ifdef _WIN32
  3096. Sleep(msec);
  3097. #else
  3098. usleep(msec * 1000);
  3099. #endif
  3100. }
  3101. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3102. const char *cmd_line, int *argc, char ***argv)
  3103. {
  3104. if (!cmd_line || !argc || !argv)
  3105. {
  3106. return;
  3107. }
  3108. // A space delimites an argument except when it is inside a quote
  3109. (*argc) = 1;
  3110. size_t cmd_line_len = strlen(cmd_line);
  3111. size_t i;
  3112. for (i = 0; i < cmd_line_len; i++)
  3113. {
  3114. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3115. {
  3116. i++;
  3117. }
  3118. if (i < cmd_line_len)
  3119. {
  3120. if (cmd_line[i] == '\"')
  3121. {
  3122. i++;
  3123. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3124. {
  3125. i++;
  3126. }
  3127. (*argc)++;
  3128. }
  3129. else
  3130. {
  3131. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3132. {
  3133. i++;
  3134. }
  3135. (*argc)++;
  3136. }
  3137. }
  3138. }
  3139. (*argv) = new char* [(*argc) + 1];
  3140. (*argv)[(*argc)] = NULL;
  3141. // Set the first arg to be the exec name
  3142. (*argv)[0] = new char [1024];
  3143. #ifdef _WIN32
  3144. ::GetModuleFileName(0, (*argv)[0], 1024);
  3145. #else
  3146. (*argv)[0][0] = '\0';
  3147. #endif
  3148. // Allocate the others
  3149. int j;
  3150. for (j = 1; j < (*argc); j++)
  3151. {
  3152. (*argv)[j] = new char [cmd_line_len + 10];
  3153. }
  3154. // Grab the args
  3155. size_t pos;
  3156. int argc_idx = 1;
  3157. for (i = 0; i < cmd_line_len; i++)
  3158. {
  3159. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3160. {
  3161. i++;
  3162. }
  3163. if (i < cmd_line_len)
  3164. {
  3165. if (cmd_line[i] == '\"')
  3166. {
  3167. i++;
  3168. pos = i;
  3169. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3170. {
  3171. i++;
  3172. }
  3173. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3174. (*argv)[argc_idx][i - pos] = '\0';
  3175. argc_idx++;
  3176. }
  3177. else
  3178. {
  3179. pos = i;
  3180. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3181. {
  3182. i++;
  3183. }
  3184. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3185. (*argv)[argc_idx][i - pos] = '\0';
  3186. argc_idx++;
  3187. }
  3188. }
  3189. }
  3190. }
  3191. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  3192. {
  3193. kwsys_stl::string res;
  3194. #ifdef _WIN32
  3195. char buffer[256];
  3196. OSVERSIONINFOEX osvi;
  3197. BOOL bOsVersionInfoEx;
  3198. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  3199. // If that fails, try using the OSVERSIONINFO structure.
  3200. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  3201. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  3202. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  3203. if (!bOsVersionInfoEx)
  3204. {
  3205. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3206. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  3207. {
  3208. return 0;
  3209. }
  3210. }
  3211. switch (osvi.dwPlatformId)
  3212. {
  3213. // Test for the Windows NT product family.
  3214. case VER_PLATFORM_WIN32_NT:
  3215. // Test for the specific product family.
  3216. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3217. {
  3218. res += "Microsoft Windows Server 2003 family";
  3219. }
  3220. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  3221. {
  3222. res += "Microsoft Windows XP";
  3223. }
  3224. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3225. {
  3226. res += "Microsoft Windows 2000";
  3227. }
  3228. if (osvi.dwMajorVersion <= 4)
  3229. {
  3230. res += "Microsoft Windows NT";
  3231. }
  3232. // Test for specific product on Windows NT 4.0 SP6 and later.
  3233. if (bOsVersionInfoEx)
  3234. {
  3235. // Test for the workstation type.
  3236. #if (_MSC_VER >= 1300)
  3237. if (osvi.wProductType == VER_NT_WORKSTATION)
  3238. {
  3239. if (osvi.dwMajorVersion == 4)
  3240. {
  3241. res += " Workstation 4.0";
  3242. }
  3243. else if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  3244. {
  3245. res += " Home Edition";
  3246. }
  3247. else
  3248. {
  3249. res += " Professional";
  3250. }
  3251. }
  3252. // Test for the server type.
  3253. else if (osvi.wProductType == VER_NT_SERVER)
  3254. {
  3255. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3256. {
  3257. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3258. {
  3259. res += " Datacenter Edition";
  3260. }
  3261. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3262. {
  3263. res += " Enterprise Edition";
  3264. }
  3265. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  3266. {
  3267. res += " Web Edition";
  3268. }
  3269. else
  3270. {
  3271. res += " Standard Edition";
  3272. }
  3273. }
  3274. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3275. {
  3276. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3277. {
  3278. res += " Datacenter Server";
  3279. }
  3280. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3281. {
  3282. res += " Advanced Server";
  3283. }
  3284. else
  3285. {
  3286. res += " Server";
  3287. }
  3288. }
  3289. else // Windows NT 4.0
  3290. {
  3291. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3292. {
  3293. res += " Server 4.0, Enterprise Edition";
  3294. }
  3295. else
  3296. {
  3297. res += " Server 4.0";
  3298. }
  3299. }
  3300. }
  3301. #endif // Visual Studio 7 and up
  3302. }
  3303. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3304. else
  3305. {
  3306. HKEY hKey;
  3307. #define BUFSIZE 80
  3308. char szProductType[BUFSIZE];
  3309. DWORD dwBufLen=BUFSIZE;
  3310. LONG lRet;
  3311. lRet = RegOpenKeyEx(
  3312. HKEY_LOCAL_MACHINE,
  3313. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3314. 0, KEY_QUERY_VALUE, &hKey);
  3315. if (lRet != ERROR_SUCCESS)
  3316. {
  3317. return 0;
  3318. }
  3319. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  3320. (LPBYTE) szProductType, &dwBufLen);
  3321. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  3322. {
  3323. return 0;
  3324. }
  3325. RegCloseKey(hKey);
  3326. if (lstrcmpi("WINNT", szProductType) == 0)
  3327. {
  3328. res += " Workstation";
  3329. }
  3330. if (lstrcmpi("LANMANNT", szProductType) == 0)
  3331. {
  3332. res += " Server";
  3333. }
  3334. if (lstrcmpi("SERVERNT", szProductType) == 0)
  3335. {
  3336. res += " Advanced Server";
  3337. }
  3338. res += " ";
  3339. sprintf(buffer, "%d", osvi.dwMajorVersion);
  3340. res += buffer;
  3341. res += ".";
  3342. sprintf(buffer, "%d", osvi.dwMinorVersion);
  3343. res += buffer;
  3344. }
  3345. // Display service pack (if any) and build number.
  3346. if (osvi.dwMajorVersion == 4 &&
  3347. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  3348. {
  3349. HKEY hKey;
  3350. LONG lRet;
  3351. // Test for SP6 versus SP6a.
  3352. lRet = RegOpenKeyEx(
  3353. HKEY_LOCAL_MACHINE,
  3354. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  3355. 0, KEY_QUERY_VALUE, &hKey);
  3356. if (lRet == ERROR_SUCCESS)
  3357. {
  3358. res += " Service Pack 6a (Build ";
  3359. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3360. res += buffer;
  3361. res += ")";
  3362. }
  3363. else // Windows NT 4.0 prior to SP6a
  3364. {
  3365. res += " ";
  3366. res += osvi.szCSDVersion;
  3367. res += " (Build ";
  3368. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3369. res += buffer;
  3370. res += ")";
  3371. }
  3372. RegCloseKey(hKey);
  3373. }
  3374. else // Windows NT 3.51 and earlier or Windows 2000 and later
  3375. {
  3376. res += " ";
  3377. res += osvi.szCSDVersion;
  3378. res += " (Build ";
  3379. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3380. res += buffer;
  3381. res += ")";
  3382. }
  3383. break;
  3384. // Test for the Windows 95 product family.
  3385. case VER_PLATFORM_WIN32_WINDOWS:
  3386. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  3387. {
  3388. res += "Microsoft Windows 95";
  3389. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  3390. {
  3391. res += " OSR2";
  3392. }
  3393. }
  3394. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  3395. {
  3396. res += "Microsoft Windows 98";
  3397. if (osvi.szCSDVersion[1] == 'A')
  3398. {
  3399. res += " SE";
  3400. }
  3401. }
  3402. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  3403. {
  3404. res += "Microsoft Windows Millennium Edition";
  3405. }
  3406. break;
  3407. case VER_PLATFORM_WIN32s:
  3408. res += "Microsoft Win32s";
  3409. break;
  3410. }
  3411. #endif
  3412. return res;
  3413. }
  3414. // These must NOT be initialized. Default initialization to zero is
  3415. // necessary.
  3416. unsigned int SystemToolsManagerCount;
  3417. SystemToolsTranslationMap *SystemTools::TranslationMap;
  3418. // SystemToolsManager manages the SystemTools singleton.
  3419. // SystemToolsManager should be included in any translation unit
  3420. // that will use SystemTools or that implements the singleton
  3421. // pattern. It makes sure that the SystemTools singleton is created
  3422. // before and destroyed after all other singletons in CMake.
  3423. SystemToolsManager::SystemToolsManager()
  3424. {
  3425. if(++SystemToolsManagerCount == 1)
  3426. {
  3427. SystemTools::ClassInitialize();
  3428. }
  3429. }
  3430. SystemToolsManager::~SystemToolsManager()
  3431. {
  3432. if(--SystemToolsManagerCount == 0)
  3433. {
  3434. SystemTools::ClassFinalize();
  3435. }
  3436. }
  3437. void SystemTools::ClassInitialize()
  3438. {
  3439. // Allocate the translation map first.
  3440. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  3441. // Add some special translation paths for unix. These are not added
  3442. // for windows because drive letters need to be maintained. Also,
  3443. // there are not sym-links and mount points on windows anyway.
  3444. #if !defined(_WIN32) || defined(__CYGWIN__)
  3445. // Work-around an SGI problem by always adding this mapping:
  3446. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  3447. // The tmp path is frequently a logical path so always keep it:
  3448. SystemTools::AddKeepPath("/tmp/");
  3449. // If the current working directory is a logical path then keep the
  3450. // logical name.
  3451. if(const char* pwd = getenv("PWD"))
  3452. {
  3453. char buf[2048];
  3454. if(const char* cwd = Getcwd(buf, 2048))
  3455. {
  3456. // The current working directory may be a logical path. Find
  3457. // the shortest logical path that still produces the correct
  3458. // physical path.
  3459. kwsys_stl::string cwd_changed;
  3460. kwsys_stl::string pwd_changed;
  3461. // Test progressively shorter logical-to-physical mappings.
  3462. kwsys_stl::string pwd_str = pwd;
  3463. kwsys_stl::string cwd_str = cwd;
  3464. kwsys_stl::string pwd_path;
  3465. Realpath(pwd, pwd_path);
  3466. while(cwd_str == pwd_path && cwd_str != pwd_str)
  3467. {
  3468. // The current pair of paths is a working logical mapping.
  3469. cwd_changed = cwd_str;
  3470. pwd_changed = pwd_str;
  3471. // Strip off one directory level and see if the logical
  3472. // mapping still works.
  3473. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  3474. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  3475. Realpath(pwd_str.c_str(), pwd_path);
  3476. }
  3477. // Add the translation to keep the logical path name.
  3478. if(!cwd_changed.empty() && !pwd_changed.empty())
  3479. {
  3480. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  3481. pwd_changed.c_str());
  3482. }
  3483. }
  3484. }
  3485. #endif
  3486. }
  3487. void SystemTools::ClassFinalize()
  3488. {
  3489. delete SystemTools::TranslationMap;
  3490. }
  3491. } // namespace KWSYS_NAMESPACE
  3492. #if defined(_MSC_VER) && defined(_DEBUG)
  3493. # include <crtdbg.h>
  3494. # include <stdio.h>
  3495. # include <stdlib.h>
  3496. namespace KWSYS_NAMESPACE
  3497. {
  3498. static int SystemToolsDebugReport(int, char* message, int*)
  3499. {
  3500. fprintf(stderr, message);
  3501. exit(1);
  3502. }
  3503. void SystemTools::EnableMSVCDebugHook()
  3504. {
  3505. if(getenv("DART_TEST_FROM_DART"))
  3506. {
  3507. _CrtSetReportHook(SystemToolsDebugReport);
  3508. }
  3509. }
  3510. } // namespace KWSYS_NAMESPACE
  3511. #else
  3512. namespace KWSYS_NAMESPACE
  3513. {
  3514. void SystemTools::EnableMSVCDebugHook() {}
  3515. } // namespace KWSYS_NAMESPACE
  3516. #endif