cmSystemTools.cxx 75 KB

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