SystemTools.cxx 129 KB

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