1
0

SystemTools.cxx 139 KB

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