SystemTools.cxx 111 KB

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