cmSystemTools.cxx 75 KB

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