cmSystemTools.cxx 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960
  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. #ifdef CMAKE_BUILD_WITH_CMAKE
  1492. //----------------------------------------------------------------------
  1493. bool cmSystemTools::UnsetEnv(const char* value)
  1494. {
  1495. #if !defined(HAVE_UNSETENV)
  1496. std::string var = value;
  1497. var += "=";
  1498. return cmSystemTools::PutEnv(var.c_str());
  1499. #else
  1500. unsetenv(value);
  1501. return true;
  1502. #endif
  1503. }
  1504. //----------------------------------------------------------------------
  1505. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1506. {
  1507. std::vector<std::string> env;
  1508. int cc;
  1509. for ( cc = 0; environ[cc]; ++ cc )
  1510. {
  1511. env.push_back(environ[cc]);
  1512. }
  1513. return env;
  1514. }
  1515. //----------------------------------------------------------------------
  1516. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1517. {
  1518. for(std::vector<std::string>::const_iterator eit = env.begin();
  1519. eit != env.end(); ++eit)
  1520. {
  1521. cmSystemTools::PutEnv(eit->c_str());
  1522. }
  1523. }
  1524. //----------------------------------------------------------------------
  1525. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1526. {
  1527. this->Env = cmSystemTools::GetEnvironmentVariables();
  1528. }
  1529. //----------------------------------------------------------------------
  1530. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1531. {
  1532. // First clear everything in the current environment:
  1533. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1534. for(std::vector<std::string>::const_iterator
  1535. eit = currentEnv.begin(); eit != currentEnv.end(); ++eit)
  1536. {
  1537. std::string var(*eit);
  1538. std::string::size_type pos = var.find("=");
  1539. if (pos != std::string::npos)
  1540. {
  1541. var = var.substr(0, pos);
  1542. }
  1543. cmSystemTools::UnsetEnv(var.c_str());
  1544. }
  1545. // Then put back each entry from the original environment:
  1546. cmSystemTools::AppendEnv(this->Env);
  1547. }
  1548. #endif
  1549. void cmSystemTools::EnableVSConsoleOutput()
  1550. {
  1551. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1552. // display output to the console unless this environment variable is
  1553. // set. We need it to capture the output of these build tools.
  1554. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1555. // either of these executables where NAME is created with
  1556. // CreateNamedPipe. This would bypass the internal buffering of the
  1557. // output and allow it to be captured on the fly.
  1558. #ifdef _WIN32
  1559. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1560. #endif
  1561. }
  1562. bool cmSystemTools::IsPathToFramework(const char* path)
  1563. {
  1564. if(cmSystemTools::FileIsFullPath(path))
  1565. {
  1566. std::string libname = path;
  1567. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1568. {
  1569. return true;
  1570. }
  1571. }
  1572. return false;
  1573. }
  1574. bool cmSystemTools::CreateTar(const char* outFileName,
  1575. const std::vector<cmStdString>& files,
  1576. bool gzip, bool bzip2, bool verbose)
  1577. {
  1578. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1579. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1580. std::ofstream fout(outFileName, std::ios::out | cmsys_ios_binary);
  1581. if(!fout)
  1582. {
  1583. std::string e = "Cannot open output file \"";
  1584. e += outFileName;
  1585. e += "\": ";
  1586. e += cmSystemTools::GetLastSystemError();
  1587. cmSystemTools::Error(e.c_str());
  1588. return false;
  1589. }
  1590. cmArchiveWrite a(fout, (gzip? cmArchiveWrite::CompressGZip :
  1591. (bzip2? cmArchiveWrite::CompressBZip2 :
  1592. cmArchiveWrite::CompressNone)),
  1593. cmArchiveWrite::TypeTAR);
  1594. a.SetVerbose(verbose);
  1595. for(std::vector<cmStdString>::const_iterator i = files.begin();
  1596. i != files.end(); ++i)
  1597. {
  1598. std::string path = *i;
  1599. if(cmSystemTools::FileIsFullPath(path.c_str()))
  1600. {
  1601. // Get the relative path to the file.
  1602. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1603. }
  1604. if(!a.Add(path))
  1605. {
  1606. break;
  1607. }
  1608. }
  1609. if(!a)
  1610. {
  1611. cmSystemTools::Error(a.GetError().c_str());
  1612. return false;
  1613. }
  1614. return true;
  1615. #else
  1616. (void)outFileName;
  1617. (void)files;
  1618. (void)gzip;
  1619. (void)verbose;
  1620. return false;
  1621. #endif
  1622. }
  1623. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1624. namespace{
  1625. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1626. #define BSDTAR_FILESIZE_TYPE unsigned long
  1627. void
  1628. list_item_verbose(FILE *out, struct archive_entry *entry)
  1629. {
  1630. char tmp[100];
  1631. size_t w;
  1632. const char *p;
  1633. const char *fmt;
  1634. time_t tim;
  1635. static time_t now;
  1636. size_t u_width = 6;
  1637. size_t gs_width = 13;
  1638. /*
  1639. * We avoid collecting the entire list in memory at once by
  1640. * listing things as we see them. However, that also means we can't
  1641. * just pre-compute the field widths. Instead, we start with guesses
  1642. * and just widen them as necessary. These numbers are completely
  1643. * arbitrary.
  1644. */
  1645. if (!now)
  1646. {
  1647. time(&now);
  1648. }
  1649. fprintf(out, "%s %d ",
  1650. archive_entry_strmode(entry),
  1651. archive_entry_nlink(entry));
  1652. /* Use uname if it's present, else uid. */
  1653. p = archive_entry_uname(entry);
  1654. if ((p == NULL) || (*p == '\0'))
  1655. {
  1656. sprintf(tmp, "%lu ",
  1657. (unsigned long)archive_entry_uid(entry));
  1658. p = tmp;
  1659. }
  1660. w = strlen(p);
  1661. if (w > u_width)
  1662. {
  1663. u_width = w;
  1664. }
  1665. fprintf(out, "%-*s ", (int)u_width, p);
  1666. /* Use gname if it's present, else gid. */
  1667. p = archive_entry_gname(entry);
  1668. if (p != NULL && p[0] != '\0')
  1669. {
  1670. fprintf(out, "%s", p);
  1671. w = strlen(p);
  1672. }
  1673. else
  1674. {
  1675. sprintf(tmp, "%lu",
  1676. (unsigned long)archive_entry_gid(entry));
  1677. w = strlen(tmp);
  1678. fprintf(out, "%s", tmp);
  1679. }
  1680. /*
  1681. * Print device number or file size, right-aligned so as to make
  1682. * total width of group and devnum/filesize fields be gs_width.
  1683. * If gs_width is too small, grow it.
  1684. */
  1685. if (archive_entry_filetype(entry) == AE_IFCHR
  1686. || archive_entry_filetype(entry) == AE_IFBLK)
  1687. {
  1688. sprintf(tmp, "%lu,%lu",
  1689. (unsigned long)archive_entry_rdevmajor(entry),
  1690. (unsigned long)archive_entry_rdevminor(entry));
  1691. }
  1692. else
  1693. {
  1694. /*
  1695. * Note the use of platform-dependent macros to format
  1696. * the filesize here. We need the format string and the
  1697. * corresponding type for the cast.
  1698. */
  1699. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1700. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1701. }
  1702. if (w + strlen(tmp) >= gs_width)
  1703. {
  1704. gs_width = w+strlen(tmp)+1;
  1705. }
  1706. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1707. /* Format the time using 'ls -l' conventions. */
  1708. tim = archive_entry_mtime(entry);
  1709. #define HALF_YEAR (time_t)365 * 86400 / 2
  1710. #if defined(_WIN32) && !defined(__CYGWIN__)
  1711. /* Windows' strftime function does not support %e format. */
  1712. #define DAY_FMT "%d"
  1713. #else
  1714. #define DAY_FMT "%e" /* Day number without leading zeros */
  1715. #endif
  1716. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1717. {
  1718. fmt = DAY_FMT " %b %Y";
  1719. }
  1720. else
  1721. {
  1722. fmt = DAY_FMT " %b %H:%M";
  1723. }
  1724. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1725. fprintf(out, " %s ", tmp);
  1726. fprintf(out, "%s", archive_entry_pathname(entry));
  1727. /* Extra information for links. */
  1728. if (archive_entry_hardlink(entry)) /* Hard link */
  1729. {
  1730. fprintf(out, " link to %s",
  1731. archive_entry_hardlink(entry));
  1732. }
  1733. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1734. {
  1735. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1736. }
  1737. }
  1738. #ifdef __BORLANDC__
  1739. # pragma warn -8066 /* unreachable code */
  1740. #endif
  1741. long copy_data(struct archive *ar, struct archive *aw)
  1742. {
  1743. long r;
  1744. const void *buff;
  1745. size_t size;
  1746. #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1747. __LA_INT64_T offset;
  1748. #else
  1749. off_t offset;
  1750. #endif
  1751. for (;;)
  1752. {
  1753. r = archive_read_data_block(ar, &buff, &size, &offset);
  1754. if (r == ARCHIVE_EOF)
  1755. {
  1756. return (ARCHIVE_OK);
  1757. }
  1758. if (r != ARCHIVE_OK)
  1759. {
  1760. return (r);
  1761. }
  1762. r = archive_write_data_block(aw, buff, size, offset);
  1763. if (r != ARCHIVE_OK)
  1764. {
  1765. cmSystemTools::Message("archive_write_data_block()",
  1766. archive_error_string(aw));
  1767. return (r);
  1768. }
  1769. }
  1770. return r;
  1771. }
  1772. bool extract_tar(const char* outFileName, bool verbose,
  1773. bool extract)
  1774. {
  1775. struct archive* a = archive_read_new();
  1776. struct archive *ext = archive_write_disk_new();
  1777. archive_read_support_compression_all(a);
  1778. archive_read_support_format_all(a);
  1779. struct archive_entry *entry;
  1780. int r = archive_read_open_file(a, outFileName, 10240);
  1781. if(r)
  1782. {
  1783. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1784. archive_error_string(a));
  1785. return false;
  1786. }
  1787. for (;;)
  1788. {
  1789. r = archive_read_next_header(a, &entry);
  1790. if (r == ARCHIVE_EOF)
  1791. {
  1792. break;
  1793. }
  1794. if (r != ARCHIVE_OK)
  1795. {
  1796. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1797. archive_error_string(a));
  1798. break;
  1799. }
  1800. if (verbose && extract)
  1801. {
  1802. cmSystemTools::Stdout("x ");
  1803. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1804. }
  1805. if(verbose && !extract)
  1806. {
  1807. list_item_verbose(stdout, entry);
  1808. }
  1809. else if(!extract)
  1810. {
  1811. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1812. }
  1813. if(extract)
  1814. {
  1815. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1816. if (r != ARCHIVE_OK)
  1817. {
  1818. cmSystemTools::Error(
  1819. "Problem with archive_write_disk_set_options(): ",
  1820. archive_error_string(ext));
  1821. break;
  1822. }
  1823. r = archive_write_header(ext, entry);
  1824. if (r != ARCHIVE_OK)
  1825. {
  1826. cmSystemTools::Error("Problem with archive_write_header(): ",
  1827. archive_error_string(ext));
  1828. cmSystemTools::Error("Current file:",
  1829. archive_entry_pathname(entry));
  1830. break;
  1831. }
  1832. else
  1833. {
  1834. copy_data(a, ext);
  1835. r = archive_write_finish_entry(ext);
  1836. if (r != ARCHIVE_OK)
  1837. {
  1838. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1839. archive_error_string(ext));
  1840. break;
  1841. }
  1842. }
  1843. }
  1844. if (verbose || !extract)
  1845. {
  1846. cmSystemTools::Stdout("\n");
  1847. }
  1848. }
  1849. archive_read_close(a);
  1850. archive_read_finish(a);
  1851. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1852. }
  1853. }
  1854. #endif
  1855. bool cmSystemTools::ExtractTar(const char* outFileName,
  1856. bool , bool verbose)
  1857. {
  1858. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1859. return extract_tar(outFileName, verbose, true);
  1860. #else
  1861. (void)outFileName;
  1862. (void)verbose;
  1863. return false;
  1864. #endif
  1865. }
  1866. bool cmSystemTools::ListTar(const char* outFileName,
  1867. bool ,
  1868. bool verbose)
  1869. {
  1870. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1871. return extract_tar(outFileName, verbose, false);
  1872. #else
  1873. (void)outFileName;
  1874. (void)verbose;
  1875. return false;
  1876. #endif
  1877. }
  1878. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1879. double timeout,
  1880. std::vector<char>& out,
  1881. std::vector<char>& err)
  1882. {
  1883. line = "";
  1884. std::vector<char>::iterator outiter = out.begin();
  1885. std::vector<char>::iterator erriter = err.begin();
  1886. while(1)
  1887. {
  1888. // Check for a newline in stdout.
  1889. for(;outiter != out.end(); ++outiter)
  1890. {
  1891. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1892. {
  1893. break;
  1894. }
  1895. else if(*outiter == '\n' || *outiter == '\0')
  1896. {
  1897. std::vector<char>::size_type length = outiter-out.begin();
  1898. if(length > 1 && *(outiter-1) == '\r')
  1899. {
  1900. --length;
  1901. }
  1902. if(length > 0)
  1903. {
  1904. line.append(&out[0], length);
  1905. }
  1906. out.erase(out.begin(), outiter+1);
  1907. return cmsysProcess_Pipe_STDOUT;
  1908. }
  1909. }
  1910. // Check for a newline in stderr.
  1911. for(;erriter != err.end(); ++erriter)
  1912. {
  1913. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1914. {
  1915. break;
  1916. }
  1917. else if(*erriter == '\n' || *erriter == '\0')
  1918. {
  1919. std::vector<char>::size_type length = erriter-err.begin();
  1920. if(length > 1 && *(erriter-1) == '\r')
  1921. {
  1922. --length;
  1923. }
  1924. if(length > 0)
  1925. {
  1926. line.append(&err[0], length);
  1927. }
  1928. err.erase(err.begin(), erriter+1);
  1929. return cmsysProcess_Pipe_STDERR;
  1930. }
  1931. }
  1932. // No newlines found. Wait for more data from the process.
  1933. int length;
  1934. char* data;
  1935. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1936. if(pipe == cmsysProcess_Pipe_Timeout)
  1937. {
  1938. // Timeout has been exceeded.
  1939. return pipe;
  1940. }
  1941. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1942. {
  1943. // Append to the stdout buffer.
  1944. std::vector<char>::size_type size = out.size();
  1945. out.insert(out.end(), data, data+length);
  1946. outiter = out.begin()+size;
  1947. }
  1948. else if(pipe == cmsysProcess_Pipe_STDERR)
  1949. {
  1950. // Append to the stderr buffer.
  1951. std::vector<char>::size_type size = err.size();
  1952. err.insert(err.end(), data, data+length);
  1953. erriter = err.begin()+size;
  1954. }
  1955. else if(pipe == cmsysProcess_Pipe_None)
  1956. {
  1957. // Both stdout and stderr pipes have broken. Return leftover data.
  1958. if(!out.empty())
  1959. {
  1960. line.append(&out[0], outiter-out.begin());
  1961. out.erase(out.begin(), out.end());
  1962. return cmsysProcess_Pipe_STDOUT;
  1963. }
  1964. else if(!err.empty())
  1965. {
  1966. line.append(&err[0], erriter-err.begin());
  1967. err.erase(err.begin(), err.end());
  1968. return cmsysProcess_Pipe_STDERR;
  1969. }
  1970. else
  1971. {
  1972. return cmsysProcess_Pipe_None;
  1973. }
  1974. }
  1975. }
  1976. }
  1977. void cmSystemTools::DoNotInheritStdPipes()
  1978. {
  1979. #ifdef _WIN32
  1980. // Check to see if we are attached to a console
  1981. // if so, then do not stop the inherited pipes
  1982. // or stdout and stderr will not show up in dos
  1983. // shell windows
  1984. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1985. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1986. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  1987. {
  1988. return;
  1989. }
  1990. {
  1991. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1992. DuplicateHandle(GetCurrentProcess(), out,
  1993. GetCurrentProcess(), &out, 0, FALSE,
  1994. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1995. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1996. }
  1997. {
  1998. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1999. DuplicateHandle(GetCurrentProcess(), out,
  2000. GetCurrentProcess(), &out, 0, FALSE,
  2001. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2002. SetStdHandle(STD_ERROR_HANDLE, out);
  2003. }
  2004. #endif
  2005. }
  2006. //----------------------------------------------------------------------------
  2007. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  2008. {
  2009. #if defined(_WIN32) && !defined(__CYGWIN__)
  2010. cmSystemToolsWindowsHandle hFrom =
  2011. CreateFile(fromFile, GENERIC_READ, FILE_SHARE_READ, 0,
  2012. OPEN_EXISTING, 0, 0);
  2013. cmSystemToolsWindowsHandle hTo =
  2014. CreateFile(toFile, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2015. if(!hFrom || !hTo)
  2016. {
  2017. return false;
  2018. }
  2019. FILETIME timeCreation;
  2020. FILETIME timeLastAccess;
  2021. FILETIME timeLastWrite;
  2022. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  2023. {
  2024. return false;
  2025. }
  2026. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  2027. {
  2028. return false;
  2029. }
  2030. #else
  2031. struct stat fromStat;
  2032. if(stat(fromFile, &fromStat) < 0)
  2033. {
  2034. return false;
  2035. }
  2036. struct utimbuf buf;
  2037. buf.actime = fromStat.st_atime;
  2038. buf.modtime = fromStat.st_mtime;
  2039. if(utime(toFile, &buf) < 0)
  2040. {
  2041. return false;
  2042. }
  2043. #endif
  2044. return true;
  2045. }
  2046. //----------------------------------------------------------------------------
  2047. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  2048. {
  2049. return new cmSystemToolsFileTime;
  2050. }
  2051. //----------------------------------------------------------------------------
  2052. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  2053. {
  2054. delete t;
  2055. }
  2056. //----------------------------------------------------------------------------
  2057. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  2058. {
  2059. #if defined(_WIN32) && !defined(__CYGWIN__)
  2060. cmSystemToolsWindowsHandle h =
  2061. CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  2062. if(!h)
  2063. {
  2064. return false;
  2065. }
  2066. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2067. {
  2068. return false;
  2069. }
  2070. #else
  2071. struct stat st;
  2072. if(stat(fname, &st) < 0)
  2073. {
  2074. return false;
  2075. }
  2076. t->timeBuf.actime = st.st_atime;
  2077. t->timeBuf.modtime = st.st_mtime;
  2078. #endif
  2079. return true;
  2080. }
  2081. //----------------------------------------------------------------------------
  2082. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2083. {
  2084. #if defined(_WIN32) && !defined(__CYGWIN__)
  2085. cmSystemToolsWindowsHandle h =
  2086. CreateFile(fname, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2087. if(!h)
  2088. {
  2089. return false;
  2090. }
  2091. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2092. {
  2093. return false;
  2094. }
  2095. #else
  2096. if(utime(fname, &t->timeBuf) < 0)
  2097. {
  2098. return false;
  2099. }
  2100. #endif
  2101. return true;
  2102. }
  2103. //----------------------------------------------------------------------------
  2104. #ifdef _WIN32
  2105. # ifndef CRYPT_SILENT
  2106. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2107. # endif
  2108. static int WinCryptRandom(void* data, size_t size)
  2109. {
  2110. int result = 0;
  2111. HCRYPTPROV hProvider = 0;
  2112. if(CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2113. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2114. {
  2115. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data)? 1:0;
  2116. CryptReleaseContext(hProvider, 0);
  2117. }
  2118. return result;
  2119. }
  2120. #endif
  2121. //----------------------------------------------------------------------------
  2122. unsigned int cmSystemTools::RandomSeed()
  2123. {
  2124. #if defined(_WIN32) && !defined(__CYGWIN__)
  2125. unsigned int seed = 0;
  2126. // Try using a real random source.
  2127. if(WinCryptRandom(&seed, sizeof(seed)))
  2128. {
  2129. return seed;
  2130. }
  2131. // Fall back to the time and pid.
  2132. FILETIME ft;
  2133. GetSystemTimeAsFileTime(&ft);
  2134. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2135. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2136. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2137. return t1 ^ t2 ^ pid;
  2138. #else
  2139. union
  2140. {
  2141. unsigned int integer;
  2142. char bytes[sizeof(unsigned int)];
  2143. } seed;
  2144. // Try using a real random source.
  2145. std::ifstream fin("/dev/urandom");
  2146. if(fin && fin.read(seed.bytes, sizeof(seed)) &&
  2147. fin.gcount() == sizeof(seed))
  2148. {
  2149. return seed.integer;
  2150. }
  2151. // Fall back to the time and pid.
  2152. struct timeval t;
  2153. gettimeofday(&t, 0);
  2154. unsigned int pid = static_cast<unsigned int>(getpid());
  2155. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2156. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2157. // Since tv_usec never fills more than 11 bits we shift it to fill
  2158. // in the slow-changing high-order bits of tv_sec.
  2159. return tv_sec ^ (tv_usec << 21) ^ pid;
  2160. #endif
  2161. }
  2162. //----------------------------------------------------------------------------
  2163. static std::string cmSystemToolsExecutableDirectory;
  2164. void cmSystemTools::FindExecutableDirectory(const char* argv0)
  2165. {
  2166. #if defined(_WIN32) && !defined(__CYGWIN__)
  2167. (void)argv0; // ignore this on windows
  2168. char modulepath[_MAX_PATH];
  2169. ::GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  2170. cmSystemToolsExecutableDirectory =
  2171. cmSystemTools::GetFilenamePath(modulepath);
  2172. return;
  2173. #else
  2174. std::string errorMsg;
  2175. std::string exe;
  2176. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2177. {
  2178. // remove symlinks
  2179. exe = cmSystemTools::GetRealPath(exe.c_str());
  2180. cmSystemToolsExecutableDirectory =
  2181. cmSystemTools::GetFilenamePath(exe.c_str());
  2182. }
  2183. else
  2184. {
  2185. // ???
  2186. }
  2187. #endif
  2188. }
  2189. //----------------------------------------------------------------------------
  2190. const char* cmSystemTools::GetExecutableDirectory()
  2191. {
  2192. return cmSystemToolsExecutableDirectory.c_str();
  2193. }
  2194. //----------------------------------------------------------------------------
  2195. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2196. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2197. bool newline, bool enabled)
  2198. {
  2199. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2200. // to determine whether the stream is displayed on a tty. In this
  2201. // case it assumes no unless we tell it otherwise. Since we want
  2202. // color messages to be displayed for users we will assume yes.
  2203. // However, we can test for some situations when the answer is most
  2204. // likely no.
  2205. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2206. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2207. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2208. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2209. {
  2210. // Avoid printing color escapes during dashboard builds.
  2211. assumeTTY = 0;
  2212. }
  2213. if(enabled)
  2214. {
  2215. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2216. message, newline? "\n" : "");
  2217. }
  2218. else
  2219. {
  2220. // Color is disabled. Print without color.
  2221. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2222. }
  2223. }
  2224. #endif
  2225. //----------------------------------------------------------------------------
  2226. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2227. std::string& soname)
  2228. {
  2229. // For ELF shared libraries use a real parser to get the correct
  2230. // soname.
  2231. #if defined(CMAKE_USE_ELF_PARSER)
  2232. cmELF elf(fullPath.c_str());
  2233. if(elf)
  2234. {
  2235. return elf.GetSOName(soname);
  2236. }
  2237. #endif
  2238. // If the file is not a symlink we have no guess for its soname.
  2239. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2240. {
  2241. return false;
  2242. }
  2243. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2244. {
  2245. return false;
  2246. }
  2247. // If the symlink has a path component we have no guess for the soname.
  2248. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2249. {
  2250. return false;
  2251. }
  2252. // If the symlink points at an extended version of the same name
  2253. // assume it is the soname.
  2254. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2255. if(soname.length() > name.length() &&
  2256. soname.substr(0, name.length()) == name)
  2257. {
  2258. return true;
  2259. }
  2260. return false;
  2261. }
  2262. //----------------------------------------------------------------------------
  2263. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2264. std::string& soname)
  2265. {
  2266. std::vector<cmStdString> cmds;
  2267. cmds.push_back("otool");
  2268. cmds.push_back("-D");
  2269. cmds.push_back(fullPath.c_str());
  2270. std::string output;
  2271. RunSingleCommand(cmds, &output, 0, 0, OUTPUT_NONE);
  2272. std::vector<std::string> strs = cmSystemTools::tokenize(output, "\n");
  2273. if(strs.size() == 2)
  2274. {
  2275. soname = strs[1];
  2276. return true;
  2277. }
  2278. return false;
  2279. }
  2280. //----------------------------------------------------------------------------
  2281. #if defined(CMAKE_USE_ELF_PARSER)
  2282. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2283. std::string const& want)
  2284. {
  2285. // Search for the desired rpath.
  2286. std::string::size_type pos = have.find(want);
  2287. // If the path is not present we are done.
  2288. if(pos == std::string::npos)
  2289. {
  2290. return pos;
  2291. }
  2292. // Build a regex to match a properly separated path instance.
  2293. std::string regex_str = "(^|:)(";
  2294. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2295. {
  2296. int ch = *i;
  2297. if(!(('a' <= ch && ch <= 'z') ||
  2298. ('A' <= ch && ch <= 'Z') ||
  2299. ('0' <= ch && ch <= '9')))
  2300. {
  2301. // Escape the non-alphanumeric character.
  2302. regex_str += "\\";
  2303. }
  2304. // Store the character.
  2305. regex_str.append(1, static_cast<char>(ch));
  2306. }
  2307. regex_str += ")(:|$)";
  2308. // Look for the separated path.
  2309. cmsys::RegularExpression regex(regex_str.c_str());
  2310. if(regex.find(have))
  2311. {
  2312. // Return the position of the path portion.
  2313. return regex.start(2);
  2314. }
  2315. else
  2316. {
  2317. // The desired rpath was not found.
  2318. return std::string::npos;
  2319. }
  2320. }
  2321. #endif
  2322. #if defined(CMAKE_USE_ELF_PARSER)
  2323. struct cmSystemToolsRPathInfo
  2324. {
  2325. unsigned long Position;
  2326. unsigned long Size;
  2327. std::string Name;
  2328. std::string Value;
  2329. };
  2330. #endif
  2331. //----------------------------------------------------------------------------
  2332. bool cmSystemTools::ChangeRPath(std::string const& file,
  2333. std::string const& oldRPath,
  2334. std::string const& newRPath,
  2335. std::string* emsg,
  2336. bool* changed)
  2337. {
  2338. #if defined(CMAKE_USE_ELF_PARSER)
  2339. if(changed)
  2340. {
  2341. *changed = false;
  2342. }
  2343. int rp_count = 0;
  2344. cmSystemToolsRPathInfo rp[2];
  2345. {
  2346. // Parse the ELF binary.
  2347. cmELF elf(file.c_str());
  2348. // Get the RPATH and RUNPATH entries from it.
  2349. int se_count = 0;
  2350. cmELF::StringEntry const* se[2] = {0, 0};
  2351. const char* se_name[2] = {0, 0};
  2352. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2353. {
  2354. se[se_count] = se_rpath;
  2355. se_name[se_count] = "RPATH";
  2356. ++se_count;
  2357. }
  2358. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2359. {
  2360. se[se_count] = se_runpath;
  2361. se_name[se_count] = "RUNPATH";
  2362. ++se_count;
  2363. }
  2364. if(se_count == 0)
  2365. {
  2366. if(newRPath.empty())
  2367. {
  2368. // The new rpath is empty and there is no rpath anyway so it is
  2369. // okay.
  2370. return true;
  2371. }
  2372. else
  2373. {
  2374. if(emsg)
  2375. {
  2376. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2377. *emsg += elf.GetErrorMessage();
  2378. }
  2379. return false;
  2380. }
  2381. }
  2382. for(int i=0; i < se_count; ++i)
  2383. {
  2384. // If both RPATH and RUNPATH refer to the same string literal it
  2385. // needs to be changed only once.
  2386. if(rp_count && rp[0].Position == se[i]->Position)
  2387. {
  2388. continue;
  2389. }
  2390. // Make sure the current rpath contains the old rpath.
  2391. std::string::size_type pos =
  2392. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2393. if(pos == std::string::npos)
  2394. {
  2395. // If it contains the new rpath instead then it is okay.
  2396. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2397. {
  2398. continue;
  2399. }
  2400. if(emsg)
  2401. {
  2402. cmOStringStream e;
  2403. e << "The current " << se_name[i] << " is:\n"
  2404. << " " << se[i]->Value << "\n"
  2405. << "which does not contain:\n"
  2406. << " " << oldRPath << "\n"
  2407. << "as was expected.";
  2408. *emsg = e.str();
  2409. }
  2410. return false;
  2411. }
  2412. // Store information about the entry in the file.
  2413. rp[rp_count].Position = se[i]->Position;
  2414. rp[rp_count].Size = se[i]->Size;
  2415. rp[rp_count].Name = se_name[i];
  2416. // Construct the new value which preserves the part of the path
  2417. // not being changed.
  2418. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2419. rp[rp_count].Value += newRPath;
  2420. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2421. oldRPath.npos);
  2422. // Make sure there is enough room to store the new rpath and at
  2423. // least one null terminator.
  2424. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2425. {
  2426. if(emsg)
  2427. {
  2428. *emsg = "The replacement path is too long for the ";
  2429. *emsg += se_name[i];
  2430. *emsg += " entry.";
  2431. }
  2432. return false;
  2433. }
  2434. // This entry is ready for update.
  2435. ++rp_count;
  2436. }
  2437. }
  2438. // If no runtime path needs to be changed, we are done.
  2439. if(rp_count == 0)
  2440. {
  2441. return true;
  2442. }
  2443. {
  2444. // Open the file for update.
  2445. std::ofstream f(file.c_str(),
  2446. std::ios::in | std::ios::out | std::ios::binary);
  2447. if(!f)
  2448. {
  2449. if(emsg)
  2450. {
  2451. *emsg = "Error opening file for update.";
  2452. }
  2453. return false;
  2454. }
  2455. // Store the new RPATH and RUNPATH strings.
  2456. for(int i=0; i < rp_count; ++i)
  2457. {
  2458. // Seek to the RPATH position.
  2459. if(!f.seekp(rp[i].Position))
  2460. {
  2461. if(emsg)
  2462. {
  2463. *emsg = "Error seeking to ";
  2464. *emsg += rp[i].Name;
  2465. *emsg += " position.";
  2466. }
  2467. return false;
  2468. }
  2469. // Write the new rpath. Follow it with enough null terminators to
  2470. // fill the string table entry.
  2471. f << rp[i].Value;
  2472. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2473. {
  2474. f << '\0';
  2475. }
  2476. // Make sure it wrote correctly.
  2477. if(!f)
  2478. {
  2479. if(emsg)
  2480. {
  2481. *emsg = "Error writing the new ";
  2482. *emsg += rp[i].Name;
  2483. *emsg += " string to the file.";
  2484. }
  2485. return false;
  2486. }
  2487. }
  2488. }
  2489. // Everything was updated successfully.
  2490. if(changed)
  2491. {
  2492. *changed = true;
  2493. }
  2494. return true;
  2495. #else
  2496. (void)file;
  2497. (void)oldRPath;
  2498. (void)newRPath;
  2499. (void)emsg;
  2500. (void)changed;
  2501. return false;
  2502. #endif
  2503. }
  2504. //----------------------------------------------------------------------------
  2505. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2506. const char* lhss, const char* rhss)
  2507. {
  2508. unsigned int lhs[4] = {0,0,0,0};
  2509. unsigned int rhs[4] = {0,0,0,0};
  2510. sscanf(lhss, "%u.%u.%u.%u", &lhs[0], &lhs[1], &lhs[2], &lhs[3]);
  2511. sscanf(rhss, "%u.%u.%u.%u", &rhs[0], &rhs[1], &rhs[2], &rhs[3]);
  2512. // Do component-wise comparison.
  2513. for(unsigned int i=0; i < 4; ++i)
  2514. {
  2515. if(lhs[i] < rhs[i])
  2516. {
  2517. // lhs < rhs, so true if operation is LESS
  2518. return op == cmSystemTools::OP_LESS;
  2519. }
  2520. else if(lhs[i] > rhs[i])
  2521. {
  2522. // lhs > rhs, so true if operation is GREATER
  2523. return op == cmSystemTools::OP_GREATER;
  2524. }
  2525. }
  2526. // lhs == rhs, so true if operation is EQUAL
  2527. return op == cmSystemTools::OP_EQUAL;
  2528. }
  2529. //----------------------------------------------------------------------------
  2530. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2531. bool* removed)
  2532. {
  2533. #if defined(CMAKE_USE_ELF_PARSER)
  2534. if(removed)
  2535. {
  2536. *removed = false;
  2537. }
  2538. int zeroCount = 0;
  2539. unsigned long zeroPosition[2] = {0,0};
  2540. unsigned long zeroSize[2] = {0,0};
  2541. unsigned long bytesBegin = 0;
  2542. std::vector<char> bytes;
  2543. {
  2544. // Parse the ELF binary.
  2545. cmELF elf(file.c_str());
  2546. // Get the RPATH and RUNPATH entries from it and sort them by index
  2547. // in the dynamic section header.
  2548. int se_count = 0;
  2549. cmELF::StringEntry const* se[2] = {0, 0};
  2550. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2551. {
  2552. se[se_count++] = se_rpath;
  2553. }
  2554. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2555. {
  2556. se[se_count++] = se_runpath;
  2557. }
  2558. if(se_count == 0)
  2559. {
  2560. // There is no RPATH or RUNPATH anyway.
  2561. return true;
  2562. }
  2563. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2564. {
  2565. cmsys_stl::swap(se[0], se[1]);
  2566. }
  2567. // Get the size of the dynamic section header.
  2568. unsigned int count = elf.GetDynamicEntryCount();
  2569. if(count == 0)
  2570. {
  2571. // This should happen only for invalid ELF files where a DT_NULL
  2572. // appears before the end of the table.
  2573. if(emsg)
  2574. {
  2575. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2576. }
  2577. return false;
  2578. }
  2579. // Save information about the string entries to be zeroed.
  2580. zeroCount = se_count;
  2581. for(int i=0; i < se_count; ++i)
  2582. {
  2583. zeroPosition[i] = se[i]->Position;
  2584. zeroSize[i] = se[i]->Size;
  2585. }
  2586. // Get the range of file positions corresponding to each entry and
  2587. // the rest of the table after them.
  2588. unsigned long entryBegin[3] = {0,0,0};
  2589. unsigned long entryEnd[2] = {0,0};
  2590. for(int i=0; i < se_count; ++i)
  2591. {
  2592. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2593. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2594. }
  2595. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2596. // The data are to be written over the old table entries starting at
  2597. // the first one being removed.
  2598. bytesBegin = entryBegin[0];
  2599. unsigned long bytesEnd = entryBegin[se_count];
  2600. // Allocate a buffer to hold the part of the file to be written.
  2601. // Initialize it with zeros.
  2602. bytes.resize(bytesEnd - bytesBegin, 0);
  2603. // Read the part of the DYNAMIC section header that will move.
  2604. // The remainder of the buffer will be left with zeros which
  2605. // represent a DT_NULL entry.
  2606. char* data = &bytes[0];
  2607. for(int i=0; i < se_count; ++i)
  2608. {
  2609. // Read data between the entries being removed.
  2610. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2611. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2612. {
  2613. if(emsg)
  2614. {
  2615. *emsg = "Failed to read DYNAMIC section header.";
  2616. }
  2617. return false;
  2618. }
  2619. data += sz;
  2620. }
  2621. }
  2622. // Open the file for update.
  2623. std::ofstream f(file.c_str(),
  2624. std::ios::in | std::ios::out | std::ios::binary);
  2625. if(!f)
  2626. {
  2627. if(emsg)
  2628. {
  2629. *emsg = "Error opening file for update.";
  2630. }
  2631. return false;
  2632. }
  2633. // Write the new DYNAMIC table header.
  2634. if(!f.seekp(bytesBegin))
  2635. {
  2636. if(emsg)
  2637. {
  2638. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2639. }
  2640. return false;
  2641. }
  2642. if(!f.write(&bytes[0], bytes.size()))
  2643. {
  2644. if(emsg)
  2645. {
  2646. *emsg = "Error replacing DYNAMIC table header.";
  2647. }
  2648. return false;
  2649. }
  2650. // Fill the RPATH and RUNPATH strings with zero bytes.
  2651. for(int i=0; i < zeroCount; ++i)
  2652. {
  2653. if(!f.seekp(zeroPosition[i]))
  2654. {
  2655. if(emsg)
  2656. {
  2657. *emsg = "Error seeking to RPATH position.";
  2658. }
  2659. return false;
  2660. }
  2661. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2662. {
  2663. f << '\0';
  2664. }
  2665. if(!f)
  2666. {
  2667. if(emsg)
  2668. {
  2669. *emsg = "Error writing the empty rpath string to the file.";
  2670. }
  2671. return false;
  2672. }
  2673. }
  2674. // Everything was updated successfully.
  2675. if(removed)
  2676. {
  2677. *removed = true;
  2678. }
  2679. return true;
  2680. #else
  2681. (void)file;
  2682. (void)emsg;
  2683. (void)removed;
  2684. return false;
  2685. #endif
  2686. }
  2687. //----------------------------------------------------------------------------
  2688. bool cmSystemTools::CheckRPath(std::string const& file,
  2689. std::string const& newRPath)
  2690. {
  2691. #if defined(CMAKE_USE_ELF_PARSER)
  2692. // Parse the ELF binary.
  2693. cmELF elf(file.c_str());
  2694. // Get the RPATH or RUNPATH entry from it.
  2695. cmELF::StringEntry const* se = elf.GetRPath();
  2696. if(!se)
  2697. {
  2698. se = elf.GetRunPath();
  2699. }
  2700. // Make sure the current rpath contains the new rpath.
  2701. if(newRPath.empty())
  2702. {
  2703. if(!se)
  2704. {
  2705. return true;
  2706. }
  2707. }
  2708. else
  2709. {
  2710. if(se &&
  2711. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2712. {
  2713. return true;
  2714. }
  2715. }
  2716. return false;
  2717. #else
  2718. (void)file;
  2719. (void)newRPath;
  2720. return false;
  2721. #endif
  2722. }
  2723. //----------------------------------------------------------------------------
  2724. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2725. {
  2726. // Windows sometimes locks files temporarily so try a few times.
  2727. for(int i = 0; i < 10; ++i)
  2728. {
  2729. if(cmSystemTools::RemoveADirectory(dir))
  2730. {
  2731. return true;
  2732. }
  2733. cmSystemTools::Delay(100);
  2734. }
  2735. return false;
  2736. }
  2737. //----------------------------------------------------------------------------
  2738. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2739. const std::string& sep)
  2740. {
  2741. std::vector<std::string> tokens;
  2742. std::string::size_type tokend = 0;
  2743. do
  2744. {
  2745. std::string::size_type tokstart=str.find_first_not_of(sep, tokend);
  2746. if (tokstart==std::string::npos)
  2747. {
  2748. break; // no more tokens
  2749. }
  2750. tokend=str.find_first_of(sep,tokstart);
  2751. if (tokend==std::string::npos)
  2752. {
  2753. tokens.push_back(str.substr(tokstart));
  2754. }
  2755. else
  2756. {
  2757. tokens.push_back(str.substr(tokstart,tokend-tokstart));
  2758. }
  2759. } while (tokend!=std::string::npos);
  2760. if (tokens.empty())
  2761. {
  2762. tokens.push_back("");
  2763. }
  2764. return tokens;
  2765. }