SystemTools.cxx 127 KB

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