cmSystemTools.cxx 73 KB

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