SystemTools.cxx 137 KB

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