cmSystemTools.cxx 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #if defined(_MSC_VER) && _MSC_VER < 1300
  11. # define _WIN32_WINNT 0x0400 /* for wincrypt.h */
  12. #endif
  13. #include "cmSystemTools.h"
  14. #include <ctype.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <string.h>
  18. #include <stdlib.h>
  19. #ifdef __QNX__
  20. # include <malloc.h> /* for malloc/free on QNX */
  21. #endif
  22. #include <cmsys/Glob.hxx>
  23. #include <cmsys/RegularExpression.hxx>
  24. #include <cmsys/Directory.hxx>
  25. #include <cmsys/System.h>
  26. #if defined(CMAKE_BUILD_WITH_CMAKE)
  27. # include "cmArchiveWrite.h"
  28. # include <cm_libarchive.h>
  29. # include <cmsys/Terminal.h>
  30. #endif
  31. #include <cmsys/stl/algorithm>
  32. #if defined(_WIN32)
  33. # include <windows.h>
  34. # include <wincrypt.h>
  35. #else
  36. # include <sys/time.h>
  37. # include <sys/types.h>
  38. # include <unistd.h>
  39. # include <utime.h>
  40. # include <sys/wait.h>
  41. #endif
  42. #include <sys/stat.h>
  43. #if defined(_WIN32) && \
  44. (defined(_MSC_VER) || defined(__WATCOMC__) || \
  45. defined(__BORLANDC__) || defined(__MINGW32__))
  46. # include <io.h>
  47. #endif
  48. #if defined(CMAKE_BUILD_WITH_CMAKE)
  49. # include <fcntl.h>
  50. # include "cmCryptoHash.h"
  51. #endif
  52. #if defined(CMAKE_USE_ELF_PARSER)
  53. # include "cmELF.h"
  54. #endif
  55. class cmSystemToolsFileTime
  56. {
  57. public:
  58. #if defined(_WIN32) && !defined(__CYGWIN__)
  59. FILETIME timeCreation;
  60. FILETIME timeLastAccess;
  61. FILETIME timeLastWrite;
  62. #else
  63. struct utimbuf timeBuf;
  64. #endif
  65. };
  66. #if defined(__sgi) && !defined(__GNUC__)
  67. # pragma set woff 1375 /* base class destructor not virtual */
  68. #endif
  69. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  70. // For GetEnvironmentVariables
  71. # if defined(_WIN32)
  72. extern __declspec( dllimport ) char** environ;
  73. # else
  74. extern char** environ;
  75. # endif
  76. #endif
  77. #ifdef _WIN32
  78. class cmSystemToolsWindowsHandle
  79. {
  80. public:
  81. cmSystemToolsWindowsHandle(HANDLE h): handle_(h) {}
  82. ~cmSystemToolsWindowsHandle()
  83. {
  84. if(this->handle_ != INVALID_HANDLE_VALUE)
  85. {
  86. CloseHandle(this->handle_);
  87. }
  88. }
  89. operator bool() const { return this->handle_ != INVALID_HANDLE_VALUE; }
  90. bool operator !() const { return this->handle_ == INVALID_HANDLE_VALUE; }
  91. operator HANDLE() const { return this->handle_; }
  92. private:
  93. HANDLE handle_;
  94. };
  95. #elif defined(__APPLE__)
  96. #include <crt_externs.h>
  97. #define environ (*_NSGetEnviron())
  98. #endif
  99. bool cmSystemTools::s_RunCommandHideConsole = false;
  100. bool cmSystemTools::s_DisableRunCommandOutput = false;
  101. bool cmSystemTools::s_ErrorOccured = false;
  102. bool cmSystemTools::s_FatalErrorOccured = false;
  103. bool cmSystemTools::s_DisableMessages = false;
  104. bool cmSystemTools::s_ForceUnixPaths = false;
  105. std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
  106. void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
  107. {
  108. if ( str )
  109. {
  110. cmSystemTools::s_Windows9xComspecSubstitute = str;
  111. }
  112. }
  113. const char* cmSystemTools::GetWindows9xComspecSubstitute()
  114. {
  115. return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
  116. }
  117. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*,
  118. bool&, void*);
  119. void (*cmSystemTools::s_StdoutCallback)(const char*, int len, void*);
  120. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  121. void* cmSystemTools::s_StdoutCallbackClientData = 0;
  122. bool (*cmSystemTools::s_InterruptCallback)(void*);
  123. void* cmSystemTools::s_InterruptCallbackClientData = 0;
  124. // replace replace with with as many times as it shows up in source.
  125. // write the result into source.
  126. #if defined(_WIN32) && !defined(__CYGWIN__)
  127. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  128. {
  129. // Regular expression to match anything inside [...] that begins in HKEY.
  130. // Note that there is a special rule for regular expressions to match a
  131. // close square-bracket inside a list delimited by square brackets.
  132. // The "[^]]" part of this expression will match any character except
  133. // a close square-bracket. The ']' character must be the first in the
  134. // list of characters inside the [^...] block of the expression.
  135. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  136. // check for black line or comment
  137. while (regEntry.find(source))
  138. {
  139. // the arguments are the second match
  140. std::string key = regEntry.match(1);
  141. std::string val;
  142. if (ReadRegistryValue(key.c_str(), val, view))
  143. {
  144. std::string reg = "[";
  145. reg += key + "]";
  146. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  147. }
  148. else
  149. {
  150. std::string reg = "[";
  151. reg += key + "]";
  152. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  153. }
  154. }
  155. }
  156. #else
  157. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64)
  158. {
  159. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  160. while (regEntry.find(source))
  161. {
  162. // the arguments are the second match
  163. std::string key = regEntry.match(1);
  164. std::string val;
  165. std::string reg = "[";
  166. reg += key + "]";
  167. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  168. }
  169. }
  170. #endif
  171. std::string cmSystemTools::EscapeQuotes(const char* str)
  172. {
  173. std::string result = "";
  174. for(const char* ch = str; *ch != '\0'; ++ch)
  175. {
  176. if(*ch == '"')
  177. {
  178. result += '\\';
  179. }
  180. result += *ch;
  181. }
  182. return result;
  183. }
  184. std::string cmSystemTools::TrimWhitespace(const std::string& s)
  185. {
  186. std::string::const_iterator start = s.begin();
  187. while(start != s.end() && *start <= ' ')
  188. ++start;
  189. if (start == s.end())
  190. return "";
  191. std::string::const_iterator stop = s.end()-1;
  192. while(*stop <= ' ')
  193. --stop;
  194. return std::string(start, stop+1);
  195. }
  196. void cmSystemTools::Error(const char* m1, const char* m2,
  197. const char* m3, const char* m4)
  198. {
  199. std::string message = "CMake Error: ";
  200. if(m1)
  201. {
  202. message += m1;
  203. }
  204. if(m2)
  205. {
  206. message += m2;
  207. }
  208. if(m3)
  209. {
  210. message += m3;
  211. }
  212. if(m4)
  213. {
  214. message += m4;
  215. }
  216. cmSystemTools::s_ErrorOccured = true;
  217. cmSystemTools::Message(message.c_str(),"Error");
  218. }
  219. void cmSystemTools::SetInterruptCallback(InterruptCallback f, void* clientData)
  220. {
  221. s_InterruptCallback = f;
  222. s_InterruptCallbackClientData = clientData;
  223. }
  224. bool cmSystemTools::GetInterruptFlag()
  225. {
  226. if(s_InterruptCallback)
  227. {
  228. return (*s_InterruptCallback)(s_InterruptCallbackClientData);
  229. }
  230. return false;
  231. }
  232. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  233. {
  234. s_ErrorCallback = f;
  235. s_ErrorCallbackClientData = clientData;
  236. }
  237. void cmSystemTools::SetStdoutCallback(StdoutCallback f, void* clientData)
  238. {
  239. s_StdoutCallback = f;
  240. s_StdoutCallbackClientData = clientData;
  241. }
  242. void cmSystemTools::Stdout(const char* s)
  243. {
  244. if(s_StdoutCallback)
  245. {
  246. (*s_StdoutCallback)(s, static_cast<int>(strlen(s)),
  247. s_StdoutCallbackClientData);
  248. }
  249. else
  250. {
  251. std::cout << s;
  252. std::cout.flush();
  253. }
  254. }
  255. void cmSystemTools::Stderr(const char* s, int length)
  256. {
  257. std::cerr.write(s, length);
  258. std::cerr.flush();
  259. }
  260. void cmSystemTools::Stdout(const char* s, int length)
  261. {
  262. if(s_StdoutCallback)
  263. {
  264. (*s_StdoutCallback)(s, length, s_StdoutCallbackClientData);
  265. }
  266. else
  267. {
  268. std::cout.write(s, length);
  269. std::cout.flush();
  270. }
  271. }
  272. void cmSystemTools::Message(const char* m1, const char *title)
  273. {
  274. if(s_DisableMessages)
  275. {
  276. return;
  277. }
  278. if(s_ErrorCallback)
  279. {
  280. (*s_ErrorCallback)(m1, title, s_DisableMessages,
  281. s_ErrorCallbackClientData);
  282. return;
  283. }
  284. else
  285. {
  286. std::cerr << m1 << std::endl << std::flush;
  287. }
  288. }
  289. void cmSystemTools::ReportLastSystemError(const char* msg)
  290. {
  291. std::string m = msg;
  292. m += ": System Error: ";
  293. m += Superclass::GetLastSystemError();
  294. cmSystemTools::Error(m.c_str());
  295. }
  296. bool cmSystemTools::IsInternallyOn(const char* val)
  297. {
  298. if (!val)
  299. {
  300. return false;
  301. }
  302. std::basic_string<char> v = val;
  303. for(std::basic_string<char>::iterator c = v.begin();
  304. c != v.end(); c++)
  305. {
  306. *c = static_cast<char>(toupper(*c));
  307. }
  308. return (v == "I_ON" || v == "i_on");
  309. }
  310. bool cmSystemTools::IsOn(const char* val)
  311. {
  312. if (!val)
  313. {
  314. return false;
  315. }
  316. std::basic_string<char> v = val;
  317. for(std::basic_string<char>::iterator c = v.begin();
  318. c != v.end(); c++)
  319. {
  320. *c = static_cast<char>(toupper(*c));
  321. }
  322. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  323. }
  324. bool cmSystemTools::IsNOTFOUND(const char* val)
  325. {
  326. size_t len = strlen(val);
  327. const char* notfound = "-NOTFOUND";
  328. const size_t lenNotFound = 9;
  329. if(len < lenNotFound-1)
  330. {
  331. return false;
  332. }
  333. if(len == lenNotFound-1)
  334. {
  335. return ( strcmp(val, "NOTFOUND") == 0);
  336. }
  337. return ((strncmp((val + (len - lenNotFound)), notfound, lenNotFound) == 0));
  338. }
  339. bool cmSystemTools::IsOff(const char* val)
  340. {
  341. if (!val || strlen(val) == 0)
  342. {
  343. return true;
  344. }
  345. std::basic_string<char> v = val;
  346. for(std::basic_string<char>::iterator c = v.begin();
  347. c != v.end(); c++)
  348. {
  349. *c = static_cast<char>(toupper(*c));
  350. }
  351. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  352. v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");
  353. }
  354. //----------------------------------------------------------------------------
  355. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  356. std::vector<std::string>& args)
  357. {
  358. // See the MSDN document "Parsing C Command-Line Arguments" at
  359. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  360. // of parsing the windows command line.
  361. bool in_argument = false;
  362. bool in_quotes = false;
  363. int backslashes = 0;
  364. std::string arg;
  365. for(const char* c = command;*c; ++c)
  366. {
  367. if(*c == '\\')
  368. {
  369. ++backslashes;
  370. in_argument = true;
  371. }
  372. else if(*c == '"')
  373. {
  374. int backslash_pairs = backslashes >> 1;
  375. int backslash_escaped = backslashes & 1;
  376. arg.append(backslash_pairs, '\\');
  377. backslashes = 0;
  378. if(backslash_escaped)
  379. {
  380. /* An odd number of backslashes precede this quote.
  381. It is escaped. */
  382. arg.append(1, '"');
  383. }
  384. else
  385. {
  386. /* An even number of backslashes precede this quote.
  387. It is not escaped. */
  388. in_quotes = !in_quotes;
  389. }
  390. in_argument = true;
  391. }
  392. else
  393. {
  394. arg.append(backslashes, '\\');
  395. backslashes = 0;
  396. if(isspace(*c))
  397. {
  398. if(in_quotes)
  399. {
  400. arg.append(1, *c);
  401. }
  402. else if(in_argument)
  403. {
  404. args.push_back(arg);
  405. arg = "";
  406. in_argument = false;
  407. }
  408. }
  409. else
  410. {
  411. in_argument = true;
  412. arg.append(1, *c);
  413. }
  414. }
  415. }
  416. arg.append(backslashes, '\\');
  417. if(in_argument)
  418. {
  419. args.push_back(arg);
  420. }
  421. }
  422. //----------------------------------------------------------------------------
  423. class cmSystemToolsArgV
  424. {
  425. char** ArgV;
  426. public:
  427. cmSystemToolsArgV(char** argv): ArgV(argv) {}
  428. ~cmSystemToolsArgV()
  429. {
  430. for(char** arg = this->ArgV; arg && *arg; ++arg)
  431. {
  432. free(*arg);
  433. }
  434. free(this->ArgV);
  435. }
  436. void Store(std::vector<std::string>& args) const
  437. {
  438. for(char** arg = this->ArgV; arg && *arg; ++arg)
  439. {
  440. args.push_back(*arg);
  441. }
  442. }
  443. void Store(std::vector<cmStdString>& args) const
  444. {
  445. for(char** arg = this->ArgV; arg && *arg; ++arg)
  446. {
  447. args.push_back(*arg);
  448. }
  449. }
  450. };
  451. //----------------------------------------------------------------------------
  452. void cmSystemTools::ParseUnixCommandLine(const char* command,
  453. std::vector<std::string>& args)
  454. {
  455. // Invoke the underlying parser.
  456. cmSystemToolsArgV argv = cmsysSystem_Parse_CommandForUnix(command, 0);
  457. argv.Store(args);
  458. }
  459. //----------------------------------------------------------------------------
  460. void cmSystemTools::ParseUnixCommandLine(const char* command,
  461. std::vector<cmStdString>& args)
  462. {
  463. // Invoke the underlying parser.
  464. cmSystemToolsArgV argv = cmsysSystem_Parse_CommandForUnix(command, 0);
  465. argv.Store(args);
  466. }
  467. std::string cmSystemTools::EscapeWindowsShellArgument(const char* arg,
  468. int shell_flags)
  469. {
  470. char local_buffer[1024];
  471. char* buffer = local_buffer;
  472. int size = cmsysSystem_Shell_GetArgumentSizeForWindows(arg, shell_flags);
  473. if(size > 1024)
  474. {
  475. buffer = new char[size];
  476. }
  477. cmsysSystem_Shell_GetArgumentForWindows(arg, buffer, shell_flags);
  478. std::string result(buffer);
  479. if(buffer != local_buffer)
  480. {
  481. delete [] buffer;
  482. }
  483. return result;
  484. }
  485. std::vector<cmStdString> cmSystemTools::ParseArguments(const char* command)
  486. {
  487. std::vector<cmStdString> args;
  488. std::string arg;
  489. bool win_path = false;
  490. if ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  491. (command[0] == '\"' && command[1] != '/' && command[2] == ':'
  492. && command[3] == '\\') ||
  493. (command[0] == '\'' && command[1] != '/' && command[2] == ':'
  494. && command[3] == '\\') ||
  495. (command[0] == '\\' && command[1] == '\\'))
  496. {
  497. win_path = true;
  498. }
  499. // Split the command into an argv array.
  500. for(const char* c = command; *c;)
  501. {
  502. // Skip over whitespace.
  503. while(*c == ' ' || *c == '\t')
  504. {
  505. ++c;
  506. }
  507. arg = "";
  508. if(*c == '"')
  509. {
  510. // Parse a quoted argument.
  511. ++c;
  512. while(*c && *c != '"')
  513. {
  514. arg.append(1, *c);
  515. ++c;
  516. }
  517. if(*c)
  518. {
  519. ++c;
  520. }
  521. args.push_back(arg);
  522. }
  523. else if(*c == '\'')
  524. {
  525. // Parse a quoted argument.
  526. ++c;
  527. while(*c && *c != '\'')
  528. {
  529. arg.append(1, *c);
  530. ++c;
  531. }
  532. if(*c)
  533. {
  534. ++c;
  535. }
  536. args.push_back(arg);
  537. }
  538. else if(*c)
  539. {
  540. // Parse an unquoted argument.
  541. while(*c && *c != ' ' && *c != '\t')
  542. {
  543. if(*c == '\\' && !win_path)
  544. {
  545. ++c;
  546. if(*c)
  547. {
  548. arg.append(1, *c);
  549. ++c;
  550. }
  551. }
  552. else
  553. {
  554. arg.append(1, *c);
  555. ++c;
  556. }
  557. }
  558. args.push_back(arg);
  559. }
  560. }
  561. return args;
  562. }
  563. bool cmSystemTools::RunSingleCommand(std::vector<cmStdString>const& command,
  564. std::string* output ,
  565. int* retVal , const char* dir ,
  566. OutputOption outputflag ,
  567. double timeout )
  568. {
  569. std::vector<const char*> argv;
  570. for(std::vector<cmStdString>::const_iterator a = command.begin();
  571. a != command.end(); ++a)
  572. {
  573. argv.push_back(a->c_str());
  574. }
  575. argv.push_back(0);
  576. if ( output )
  577. {
  578. *output = "";
  579. }
  580. cmsysProcess* cp = cmsysProcess_New();
  581. cmsysProcess_SetCommand(cp, &*argv.begin());
  582. cmsysProcess_SetWorkingDirectory(cp, dir);
  583. if(cmSystemTools::GetRunCommandHideConsole())
  584. {
  585. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  586. }
  587. cmsysProcess_SetTimeout(cp, timeout);
  588. cmsysProcess_Execute(cp);
  589. std::vector<char> tempOutput;
  590. char* data;
  591. int length;
  592. int pipe;
  593. if ( output || outputflag != OUTPUT_NONE )
  594. {
  595. while((pipe = cmsysProcess_WaitForData(cp, &data, &length, 0)) > 0)
  596. {
  597. if(output || outputflag != OUTPUT_NONE)
  598. {
  599. // Translate NULL characters in the output into valid text.
  600. // Visual Studio 7 puts these characters in the output of its
  601. // build process.
  602. for(int i=0; i < length; ++i)
  603. {
  604. if(data[i] == '\0')
  605. {
  606. data[i] = ' ';
  607. }
  608. }
  609. }
  610. if ( output )
  611. {
  612. tempOutput.insert(tempOutput.end(), data, data+length);
  613. }
  614. if(outputflag != OUTPUT_NONE)
  615. {
  616. if(outputflag == OUTPUT_MERGE)
  617. {
  618. cmSystemTools::Stdout(data, length);
  619. }
  620. else
  621. {
  622. if(pipe == cmsysProcess_Pipe_STDERR)
  623. {
  624. cmSystemTools::Stderr(data, length);
  625. }
  626. else if(pipe == cmsysProcess_Pipe_STDOUT)
  627. {
  628. cmSystemTools::Stdout(data, length);
  629. }
  630. }
  631. }
  632. }
  633. }
  634. cmsysProcess_WaitForExit(cp, 0);
  635. if ( output && tempOutput.begin() != tempOutput.end())
  636. {
  637. output->append(&*tempOutput.begin(), tempOutput.size());
  638. }
  639. bool result = true;
  640. if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
  641. {
  642. if ( retVal )
  643. {
  644. *retVal = cmsysProcess_GetExitValue(cp);
  645. }
  646. else
  647. {
  648. if ( cmsysProcess_GetExitValue(cp) != 0 )
  649. {
  650. result = false;
  651. }
  652. }
  653. }
  654. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
  655. {
  656. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  657. if ( outputflag != OUTPUT_NONE )
  658. {
  659. std::cerr << exception_str << std::endl;
  660. }
  661. if ( output )
  662. {
  663. output->append(exception_str, strlen(exception_str));
  664. }
  665. result = false;
  666. }
  667. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  668. {
  669. const char* error_str = cmsysProcess_GetErrorString(cp);
  670. if ( outputflag != OUTPUT_NONE )
  671. {
  672. std::cerr << error_str << std::endl;
  673. }
  674. if ( output )
  675. {
  676. output->append(error_str, strlen(error_str));
  677. }
  678. result = false;
  679. }
  680. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  681. {
  682. const char* error_str = "Process terminated due to timeout\n";
  683. if ( outputflag != OUTPUT_NONE )
  684. {
  685. std::cerr << error_str << std::endl;
  686. }
  687. if ( output )
  688. {
  689. output->append(error_str, strlen(error_str));
  690. }
  691. result = false;
  692. }
  693. cmsysProcess_Delete(cp);
  694. return result;
  695. }
  696. bool cmSystemTools::RunSingleCommand(
  697. const char* command,
  698. std::string* output,
  699. int *retVal,
  700. const char* dir,
  701. OutputOption outputflag,
  702. double timeout)
  703. {
  704. if(s_DisableRunCommandOutput)
  705. {
  706. outputflag = OUTPUT_NONE;
  707. }
  708. std::vector<cmStdString> args = cmSystemTools::ParseArguments(command);
  709. if(args.size() < 1)
  710. {
  711. return false;
  712. }
  713. return cmSystemTools::RunSingleCommand(args, output,retVal,
  714. dir, outputflag, timeout);
  715. }
  716. bool cmSystemTools::RunCommand(const char* command,
  717. std::string& output,
  718. const char* dir,
  719. bool verbose,
  720. int timeout)
  721. {
  722. int dummy;
  723. return cmSystemTools::RunCommand(command, output, dummy,
  724. dir, verbose, timeout);
  725. }
  726. #if defined(WIN32) && !defined(__CYGWIN__)
  727. #include "cmWin32ProcessExecution.h"
  728. // use this for shell commands like echo and dir
  729. bool RunCommandViaWin32(const char* command,
  730. const char* dir,
  731. std::string& output,
  732. int& retVal,
  733. bool verbose,
  734. int timeout)
  735. {
  736. #if defined(__BORLANDC__)
  737. return
  738. cmWin32ProcessExecution::
  739. BorlandRunCommand(command, dir, output,
  740. retVal,
  741. verbose, timeout,
  742. cmSystemTools::GetRunCommandHideConsole());
  743. #else // Visual studio
  744. ::SetLastError(ERROR_SUCCESS);
  745. if ( ! command )
  746. {
  747. cmSystemTools::Error("No command specified");
  748. return false;
  749. }
  750. cmWin32ProcessExecution resProc;
  751. if(cmSystemTools::GetRunCommandHideConsole())
  752. {
  753. resProc.SetHideWindows(true);
  754. }
  755. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  756. {
  757. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  758. }
  759. if ( !resProc.StartProcess(command, dir, verbose) )
  760. {
  761. output = resProc.GetOutput();
  762. if(verbose)
  763. {
  764. cmSystemTools::Stdout(output.c_str());
  765. }
  766. return false;
  767. }
  768. resProc.Wait(timeout);
  769. output = resProc.GetOutput();
  770. retVal = resProc.GetExitValue();
  771. return true;
  772. #endif
  773. }
  774. // use this for shell commands like echo and dir
  775. bool RunCommandViaSystem(const char* command,
  776. const char* dir,
  777. std::string& output,
  778. int& retVal,
  779. bool verbose)
  780. {
  781. std::cout << "@@ " << command << std::endl;
  782. std::string commandInDir;
  783. if(dir)
  784. {
  785. commandInDir = "cd ";
  786. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  787. commandInDir += " && ";
  788. commandInDir += command;
  789. }
  790. else
  791. {
  792. commandInDir = command;
  793. }
  794. command = commandInDir.c_str();
  795. std::string commandToFile = command;
  796. commandToFile += " > ";
  797. std::string tempFile;
  798. tempFile += _tempnam(0, "cmake");
  799. commandToFile += tempFile;
  800. retVal = system(commandToFile.c_str());
  801. std::ifstream fin(tempFile.c_str());
  802. if(!fin)
  803. {
  804. if(verbose)
  805. {
  806. std::string errormsg = "RunCommand produced no output: command: \"";
  807. errormsg += command;
  808. errormsg += "\"";
  809. errormsg += "\nOutput file: ";
  810. errormsg += tempFile;
  811. cmSystemTools::Error(errormsg.c_str());
  812. }
  813. fin.close();
  814. cmSystemTools::RemoveFile(tempFile.c_str());
  815. return false;
  816. }
  817. bool multiLine = false;
  818. std::string line;
  819. while(cmSystemTools::GetLineFromStream(fin, line))
  820. {
  821. output += line;
  822. if(multiLine)
  823. {
  824. output += "\n";
  825. }
  826. multiLine = true;
  827. }
  828. fin.close();
  829. cmSystemTools::RemoveFile(tempFile.c_str());
  830. return true;
  831. }
  832. #else // We have popen
  833. // BeOS seems to return from a successful pclose() before the process has
  834. // legitimately exited, or at least before SIGCHLD is thrown...the signal may
  835. // come quite some time after pclose returns! This causes havoc with later
  836. // parts of CMake that expect to catch the signal from other child processes,
  837. // so we explicitly wait to catch it here. This should be safe to do with
  838. // popen() so long as we don't actually collect the zombie process ourselves.
  839. #ifdef __BEOS__
  840. #include <signal.h>
  841. #undef SIGBUS // this is the same as SIGSEGV on BeOS and causes issues below.
  842. static volatile bool beos_seen_signal = false;
  843. static void beos_popen_workaround(int sig)
  844. {
  845. beos_seen_signal = true;
  846. }
  847. #endif
  848. bool RunCommandViaPopen(const char* command,
  849. const char* dir,
  850. std::string& output,
  851. int& retVal,
  852. bool verbose,
  853. int /*timeout*/)
  854. {
  855. // if only popen worked on windows.....
  856. std::string commandInDir;
  857. if(dir)
  858. {
  859. commandInDir = "cd \"";
  860. commandInDir += dir;
  861. commandInDir += "\" && ";
  862. commandInDir += command;
  863. }
  864. else
  865. {
  866. commandInDir = command;
  867. }
  868. #ifndef __VMS
  869. commandInDir += " 2>&1";
  870. #endif
  871. command = commandInDir.c_str();
  872. const int BUFFER_SIZE = 4096;
  873. char buffer[BUFFER_SIZE];
  874. if(verbose)
  875. {
  876. cmSystemTools::Stdout("running ");
  877. cmSystemTools::Stdout(command);
  878. cmSystemTools::Stdout("\n");
  879. }
  880. fflush(stdout);
  881. fflush(stderr);
  882. #ifdef __BEOS__
  883. beos_seen_signal = false;
  884. signal(SIGCHLD, beos_popen_workaround);
  885. #endif
  886. FILE* cpipe = popen(command, "r");
  887. if(!cpipe)
  888. {
  889. #ifdef __BEOS__
  890. signal(SIGCHLD, SIG_DFL);
  891. #endif
  892. return false;
  893. }
  894. if (!fgets(buffer, BUFFER_SIZE, cpipe))
  895. {
  896. buffer[0] = 0;
  897. }
  898. while(!feof(cpipe))
  899. {
  900. if(verbose)
  901. {
  902. cmSystemTools::Stdout(buffer);
  903. }
  904. output += buffer;
  905. if(!fgets(buffer, BUFFER_SIZE, cpipe))
  906. {
  907. buffer[0] = 0;
  908. }
  909. }
  910. retVal = pclose(cpipe);
  911. #ifdef __BEOS__
  912. for (int i = 0; (!beos_seen_signal) && (i < 3); i++)
  913. {
  914. ::sleep(1); // signals should interrupt this...
  915. }
  916. if (!beos_seen_signal)
  917. {
  918. signal(SIGCHLD, SIG_DFL); // oh well, didn't happen. Go on anyhow.
  919. }
  920. #endif
  921. if (WIFEXITED(retVal))
  922. {
  923. retVal = WEXITSTATUS(retVal);
  924. return true;
  925. }
  926. if (WIFSIGNALED(retVal))
  927. {
  928. retVal = WTERMSIG(retVal);
  929. cmOStringStream error;
  930. error << "\nProcess terminated due to ";
  931. switch (retVal)
  932. {
  933. #ifdef SIGKILL
  934. case SIGKILL:
  935. error << "SIGKILL";
  936. break;
  937. #endif
  938. #ifdef SIGFPE
  939. case SIGFPE:
  940. error << "SIGFPE";
  941. break;
  942. #endif
  943. #ifndef __HAIKU__
  944. #ifdef SIGBUS
  945. case SIGBUS:
  946. error << "SIGBUS";
  947. break;
  948. #endif
  949. #endif
  950. #ifdef SIGSEGV
  951. case SIGSEGV:
  952. error << "SIGSEGV";
  953. break;
  954. #endif
  955. default:
  956. error << "signal " << retVal;
  957. break;
  958. }
  959. output += error.str();
  960. }
  961. return false;
  962. }
  963. #endif // endif WIN32 not CYGWIN
  964. // run a command unix uses popen (easy)
  965. // windows uses system and ShortPath
  966. bool cmSystemTools::RunCommand(const char* command,
  967. std::string& output,
  968. int &retVal,
  969. const char* dir,
  970. bool verbose,
  971. int timeout)
  972. {
  973. if(s_DisableRunCommandOutput)
  974. {
  975. verbose = false;
  976. }
  977. #if defined(WIN32) && !defined(__CYGWIN__)
  978. // if the command does not start with a quote, then
  979. // try to find the program, and if the program can not be
  980. // found use system to run the command as it must be a built in
  981. // shell command like echo or dir
  982. int count = 0;
  983. if(command[0] == '\"')
  984. {
  985. // count the number of quotes
  986. for(const char* s = command; *s != 0; ++s)
  987. {
  988. if(*s == '\"')
  989. {
  990. count++;
  991. if(count > 2)
  992. {
  993. break;
  994. }
  995. }
  996. }
  997. // if there are more than two double quotes use
  998. // GetShortPathName, the cmd.exe program in windows which
  999. // is used by system fails to execute if there are more than
  1000. // one set of quotes in the arguments
  1001. if(count > 2)
  1002. {
  1003. cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1004. if(quoted.find(command))
  1005. {
  1006. std::string shortCmd;
  1007. std::string cmd = quoted.match(1);
  1008. std::string args = quoted.match(2);
  1009. if(! cmSystemTools::FileExists(cmd.c_str()) )
  1010. {
  1011. shortCmd = cmd;
  1012. }
  1013. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1014. {
  1015. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1016. return false;
  1017. }
  1018. shortCmd += " ";
  1019. shortCmd += args;
  1020. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  1021. // output, retVal, verbose);
  1022. //return WindowsRunCommand(shortCmd.c_str(), dir,
  1023. //output, retVal, verbose);
  1024. return RunCommandViaWin32(shortCmd.c_str(), dir,
  1025. output, retVal, verbose, timeout);
  1026. }
  1027. else
  1028. {
  1029. cmSystemTools::Error("Could not parse command line with quotes ",
  1030. command);
  1031. }
  1032. }
  1033. }
  1034. // if there is only one set of quotes or no quotes then just run the command
  1035. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1036. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  1037. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  1038. #else
  1039. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  1040. #endif
  1041. }
  1042. bool cmSystemTools::DoesFileExistWithExtensions(
  1043. const char* name,
  1044. const std::vector<std::string>& headerExts)
  1045. {
  1046. std::string hname;
  1047. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  1048. ext != headerExts.end(); ++ext )
  1049. {
  1050. hname = name;
  1051. hname += ".";
  1052. hname += *ext;
  1053. if(cmSystemTools::FileExists(hname.c_str()))
  1054. {
  1055. return true;
  1056. }
  1057. }
  1058. return false;
  1059. }
  1060. std::string cmSystemTools::FileExistsInParentDirectories(const char* fname,
  1061. const char* directory, const char* toplevel)
  1062. {
  1063. std::string file = fname;
  1064. cmSystemTools::ConvertToUnixSlashes(file);
  1065. std::string dir = directory;
  1066. cmSystemTools::ConvertToUnixSlashes(dir);
  1067. std::string prevDir;
  1068. while(dir != prevDir)
  1069. {
  1070. std::string path = dir + "/" + file;
  1071. if ( cmSystemTools::FileExists(path.c_str()) )
  1072. {
  1073. return path;
  1074. }
  1075. if ( dir.size() < strlen(toplevel) )
  1076. {
  1077. break;
  1078. }
  1079. prevDir = dir;
  1080. dir = cmSystemTools::GetParentDirectory(dir.c_str());
  1081. }
  1082. return "";
  1083. }
  1084. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  1085. {
  1086. return Superclass::CopyFileAlways(source, destination);
  1087. }
  1088. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  1089. const char* destination)
  1090. {
  1091. return Superclass::CopyFileIfDifferent(source, destination);
  1092. }
  1093. //----------------------------------------------------------------------------
  1094. bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
  1095. {
  1096. #ifdef _WIN32
  1097. # ifndef INVALID_FILE_ATTRIBUTES
  1098. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  1099. # endif
  1100. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  1101. fails then remove the read-only attribute from any existing destination.
  1102. Try multiple times since we may be racing against another process
  1103. creating/opening the destination file just before our MoveFileEx. */
  1104. int tries = 5;
  1105. while(!MoveFileEx(oldname, newname, MOVEFILE_REPLACE_EXISTING) && --tries)
  1106. {
  1107. // Try again only if failure was due to access permissions.
  1108. if(GetLastError() != ERROR_ACCESS_DENIED)
  1109. {
  1110. return false;
  1111. }
  1112. DWORD attrs = GetFileAttributes(newname);
  1113. if((attrs != INVALID_FILE_ATTRIBUTES) &&
  1114. (attrs & FILE_ATTRIBUTE_READONLY))
  1115. {
  1116. // Remove the read-only attribute from the destination file.
  1117. SetFileAttributes(newname, attrs & ~FILE_ATTRIBUTE_READONLY);
  1118. }
  1119. else
  1120. {
  1121. // The file may be temporarily in use so wait a bit.
  1122. cmSystemTools::Delay(100);
  1123. }
  1124. }
  1125. return tries > 0;
  1126. #else
  1127. /* On UNIX we have an OS-provided call to do this atomically. */
  1128. return rename(oldname, newname) == 0;
  1129. #endif
  1130. }
  1131. bool cmSystemTools::ComputeFileMD5(const char* source, char* md5out)
  1132. {
  1133. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1134. cmCryptoHashMD5 md5;
  1135. std::string str = md5.HashFile(source);
  1136. strncpy(md5out, str.c_str(), 32);
  1137. return !str.empty();
  1138. #else
  1139. (void)source;
  1140. (void)md5out;
  1141. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1142. return false;
  1143. #endif
  1144. }
  1145. std::string cmSystemTools::ComputeStringMD5(const char* input)
  1146. {
  1147. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1148. cmCryptoHashMD5 md5;
  1149. return md5.HashString(input);
  1150. #else
  1151. (void)input;
  1152. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  1153. return "";
  1154. #endif
  1155. }
  1156. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1157. std::vector<std::string>& files)
  1158. {
  1159. cmsys::Directory d;
  1160. cmsys::RegularExpression reg(regexp);
  1161. if (d.Load(directory))
  1162. {
  1163. size_t numf;
  1164. unsigned int i;
  1165. numf = d.GetNumberOfFiles();
  1166. for (i = 0; i < numf; i++)
  1167. {
  1168. std::string fname = d.GetFile(i);
  1169. if (reg.find(fname))
  1170. {
  1171. files.push_back(fname);
  1172. }
  1173. }
  1174. }
  1175. }
  1176. void cmSystemTools::GlobDirs(const char *fullPath,
  1177. std::vector<std::string>& files)
  1178. {
  1179. std::string path = fullPath;
  1180. std::string::size_type pos = path.find("/*");
  1181. if(pos == std::string::npos)
  1182. {
  1183. files.push_back(fullPath);
  1184. return;
  1185. }
  1186. std::string startPath = path.substr(0, pos);
  1187. std::string finishPath = path.substr(pos+2);
  1188. cmsys::Directory d;
  1189. if (d.Load(startPath.c_str()))
  1190. {
  1191. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1192. {
  1193. if((std::string(d.GetFile(i)) != ".")
  1194. && (std::string(d.GetFile(i)) != ".."))
  1195. {
  1196. std::string fname = startPath;
  1197. fname +="/";
  1198. fname += d.GetFile(i);
  1199. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1200. {
  1201. fname += finishPath;
  1202. cmSystemTools::GlobDirs(fname.c_str(), files);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1209. std::vector<std::string>& newargs)
  1210. {
  1211. std::vector<std::string>::const_iterator i;
  1212. for(i = arguments.begin();i != arguments.end(); ++i)
  1213. {
  1214. cmSystemTools::ExpandListArgument(*i, newargs);
  1215. }
  1216. }
  1217. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1218. std::vector<std::string>& newargs,
  1219. bool emptyArgs)
  1220. {
  1221. // If argument is empty, it is an empty list.
  1222. if(arg.length() == 0 && !emptyArgs)
  1223. {
  1224. return;
  1225. }
  1226. // if there are no ; in the name then just copy the current string
  1227. if(arg.find(';') == std::string::npos)
  1228. {
  1229. newargs.push_back(arg);
  1230. return;
  1231. }
  1232. std::vector<char> newArgVec;
  1233. // Break the string at non-escaped semicolons not nested in [].
  1234. int squareNesting = 0;
  1235. for(const char* c = arg.c_str(); *c; ++c)
  1236. {
  1237. switch(*c)
  1238. {
  1239. case '\\':
  1240. {
  1241. // We only want to allow escaping of semicolons. Other
  1242. // escapes should not be processed here.
  1243. ++c;
  1244. if(*c == ';')
  1245. {
  1246. newArgVec.push_back(*c);
  1247. }
  1248. else
  1249. {
  1250. newArgVec.push_back('\\');
  1251. if(*c)
  1252. {
  1253. newArgVec.push_back(*c);
  1254. }
  1255. else
  1256. {
  1257. // Terminate the loop properly.
  1258. --c;
  1259. }
  1260. }
  1261. } break;
  1262. case '[':
  1263. {
  1264. ++squareNesting;
  1265. newArgVec.push_back(*c);
  1266. } break;
  1267. case ']':
  1268. {
  1269. --squareNesting;
  1270. newArgVec.push_back(*c);
  1271. } break;
  1272. case ';':
  1273. {
  1274. // Break the string here if we are not nested inside square
  1275. // brackets.
  1276. if(squareNesting == 0)
  1277. {
  1278. if ( newArgVec.size() || emptyArgs )
  1279. {
  1280. // Add the last argument if the string is not empty.
  1281. newArgVec.push_back(0);
  1282. newargs.push_back(&*newArgVec.begin());
  1283. newArgVec.clear();
  1284. }
  1285. }
  1286. else
  1287. {
  1288. newArgVec.push_back(*c);
  1289. }
  1290. } break;
  1291. default:
  1292. {
  1293. // Just append this character.
  1294. newArgVec.push_back(*c);
  1295. } break;
  1296. }
  1297. }
  1298. if ( newArgVec.size() || emptyArgs )
  1299. {
  1300. // Add the last argument if the string is not empty.
  1301. newArgVec.push_back(0);
  1302. newargs.push_back(&*newArgVec.begin());
  1303. }
  1304. }
  1305. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  1306. std::vector<cmStdString>& files,
  1307. int type /* = 0 */)
  1308. {
  1309. files.clear();
  1310. if ( glob[glob.size()-1] != '*' )
  1311. {
  1312. return false;
  1313. }
  1314. std::string path = cmSystemTools::GetFilenamePath(glob);
  1315. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1316. ppath = ppath.substr(0, ppath.size()-1);
  1317. if ( path.size() == 0 )
  1318. {
  1319. path = "/";
  1320. }
  1321. bool res = false;
  1322. cmsys::Directory d;
  1323. if (d.Load(path.c_str()))
  1324. {
  1325. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1326. {
  1327. if((std::string(d.GetFile(i)) != ".")
  1328. && (std::string(d.GetFile(i)) != ".."))
  1329. {
  1330. std::string fname = path;
  1331. if ( path[path.size()-1] != '/' )
  1332. {
  1333. fname +="/";
  1334. }
  1335. fname += d.GetFile(i);
  1336. std::string sfname = d.GetFile(i);
  1337. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  1338. {
  1339. continue;
  1340. }
  1341. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  1342. {
  1343. continue;
  1344. }
  1345. if ( sfname.size() >= ppath.size() &&
  1346. sfname.substr(0, ppath.size()) ==
  1347. ppath )
  1348. {
  1349. files.push_back(fname);
  1350. res = true;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. return res;
  1356. }
  1357. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1358. {
  1359. if ( ! cext || *cext == 0 )
  1360. {
  1361. return cmSystemTools::NO_FILE_FORMAT;
  1362. }
  1363. //std::string ext = cmSystemTools::LowerCase(cext);
  1364. std::string ext = cext;
  1365. if ( ext == "c" || ext == ".c" ||
  1366. ext == "m" || ext == ".m"
  1367. ) { return cmSystemTools::C_FILE_FORMAT; }
  1368. if (
  1369. ext == "C" || ext == ".C" ||
  1370. ext == "M" || ext == ".M" ||
  1371. ext == "c++" || ext == ".c++" ||
  1372. ext == "cc" || ext == ".cc" ||
  1373. ext == "cpp" || ext == ".cpp" ||
  1374. ext == "cxx" || ext == ".cxx" ||
  1375. ext == "mm" || ext == ".mm"
  1376. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1377. if (
  1378. ext == "f" || ext == ".f" ||
  1379. ext == "F" || ext == ".F" ||
  1380. ext == "f77" || ext == ".f77" ||
  1381. ext == "f90" || ext == ".f90" ||
  1382. ext == "for" || ext == ".for" ||
  1383. ext == "f95" || ext == ".f95"
  1384. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1385. if ( ext == "java" || ext == ".java" )
  1386. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1387. if (
  1388. ext == "H" || ext == ".H" ||
  1389. ext == "h" || ext == ".h" ||
  1390. ext == "h++" || ext == ".h++" ||
  1391. ext == "hm" || ext == ".hm" ||
  1392. ext == "hpp" || ext == ".hpp" ||
  1393. ext == "hxx" || ext == ".hxx" ||
  1394. ext == "in" || ext == ".in" ||
  1395. ext == "txx" || ext == ".txx"
  1396. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1397. if ( ext == "rc" || ext == ".rc" )
  1398. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1399. if ( ext == "def" || ext == ".def" )
  1400. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1401. if ( ext == "lib" || ext == ".lib" ||
  1402. ext == "a" || ext == ".a")
  1403. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1404. if ( ext == "o" || ext == ".o" ||
  1405. ext == "obj" || ext == ".obj")
  1406. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1407. #ifdef __APPLE__
  1408. if ( ext == "dylib" || ext == ".dylib" )
  1409. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1410. if ( ext == "so" || ext == ".so" ||
  1411. ext == "bundle" || ext == ".bundle" )
  1412. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1413. #else // __APPLE__
  1414. if ( ext == "so" || ext == ".so" ||
  1415. ext == "sl" || ext == ".sl" ||
  1416. ext == "dll" || ext == ".dll" )
  1417. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1418. #endif // __APPLE__
  1419. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1420. }
  1421. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1422. {
  1423. std::vector<std::string> temp;
  1424. bool res = Superclass::Split(s, temp);
  1425. for(std::vector<std::string>::const_iterator i = temp.begin();
  1426. i != temp.end(); ++i)
  1427. {
  1428. l.push_back(*i);
  1429. }
  1430. return res;
  1431. }
  1432. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1433. {
  1434. #if defined(_WIN32) && !defined(__CYGWIN__)
  1435. if(s_ForceUnixPaths)
  1436. {
  1437. return cmSystemTools::ConvertToUnixOutputPath(path);
  1438. }
  1439. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1440. #else
  1441. return cmSystemTools::ConvertToUnixOutputPath(path);
  1442. #endif
  1443. }
  1444. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1445. {
  1446. #if defined(_WIN32) && !defined(__CYGWIN__)
  1447. if(!s_ForceUnixPaths)
  1448. {
  1449. // Convert to windows slashes.
  1450. std::string::size_type pos = 0;
  1451. while((pos = path.find('/', pos)) != std::string::npos)
  1452. {
  1453. path[pos++] = '\\';
  1454. }
  1455. }
  1456. #else
  1457. static_cast<void>(path);
  1458. #endif
  1459. }
  1460. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1461. {
  1462. #if defined(_WIN32) && !defined(__CYGWIN__)
  1463. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1464. #else
  1465. return cmSystemTools::ConvertToUnixOutputPath(path);
  1466. #endif
  1467. }
  1468. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1469. {
  1470. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1471. {
  1472. return 0;
  1473. }
  1474. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1475. }
  1476. // compute the relative path from here to there
  1477. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1478. {
  1479. if(!cmSystemTools::FileIsFullPath(local))
  1480. {
  1481. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1482. local);
  1483. }
  1484. if(!cmSystemTools::FileIsFullPath(remote))
  1485. {
  1486. cmSystemTools::Error
  1487. ("RelativePath must be passed a full path to remote: ", remote);
  1488. }
  1489. return cmsys::SystemTools::RelativePath(local, remote);
  1490. }
  1491. std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
  1492. std::string const& file)
  1493. {
  1494. if(dir.empty() || dir == ".")
  1495. {
  1496. return file;
  1497. }
  1498. std::vector<std::string> dirComponents;
  1499. std::vector<std::string> fileComponents;
  1500. cmSystemTools::SplitPath(dir.c_str(), dirComponents);
  1501. cmSystemTools::SplitPath(file.c_str(), fileComponents);
  1502. if(fileComponents.empty())
  1503. {
  1504. return dir;
  1505. }
  1506. if(fileComponents[0] != "")
  1507. {
  1508. // File is not a relative path.
  1509. return file;
  1510. }
  1511. std::vector<std::string>::iterator i = fileComponents.begin()+1;
  1512. while(i != fileComponents.end() && *i == ".." && dirComponents.size() > 1)
  1513. {
  1514. ++i; // Remove ".." file component.
  1515. dirComponents.pop_back(); // Remove last dir component.
  1516. }
  1517. dirComponents.insert(dirComponents.end(), i, fileComponents.end());
  1518. return cmSystemTools::JoinPath(dirComponents);
  1519. }
  1520. #ifdef CMAKE_BUILD_WITH_CMAKE
  1521. //----------------------------------------------------------------------
  1522. bool cmSystemTools::UnsetEnv(const char* value)
  1523. {
  1524. #if !defined(HAVE_UNSETENV)
  1525. std::string var = value;
  1526. var += "=";
  1527. return cmSystemTools::PutEnv(var.c_str());
  1528. #else
  1529. unsetenv(value);
  1530. return true;
  1531. #endif
  1532. }
  1533. //----------------------------------------------------------------------
  1534. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1535. {
  1536. std::vector<std::string> env;
  1537. int cc;
  1538. for ( cc = 0; environ[cc]; ++ cc )
  1539. {
  1540. env.push_back(environ[cc]);
  1541. }
  1542. return env;
  1543. }
  1544. //----------------------------------------------------------------------
  1545. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1546. {
  1547. for(std::vector<std::string>::const_iterator eit = env.begin();
  1548. eit != env.end(); ++eit)
  1549. {
  1550. cmSystemTools::PutEnv(eit->c_str());
  1551. }
  1552. }
  1553. //----------------------------------------------------------------------
  1554. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1555. {
  1556. this->Env = cmSystemTools::GetEnvironmentVariables();
  1557. }
  1558. //----------------------------------------------------------------------
  1559. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1560. {
  1561. // First clear everything in the current environment:
  1562. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1563. for(std::vector<std::string>::const_iterator
  1564. eit = currentEnv.begin(); eit != currentEnv.end(); ++eit)
  1565. {
  1566. std::string var(*eit);
  1567. std::string::size_type pos = var.find("=");
  1568. if (pos != std::string::npos)
  1569. {
  1570. var = var.substr(0, pos);
  1571. }
  1572. cmSystemTools::UnsetEnv(var.c_str());
  1573. }
  1574. // Then put back each entry from the original environment:
  1575. cmSystemTools::AppendEnv(this->Env);
  1576. }
  1577. #endif
  1578. void cmSystemTools::EnableVSConsoleOutput()
  1579. {
  1580. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1581. // display output to the console unless this environment variable is
  1582. // set. We need it to capture the output of these build tools.
  1583. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1584. // either of these executables where NAME is created with
  1585. // CreateNamedPipe. This would bypass the internal buffering of the
  1586. // output and allow it to be captured on the fly.
  1587. #ifdef _WIN32
  1588. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1589. #endif
  1590. }
  1591. bool cmSystemTools::IsPathToFramework(const char* path)
  1592. {
  1593. if(cmSystemTools::FileIsFullPath(path))
  1594. {
  1595. std::string libname = path;
  1596. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1597. {
  1598. return true;
  1599. }
  1600. }
  1601. return false;
  1602. }
  1603. bool cmSystemTools::CreateTar(const char* outFileName,
  1604. const std::vector<cmStdString>& files,
  1605. bool gzip, bool bzip2, bool verbose)
  1606. {
  1607. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1608. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1609. std::ofstream fout(outFileName, std::ios::out | cmsys_ios_binary);
  1610. if(!fout)
  1611. {
  1612. std::string e = "Cannot open output file \"";
  1613. e += outFileName;
  1614. e += "\": ";
  1615. e += cmSystemTools::GetLastSystemError();
  1616. cmSystemTools::Error(e.c_str());
  1617. return false;
  1618. }
  1619. cmArchiveWrite a(fout, (gzip? cmArchiveWrite::CompressGZip :
  1620. (bzip2? cmArchiveWrite::CompressBZip2 :
  1621. cmArchiveWrite::CompressNone)),
  1622. cmArchiveWrite::TypeTAR);
  1623. a.SetVerbose(verbose);
  1624. for(std::vector<cmStdString>::const_iterator i = files.begin();
  1625. i != files.end(); ++i)
  1626. {
  1627. std::string path = *i;
  1628. if(cmSystemTools::FileIsFullPath(path.c_str()))
  1629. {
  1630. // Get the relative path to the file.
  1631. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1632. }
  1633. if(!a.Add(path))
  1634. {
  1635. break;
  1636. }
  1637. }
  1638. if(!a)
  1639. {
  1640. cmSystemTools::Error(a.GetError().c_str());
  1641. return false;
  1642. }
  1643. return true;
  1644. #else
  1645. (void)outFileName;
  1646. (void)files;
  1647. (void)gzip;
  1648. (void)verbose;
  1649. return false;
  1650. #endif
  1651. }
  1652. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1653. namespace{
  1654. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1655. #define BSDTAR_FILESIZE_TYPE unsigned long
  1656. void
  1657. list_item_verbose(FILE *out, struct archive_entry *entry)
  1658. {
  1659. char tmp[100];
  1660. size_t w;
  1661. const char *p;
  1662. const char *fmt;
  1663. time_t tim;
  1664. static time_t now;
  1665. size_t u_width = 6;
  1666. size_t gs_width = 13;
  1667. /*
  1668. * We avoid collecting the entire list in memory at once by
  1669. * listing things as we see them. However, that also means we can't
  1670. * just pre-compute the field widths. Instead, we start with guesses
  1671. * and just widen them as necessary. These numbers are completely
  1672. * arbitrary.
  1673. */
  1674. if (!now)
  1675. {
  1676. time(&now);
  1677. }
  1678. fprintf(out, "%s %d ",
  1679. archive_entry_strmode(entry),
  1680. archive_entry_nlink(entry));
  1681. /* Use uname if it's present, else uid. */
  1682. p = archive_entry_uname(entry);
  1683. if ((p == NULL) || (*p == '\0'))
  1684. {
  1685. sprintf(tmp, "%lu ",
  1686. (unsigned long)archive_entry_uid(entry));
  1687. p = tmp;
  1688. }
  1689. w = strlen(p);
  1690. if (w > u_width)
  1691. {
  1692. u_width = w;
  1693. }
  1694. fprintf(out, "%-*s ", (int)u_width, p);
  1695. /* Use gname if it's present, else gid. */
  1696. p = archive_entry_gname(entry);
  1697. if (p != NULL && p[0] != '\0')
  1698. {
  1699. fprintf(out, "%s", p);
  1700. w = strlen(p);
  1701. }
  1702. else
  1703. {
  1704. sprintf(tmp, "%lu",
  1705. (unsigned long)archive_entry_gid(entry));
  1706. w = strlen(tmp);
  1707. fprintf(out, "%s", tmp);
  1708. }
  1709. /*
  1710. * Print device number or file size, right-aligned so as to make
  1711. * total width of group and devnum/filesize fields be gs_width.
  1712. * If gs_width is too small, grow it.
  1713. */
  1714. if (archive_entry_filetype(entry) == AE_IFCHR
  1715. || archive_entry_filetype(entry) == AE_IFBLK)
  1716. {
  1717. sprintf(tmp, "%lu,%lu",
  1718. (unsigned long)archive_entry_rdevmajor(entry),
  1719. (unsigned long)archive_entry_rdevminor(entry));
  1720. }
  1721. else
  1722. {
  1723. /*
  1724. * Note the use of platform-dependent macros to format
  1725. * the filesize here. We need the format string and the
  1726. * corresponding type for the cast.
  1727. */
  1728. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1729. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1730. }
  1731. if (w + strlen(tmp) >= gs_width)
  1732. {
  1733. gs_width = w+strlen(tmp)+1;
  1734. }
  1735. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1736. /* Format the time using 'ls -l' conventions. */
  1737. tim = archive_entry_mtime(entry);
  1738. #define HALF_YEAR (time_t)365 * 86400 / 2
  1739. #if defined(_WIN32) && !defined(__CYGWIN__)
  1740. /* Windows' strftime function does not support %e format. */
  1741. #define DAY_FMT "%d"
  1742. #else
  1743. #define DAY_FMT "%e" /* Day number without leading zeros */
  1744. #endif
  1745. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1746. {
  1747. fmt = DAY_FMT " %b %Y";
  1748. }
  1749. else
  1750. {
  1751. fmt = DAY_FMT " %b %H:%M";
  1752. }
  1753. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1754. fprintf(out, " %s ", tmp);
  1755. fprintf(out, "%s", archive_entry_pathname(entry));
  1756. /* Extra information for links. */
  1757. if (archive_entry_hardlink(entry)) /* Hard link */
  1758. {
  1759. fprintf(out, " link to %s",
  1760. archive_entry_hardlink(entry));
  1761. }
  1762. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1763. {
  1764. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1765. }
  1766. }
  1767. #ifdef __BORLANDC__
  1768. # pragma warn -8066 /* unreachable code */
  1769. #endif
  1770. long copy_data(struct archive *ar, struct archive *aw)
  1771. {
  1772. long r;
  1773. const void *buff;
  1774. size_t size;
  1775. #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1776. __LA_INT64_T offset;
  1777. #else
  1778. off_t offset;
  1779. #endif
  1780. for (;;)
  1781. {
  1782. r = archive_read_data_block(ar, &buff, &size, &offset);
  1783. if (r == ARCHIVE_EOF)
  1784. {
  1785. return (ARCHIVE_OK);
  1786. }
  1787. if (r != ARCHIVE_OK)
  1788. {
  1789. return (r);
  1790. }
  1791. r = archive_write_data_block(aw, buff, size, offset);
  1792. if (r != ARCHIVE_OK)
  1793. {
  1794. cmSystemTools::Message("archive_write_data_block()",
  1795. archive_error_string(aw));
  1796. return (r);
  1797. }
  1798. }
  1799. return r;
  1800. }
  1801. bool extract_tar(const char* outFileName, bool verbose,
  1802. bool extract)
  1803. {
  1804. struct archive* a = archive_read_new();
  1805. struct archive *ext = archive_write_disk_new();
  1806. archive_read_support_compression_all(a);
  1807. archive_read_support_format_all(a);
  1808. struct archive_entry *entry;
  1809. int r = archive_read_open_file(a, outFileName, 10240);
  1810. if(r)
  1811. {
  1812. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1813. archive_error_string(a));
  1814. return false;
  1815. }
  1816. for (;;)
  1817. {
  1818. r = archive_read_next_header(a, &entry);
  1819. if (r == ARCHIVE_EOF)
  1820. {
  1821. break;
  1822. }
  1823. if (r != ARCHIVE_OK)
  1824. {
  1825. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1826. archive_error_string(a));
  1827. break;
  1828. }
  1829. if (verbose && extract)
  1830. {
  1831. cmSystemTools::Stdout("x ");
  1832. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1833. }
  1834. if(verbose && !extract)
  1835. {
  1836. list_item_verbose(stdout, entry);
  1837. }
  1838. else if(!extract)
  1839. {
  1840. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1841. }
  1842. if(extract)
  1843. {
  1844. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1845. if (r != ARCHIVE_OK)
  1846. {
  1847. cmSystemTools::Error(
  1848. "Problem with archive_write_disk_set_options(): ",
  1849. archive_error_string(ext));
  1850. break;
  1851. }
  1852. r = archive_write_header(ext, entry);
  1853. if (r != ARCHIVE_OK)
  1854. {
  1855. cmSystemTools::Error("Problem with archive_write_header(): ",
  1856. archive_error_string(ext));
  1857. cmSystemTools::Error("Current file: ",
  1858. archive_entry_pathname(entry));
  1859. break;
  1860. }
  1861. else
  1862. {
  1863. copy_data(a, ext);
  1864. r = archive_write_finish_entry(ext);
  1865. if (r != ARCHIVE_OK)
  1866. {
  1867. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1868. archive_error_string(ext));
  1869. break;
  1870. }
  1871. }
  1872. }
  1873. if (verbose || !extract)
  1874. {
  1875. cmSystemTools::Stdout("\n");
  1876. }
  1877. }
  1878. archive_read_close(a);
  1879. archive_read_finish(a);
  1880. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1881. }
  1882. }
  1883. #endif
  1884. bool cmSystemTools::ExtractTar(const char* outFileName,
  1885. bool , bool verbose)
  1886. {
  1887. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1888. return extract_tar(outFileName, verbose, true);
  1889. #else
  1890. (void)outFileName;
  1891. (void)verbose;
  1892. return false;
  1893. #endif
  1894. }
  1895. bool cmSystemTools::ListTar(const char* outFileName,
  1896. bool ,
  1897. bool verbose)
  1898. {
  1899. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1900. return extract_tar(outFileName, verbose, false);
  1901. #else
  1902. (void)outFileName;
  1903. (void)verbose;
  1904. return false;
  1905. #endif
  1906. }
  1907. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1908. double timeout,
  1909. std::vector<char>& out,
  1910. std::vector<char>& err)
  1911. {
  1912. line = "";
  1913. std::vector<char>::iterator outiter = out.begin();
  1914. std::vector<char>::iterator erriter = err.begin();
  1915. while(1)
  1916. {
  1917. // Check for a newline in stdout.
  1918. for(;outiter != out.end(); ++outiter)
  1919. {
  1920. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1921. {
  1922. break;
  1923. }
  1924. else if(*outiter == '\n' || *outiter == '\0')
  1925. {
  1926. std::vector<char>::size_type length = outiter-out.begin();
  1927. if(length > 1 && *(outiter-1) == '\r')
  1928. {
  1929. --length;
  1930. }
  1931. if(length > 0)
  1932. {
  1933. line.append(&out[0], length);
  1934. }
  1935. out.erase(out.begin(), outiter+1);
  1936. return cmsysProcess_Pipe_STDOUT;
  1937. }
  1938. }
  1939. // Check for a newline in stderr.
  1940. for(;erriter != err.end(); ++erriter)
  1941. {
  1942. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1943. {
  1944. break;
  1945. }
  1946. else if(*erriter == '\n' || *erriter == '\0')
  1947. {
  1948. std::vector<char>::size_type length = erriter-err.begin();
  1949. if(length > 1 && *(erriter-1) == '\r')
  1950. {
  1951. --length;
  1952. }
  1953. if(length > 0)
  1954. {
  1955. line.append(&err[0], length);
  1956. }
  1957. err.erase(err.begin(), erriter+1);
  1958. return cmsysProcess_Pipe_STDERR;
  1959. }
  1960. }
  1961. // No newlines found. Wait for more data from the process.
  1962. int length;
  1963. char* data;
  1964. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1965. if(pipe == cmsysProcess_Pipe_Timeout)
  1966. {
  1967. // Timeout has been exceeded.
  1968. return pipe;
  1969. }
  1970. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1971. {
  1972. // Append to the stdout buffer.
  1973. std::vector<char>::size_type size = out.size();
  1974. out.insert(out.end(), data, data+length);
  1975. outiter = out.begin()+size;
  1976. }
  1977. else if(pipe == cmsysProcess_Pipe_STDERR)
  1978. {
  1979. // Append to the stderr buffer.
  1980. std::vector<char>::size_type size = err.size();
  1981. err.insert(err.end(), data, data+length);
  1982. erriter = err.begin()+size;
  1983. }
  1984. else if(pipe == cmsysProcess_Pipe_None)
  1985. {
  1986. // Both stdout and stderr pipes have broken. Return leftover data.
  1987. if(!out.empty())
  1988. {
  1989. line.append(&out[0], outiter-out.begin());
  1990. out.erase(out.begin(), out.end());
  1991. return cmsysProcess_Pipe_STDOUT;
  1992. }
  1993. else if(!err.empty())
  1994. {
  1995. line.append(&err[0], erriter-err.begin());
  1996. err.erase(err.begin(), err.end());
  1997. return cmsysProcess_Pipe_STDERR;
  1998. }
  1999. else
  2000. {
  2001. return cmsysProcess_Pipe_None;
  2002. }
  2003. }
  2004. }
  2005. }
  2006. void cmSystemTools::DoNotInheritStdPipes()
  2007. {
  2008. #ifdef _WIN32
  2009. // Check to see if we are attached to a console
  2010. // if so, then do not stop the inherited pipes
  2011. // or stdout and stderr will not show up in dos
  2012. // shell windows
  2013. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  2014. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2015. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  2016. {
  2017. return;
  2018. }
  2019. {
  2020. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  2021. DuplicateHandle(GetCurrentProcess(), out,
  2022. GetCurrentProcess(), &out, 0, FALSE,
  2023. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2024. SetStdHandle(STD_OUTPUT_HANDLE, out);
  2025. }
  2026. {
  2027. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  2028. DuplicateHandle(GetCurrentProcess(), out,
  2029. GetCurrentProcess(), &out, 0, FALSE,
  2030. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2031. SetStdHandle(STD_ERROR_HANDLE, out);
  2032. }
  2033. #endif
  2034. }
  2035. //----------------------------------------------------------------------------
  2036. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  2037. {
  2038. #if defined(_WIN32) && !defined(__CYGWIN__)
  2039. cmSystemToolsWindowsHandle hFrom =
  2040. CreateFile(fromFile, GENERIC_READ, FILE_SHARE_READ, 0,
  2041. OPEN_EXISTING, 0, 0);
  2042. cmSystemToolsWindowsHandle hTo =
  2043. CreateFile(toFile, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2044. if(!hFrom || !hTo)
  2045. {
  2046. return false;
  2047. }
  2048. FILETIME timeCreation;
  2049. FILETIME timeLastAccess;
  2050. FILETIME timeLastWrite;
  2051. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  2052. {
  2053. return false;
  2054. }
  2055. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  2056. {
  2057. return false;
  2058. }
  2059. #else
  2060. struct stat fromStat;
  2061. if(stat(fromFile, &fromStat) < 0)
  2062. {
  2063. return false;
  2064. }
  2065. struct utimbuf buf;
  2066. buf.actime = fromStat.st_atime;
  2067. buf.modtime = fromStat.st_mtime;
  2068. if(utime(toFile, &buf) < 0)
  2069. {
  2070. return false;
  2071. }
  2072. #endif
  2073. return true;
  2074. }
  2075. //----------------------------------------------------------------------------
  2076. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  2077. {
  2078. return new cmSystemToolsFileTime;
  2079. }
  2080. //----------------------------------------------------------------------------
  2081. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  2082. {
  2083. delete t;
  2084. }
  2085. //----------------------------------------------------------------------------
  2086. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  2087. {
  2088. #if defined(_WIN32) && !defined(__CYGWIN__)
  2089. cmSystemToolsWindowsHandle h =
  2090. CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  2091. if(!h)
  2092. {
  2093. return false;
  2094. }
  2095. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2096. {
  2097. return false;
  2098. }
  2099. #else
  2100. struct stat st;
  2101. if(stat(fname, &st) < 0)
  2102. {
  2103. return false;
  2104. }
  2105. t->timeBuf.actime = st.st_atime;
  2106. t->timeBuf.modtime = st.st_mtime;
  2107. #endif
  2108. return true;
  2109. }
  2110. //----------------------------------------------------------------------------
  2111. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2112. {
  2113. #if defined(_WIN32) && !defined(__CYGWIN__)
  2114. cmSystemToolsWindowsHandle h =
  2115. CreateFile(fname, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2116. if(!h)
  2117. {
  2118. return false;
  2119. }
  2120. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2121. {
  2122. return false;
  2123. }
  2124. #else
  2125. if(utime(fname, &t->timeBuf) < 0)
  2126. {
  2127. return false;
  2128. }
  2129. #endif
  2130. return true;
  2131. }
  2132. //----------------------------------------------------------------------------
  2133. #ifdef _WIN32
  2134. # ifndef CRYPT_SILENT
  2135. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2136. # endif
  2137. static int WinCryptRandom(void* data, size_t size)
  2138. {
  2139. int result = 0;
  2140. HCRYPTPROV hProvider = 0;
  2141. if(CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2142. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2143. {
  2144. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data)? 1:0;
  2145. CryptReleaseContext(hProvider, 0);
  2146. }
  2147. return result;
  2148. }
  2149. #endif
  2150. //----------------------------------------------------------------------------
  2151. unsigned int cmSystemTools::RandomSeed()
  2152. {
  2153. #if defined(_WIN32) && !defined(__CYGWIN__)
  2154. unsigned int seed = 0;
  2155. // Try using a real random source.
  2156. if(WinCryptRandom(&seed, sizeof(seed)))
  2157. {
  2158. return seed;
  2159. }
  2160. // Fall back to the time and pid.
  2161. FILETIME ft;
  2162. GetSystemTimeAsFileTime(&ft);
  2163. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2164. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2165. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2166. return t1 ^ t2 ^ pid;
  2167. #else
  2168. union
  2169. {
  2170. unsigned int integer;
  2171. char bytes[sizeof(unsigned int)];
  2172. } seed;
  2173. // Try using a real random source.
  2174. std::ifstream fin("/dev/urandom");
  2175. if(fin && fin.read(seed.bytes, sizeof(seed)) &&
  2176. fin.gcount() == sizeof(seed))
  2177. {
  2178. return seed.integer;
  2179. }
  2180. // Fall back to the time and pid.
  2181. struct timeval t;
  2182. gettimeofday(&t, 0);
  2183. unsigned int pid = static_cast<unsigned int>(getpid());
  2184. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2185. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2186. // Since tv_usec never fills more than 11 bits we shift it to fill
  2187. // in the slow-changing high-order bits of tv_sec.
  2188. return tv_sec ^ (tv_usec << 21) ^ pid;
  2189. #endif
  2190. }
  2191. //----------------------------------------------------------------------------
  2192. static std::string cmSystemToolsExecutableDirectory;
  2193. void cmSystemTools::FindExecutableDirectory(const char* argv0)
  2194. {
  2195. #if defined(_WIN32) && !defined(__CYGWIN__)
  2196. (void)argv0; // ignore this on windows
  2197. char modulepath[_MAX_PATH];
  2198. ::GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  2199. cmSystemToolsExecutableDirectory =
  2200. cmSystemTools::GetFilenamePath(modulepath);
  2201. return;
  2202. #else
  2203. std::string errorMsg;
  2204. std::string exe;
  2205. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2206. {
  2207. // remove symlinks
  2208. exe = cmSystemTools::GetRealPath(exe.c_str());
  2209. cmSystemToolsExecutableDirectory =
  2210. cmSystemTools::GetFilenamePath(exe.c_str());
  2211. }
  2212. else
  2213. {
  2214. // ???
  2215. }
  2216. #endif
  2217. }
  2218. //----------------------------------------------------------------------------
  2219. const char* cmSystemTools::GetExecutableDirectory()
  2220. {
  2221. return cmSystemToolsExecutableDirectory.c_str();
  2222. }
  2223. //----------------------------------------------------------------------------
  2224. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2225. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2226. bool newline, bool enabled)
  2227. {
  2228. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2229. // to determine whether the stream is displayed on a tty. In this
  2230. // case it assumes no unless we tell it otherwise. Since we want
  2231. // color messages to be displayed for users we will assume yes.
  2232. // However, we can test for some situations when the answer is most
  2233. // likely no.
  2234. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2235. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2236. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2237. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2238. {
  2239. // Avoid printing color escapes during dashboard builds.
  2240. assumeTTY = 0;
  2241. }
  2242. if(enabled)
  2243. {
  2244. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2245. message, newline? "\n" : "");
  2246. }
  2247. else
  2248. {
  2249. // Color is disabled. Print without color.
  2250. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2251. }
  2252. }
  2253. #endif
  2254. //----------------------------------------------------------------------------
  2255. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2256. std::string& soname)
  2257. {
  2258. // For ELF shared libraries use a real parser to get the correct
  2259. // soname.
  2260. #if defined(CMAKE_USE_ELF_PARSER)
  2261. cmELF elf(fullPath.c_str());
  2262. if(elf)
  2263. {
  2264. return elf.GetSOName(soname);
  2265. }
  2266. #endif
  2267. // If the file is not a symlink we have no guess for its soname.
  2268. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2269. {
  2270. return false;
  2271. }
  2272. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2273. {
  2274. return false;
  2275. }
  2276. // If the symlink has a path component we have no guess for the soname.
  2277. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2278. {
  2279. return false;
  2280. }
  2281. // If the symlink points at an extended version of the same name
  2282. // assume it is the soname.
  2283. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2284. if(soname.length() > name.length() &&
  2285. soname.substr(0, name.length()) == name)
  2286. {
  2287. return true;
  2288. }
  2289. return false;
  2290. }
  2291. //----------------------------------------------------------------------------
  2292. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2293. std::string& soname)
  2294. {
  2295. std::vector<cmStdString> cmds;
  2296. cmds.push_back("otool");
  2297. cmds.push_back("-D");
  2298. cmds.push_back(fullPath.c_str());
  2299. std::string output;
  2300. RunSingleCommand(cmds, &output, 0, 0, OUTPUT_NONE);
  2301. std::vector<std::string> strs = cmSystemTools::tokenize(output, "\n");
  2302. // otool returns extra lines reporting multiple install names
  2303. // in case the binary is multi-arch and none of the architectures
  2304. // is native (e.g. i386;ppc on x86_64)
  2305. if(strs.size() >= 2)
  2306. {
  2307. soname = strs[1];
  2308. return true;
  2309. }
  2310. return false;
  2311. }
  2312. //----------------------------------------------------------------------------
  2313. #if defined(CMAKE_USE_ELF_PARSER)
  2314. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2315. std::string const& want)
  2316. {
  2317. // Search for the desired rpath.
  2318. std::string::size_type pos = have.find(want);
  2319. // If the path is not present we are done.
  2320. if(pos == std::string::npos)
  2321. {
  2322. return pos;
  2323. }
  2324. // Build a regex to match a properly separated path instance.
  2325. std::string regex_str = "(^|:)(";
  2326. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2327. {
  2328. int ch = *i;
  2329. if(!(('a' <= ch && ch <= 'z') ||
  2330. ('A' <= ch && ch <= 'Z') ||
  2331. ('0' <= ch && ch <= '9')))
  2332. {
  2333. // Escape the non-alphanumeric character.
  2334. regex_str += "\\";
  2335. }
  2336. // Store the character.
  2337. regex_str.append(1, static_cast<char>(ch));
  2338. }
  2339. regex_str += ")(:|$)";
  2340. // Look for the separated path.
  2341. cmsys::RegularExpression regex(regex_str.c_str());
  2342. if(regex.find(have))
  2343. {
  2344. // Return the position of the path portion.
  2345. return regex.start(2);
  2346. }
  2347. else
  2348. {
  2349. // The desired rpath was not found.
  2350. return std::string::npos;
  2351. }
  2352. }
  2353. #endif
  2354. #if defined(CMAKE_USE_ELF_PARSER)
  2355. struct cmSystemToolsRPathInfo
  2356. {
  2357. unsigned long Position;
  2358. unsigned long Size;
  2359. std::string Name;
  2360. std::string Value;
  2361. };
  2362. #endif
  2363. //----------------------------------------------------------------------------
  2364. bool cmSystemTools::ChangeRPath(std::string const& file,
  2365. std::string const& oldRPath,
  2366. std::string const& newRPath,
  2367. std::string* emsg,
  2368. bool* changed)
  2369. {
  2370. #if defined(CMAKE_USE_ELF_PARSER)
  2371. if(changed)
  2372. {
  2373. *changed = false;
  2374. }
  2375. int rp_count = 0;
  2376. cmSystemToolsRPathInfo rp[2];
  2377. {
  2378. // Parse the ELF binary.
  2379. cmELF elf(file.c_str());
  2380. // Get the RPATH and RUNPATH entries from it.
  2381. int se_count = 0;
  2382. cmELF::StringEntry const* se[2] = {0, 0};
  2383. const char* se_name[2] = {0, 0};
  2384. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2385. {
  2386. se[se_count] = se_rpath;
  2387. se_name[se_count] = "RPATH";
  2388. ++se_count;
  2389. }
  2390. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2391. {
  2392. se[se_count] = se_runpath;
  2393. se_name[se_count] = "RUNPATH";
  2394. ++se_count;
  2395. }
  2396. if(se_count == 0)
  2397. {
  2398. if(newRPath.empty())
  2399. {
  2400. // The new rpath is empty and there is no rpath anyway so it is
  2401. // okay.
  2402. return true;
  2403. }
  2404. else
  2405. {
  2406. if(emsg)
  2407. {
  2408. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2409. *emsg += elf.GetErrorMessage();
  2410. }
  2411. return false;
  2412. }
  2413. }
  2414. for(int i=0; i < se_count; ++i)
  2415. {
  2416. // If both RPATH and RUNPATH refer to the same string literal it
  2417. // needs to be changed only once.
  2418. if(rp_count && rp[0].Position == se[i]->Position)
  2419. {
  2420. continue;
  2421. }
  2422. // Make sure the current rpath contains the old rpath.
  2423. std::string::size_type pos =
  2424. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2425. if(pos == std::string::npos)
  2426. {
  2427. // If it contains the new rpath instead then it is okay.
  2428. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2429. {
  2430. continue;
  2431. }
  2432. if(emsg)
  2433. {
  2434. cmOStringStream e;
  2435. e << "The current " << se_name[i] << " is:\n"
  2436. << " " << se[i]->Value << "\n"
  2437. << "which does not contain:\n"
  2438. << " " << oldRPath << "\n"
  2439. << "as was expected.";
  2440. *emsg = e.str();
  2441. }
  2442. return false;
  2443. }
  2444. // Store information about the entry in the file.
  2445. rp[rp_count].Position = se[i]->Position;
  2446. rp[rp_count].Size = se[i]->Size;
  2447. rp[rp_count].Name = se_name[i];
  2448. // Construct the new value which preserves the part of the path
  2449. // not being changed.
  2450. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2451. rp[rp_count].Value += newRPath;
  2452. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2453. oldRPath.npos);
  2454. // Make sure there is enough room to store the new rpath and at
  2455. // least one null terminator.
  2456. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2457. {
  2458. if(emsg)
  2459. {
  2460. *emsg = "The replacement path is too long for the ";
  2461. *emsg += se_name[i];
  2462. *emsg += " entry.";
  2463. }
  2464. return false;
  2465. }
  2466. // This entry is ready for update.
  2467. ++rp_count;
  2468. }
  2469. }
  2470. // If no runtime path needs to be changed, we are done.
  2471. if(rp_count == 0)
  2472. {
  2473. return true;
  2474. }
  2475. {
  2476. // Open the file for update.
  2477. std::ofstream f(file.c_str(),
  2478. std::ios::in | std::ios::out | std::ios::binary);
  2479. if(!f)
  2480. {
  2481. if(emsg)
  2482. {
  2483. *emsg = "Error opening file for update.";
  2484. }
  2485. return false;
  2486. }
  2487. // Store the new RPATH and RUNPATH strings.
  2488. for(int i=0; i < rp_count; ++i)
  2489. {
  2490. // Seek to the RPATH position.
  2491. if(!f.seekp(rp[i].Position))
  2492. {
  2493. if(emsg)
  2494. {
  2495. *emsg = "Error seeking to ";
  2496. *emsg += rp[i].Name;
  2497. *emsg += " position.";
  2498. }
  2499. return false;
  2500. }
  2501. // Write the new rpath. Follow it with enough null terminators to
  2502. // fill the string table entry.
  2503. f << rp[i].Value;
  2504. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2505. {
  2506. f << '\0';
  2507. }
  2508. // Make sure it wrote correctly.
  2509. if(!f)
  2510. {
  2511. if(emsg)
  2512. {
  2513. *emsg = "Error writing the new ";
  2514. *emsg += rp[i].Name;
  2515. *emsg += " string to the file.";
  2516. }
  2517. return false;
  2518. }
  2519. }
  2520. }
  2521. // Everything was updated successfully.
  2522. if(changed)
  2523. {
  2524. *changed = true;
  2525. }
  2526. return true;
  2527. #else
  2528. (void)file;
  2529. (void)oldRPath;
  2530. (void)newRPath;
  2531. (void)emsg;
  2532. (void)changed;
  2533. return false;
  2534. #endif
  2535. }
  2536. //----------------------------------------------------------------------------
  2537. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2538. const char* lhss, const char* rhss)
  2539. {
  2540. // Parse out up to 8 components.
  2541. unsigned int lhs[8] = {0,0,0,0,0,0,0,0};
  2542. unsigned int rhs[8] = {0,0,0,0,0,0,0,0};
  2543. sscanf(lhss, "%u.%u.%u.%u.%u.%u.%u.%u",
  2544. &lhs[0], &lhs[1], &lhs[2], &lhs[3],
  2545. &lhs[4], &lhs[5], &lhs[6], &lhs[7]);
  2546. sscanf(rhss, "%u.%u.%u.%u.%u.%u.%u.%u",
  2547. &rhs[0], &rhs[1], &rhs[2], &rhs[3],
  2548. &rhs[4], &rhs[5], &rhs[6], &rhs[7]);
  2549. // Do component-wise comparison.
  2550. for(unsigned int i=0; i < 8; ++i)
  2551. {
  2552. if(lhs[i] < rhs[i])
  2553. {
  2554. // lhs < rhs, so true if operation is LESS
  2555. return op == cmSystemTools::OP_LESS;
  2556. }
  2557. else if(lhs[i] > rhs[i])
  2558. {
  2559. // lhs > rhs, so true if operation is GREATER
  2560. return op == cmSystemTools::OP_GREATER;
  2561. }
  2562. }
  2563. // lhs == rhs, so true if operation is EQUAL
  2564. return op == cmSystemTools::OP_EQUAL;
  2565. }
  2566. //----------------------------------------------------------------------------
  2567. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2568. bool* removed)
  2569. {
  2570. #if defined(CMAKE_USE_ELF_PARSER)
  2571. if(removed)
  2572. {
  2573. *removed = false;
  2574. }
  2575. int zeroCount = 0;
  2576. unsigned long zeroPosition[2] = {0,0};
  2577. unsigned long zeroSize[2] = {0,0};
  2578. unsigned long bytesBegin = 0;
  2579. std::vector<char> bytes;
  2580. {
  2581. // Parse the ELF binary.
  2582. cmELF elf(file.c_str());
  2583. // Get the RPATH and RUNPATH entries from it and sort them by index
  2584. // in the dynamic section header.
  2585. int se_count = 0;
  2586. cmELF::StringEntry const* se[2] = {0, 0};
  2587. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2588. {
  2589. se[se_count++] = se_rpath;
  2590. }
  2591. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2592. {
  2593. se[se_count++] = se_runpath;
  2594. }
  2595. if(se_count == 0)
  2596. {
  2597. // There is no RPATH or RUNPATH anyway.
  2598. return true;
  2599. }
  2600. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2601. {
  2602. cmsys_stl::swap(se[0], se[1]);
  2603. }
  2604. // Get the size of the dynamic section header.
  2605. unsigned int count = elf.GetDynamicEntryCount();
  2606. if(count == 0)
  2607. {
  2608. // This should happen only for invalid ELF files where a DT_NULL
  2609. // appears before the end of the table.
  2610. if(emsg)
  2611. {
  2612. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2613. }
  2614. return false;
  2615. }
  2616. // Save information about the string entries to be zeroed.
  2617. zeroCount = se_count;
  2618. for(int i=0; i < se_count; ++i)
  2619. {
  2620. zeroPosition[i] = se[i]->Position;
  2621. zeroSize[i] = se[i]->Size;
  2622. }
  2623. // Get the range of file positions corresponding to each entry and
  2624. // the rest of the table after them.
  2625. unsigned long entryBegin[3] = {0,0,0};
  2626. unsigned long entryEnd[2] = {0,0};
  2627. for(int i=0; i < se_count; ++i)
  2628. {
  2629. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2630. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2631. }
  2632. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2633. // The data are to be written over the old table entries starting at
  2634. // the first one being removed.
  2635. bytesBegin = entryBegin[0];
  2636. unsigned long bytesEnd = entryBegin[se_count];
  2637. // Allocate a buffer to hold the part of the file to be written.
  2638. // Initialize it with zeros.
  2639. bytes.resize(bytesEnd - bytesBegin, 0);
  2640. // Read the part of the DYNAMIC section header that will move.
  2641. // The remainder of the buffer will be left with zeros which
  2642. // represent a DT_NULL entry.
  2643. char* data = &bytes[0];
  2644. for(int i=0; i < se_count; ++i)
  2645. {
  2646. // Read data between the entries being removed.
  2647. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2648. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2649. {
  2650. if(emsg)
  2651. {
  2652. *emsg = "Failed to read DYNAMIC section header.";
  2653. }
  2654. return false;
  2655. }
  2656. data += sz;
  2657. }
  2658. }
  2659. // Open the file for update.
  2660. std::ofstream f(file.c_str(),
  2661. std::ios::in | std::ios::out | std::ios::binary);
  2662. if(!f)
  2663. {
  2664. if(emsg)
  2665. {
  2666. *emsg = "Error opening file for update.";
  2667. }
  2668. return false;
  2669. }
  2670. // Write the new DYNAMIC table header.
  2671. if(!f.seekp(bytesBegin))
  2672. {
  2673. if(emsg)
  2674. {
  2675. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2676. }
  2677. return false;
  2678. }
  2679. if(!f.write(&bytes[0], bytes.size()))
  2680. {
  2681. if(emsg)
  2682. {
  2683. *emsg = "Error replacing DYNAMIC table header.";
  2684. }
  2685. return false;
  2686. }
  2687. // Fill the RPATH and RUNPATH strings with zero bytes.
  2688. for(int i=0; i < zeroCount; ++i)
  2689. {
  2690. if(!f.seekp(zeroPosition[i]))
  2691. {
  2692. if(emsg)
  2693. {
  2694. *emsg = "Error seeking to RPATH position.";
  2695. }
  2696. return false;
  2697. }
  2698. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2699. {
  2700. f << '\0';
  2701. }
  2702. if(!f)
  2703. {
  2704. if(emsg)
  2705. {
  2706. *emsg = "Error writing the empty rpath string to the file.";
  2707. }
  2708. return false;
  2709. }
  2710. }
  2711. // Everything was updated successfully.
  2712. if(removed)
  2713. {
  2714. *removed = true;
  2715. }
  2716. return true;
  2717. #else
  2718. (void)file;
  2719. (void)emsg;
  2720. (void)removed;
  2721. return false;
  2722. #endif
  2723. }
  2724. //----------------------------------------------------------------------------
  2725. bool cmSystemTools::CheckRPath(std::string const& file,
  2726. std::string const& newRPath)
  2727. {
  2728. #if defined(CMAKE_USE_ELF_PARSER)
  2729. // Parse the ELF binary.
  2730. cmELF elf(file.c_str());
  2731. // Get the RPATH or RUNPATH entry from it.
  2732. cmELF::StringEntry const* se = elf.GetRPath();
  2733. if(!se)
  2734. {
  2735. se = elf.GetRunPath();
  2736. }
  2737. // Make sure the current rpath contains the new rpath.
  2738. if(newRPath.empty())
  2739. {
  2740. if(!se)
  2741. {
  2742. return true;
  2743. }
  2744. }
  2745. else
  2746. {
  2747. if(se &&
  2748. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2749. {
  2750. return true;
  2751. }
  2752. }
  2753. return false;
  2754. #else
  2755. (void)file;
  2756. (void)newRPath;
  2757. return false;
  2758. #endif
  2759. }
  2760. //----------------------------------------------------------------------------
  2761. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2762. {
  2763. // Windows sometimes locks files temporarily so try a few times.
  2764. for(int i = 0; i < 10; ++i)
  2765. {
  2766. if(cmSystemTools::RemoveADirectory(dir))
  2767. {
  2768. return true;
  2769. }
  2770. cmSystemTools::Delay(100);
  2771. }
  2772. return false;
  2773. }
  2774. //----------------------------------------------------------------------------
  2775. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2776. const std::string& sep)
  2777. {
  2778. std::vector<std::string> tokens;
  2779. std::string::size_type tokend = 0;
  2780. do
  2781. {
  2782. std::string::size_type tokstart=str.find_first_not_of(sep, tokend);
  2783. if (tokstart==std::string::npos)
  2784. {
  2785. break; // no more tokens
  2786. }
  2787. tokend=str.find_first_of(sep,tokstart);
  2788. if (tokend==std::string::npos)
  2789. {
  2790. tokens.push_back(str.substr(tokstart));
  2791. }
  2792. else
  2793. {
  2794. tokens.push_back(str.substr(tokstart,tokend-tokstart));
  2795. }
  2796. } while (tokend!=std::string::npos);
  2797. if (tokens.empty())
  2798. {
  2799. tokens.push_back("");
  2800. }
  2801. return tokens;
  2802. }