SystemTools.cxx 126 KB

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