SystemTools.cxx 135 KB

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