SystemTools.cxx 132 KB

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