1
0

SystemTools.cxx 134 KB

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