SystemTools.cxx 115 KB

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