cmSystemTools.cxx 74 KB

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