SystemTools.cxx 132 KB

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