cmSystemTools.cxx 75 KB

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