SystemTools.cxx 139 KB

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