SystemTools.cxx 128 KB

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