SystemTools.cxx 134 KB

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