SystemTools.cxx 127 KB

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