SystemTools.cxx 141 KB

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