cmSystemTools.cxx 73 KB

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