SystemTools.cxx 135 KB

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