SystemTools.cxx 138 KB

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