SystemTools.cxx 104 KB

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