cmSystemTools.cxx 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894
  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. struct stat s;
  1681. stat(fileIt->c_str(), &s);
  1682. archive_read_disk_entry_from_file(disk, entry, -1, &s);
  1683. CHECK_ARCHIVE_ERROR(res, "read disk entry:");
  1684. // write entry header
  1685. res = archive_write_header(a, entry);
  1686. CHECK_ARCHIVE_ERROR(res, "write header: ");
  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. archive_entry_free(entry);
  1716. }
  1717. // close the archive and finish the write
  1718. archive_write_close(a);
  1719. archive_write_finish(a);
  1720. return true;
  1721. #else
  1722. (void)outFileName;
  1723. (void)files;
  1724. (void)gzip;
  1725. (void)verbose;
  1726. return false;
  1727. #endif
  1728. }
  1729. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1730. namespace{
  1731. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1732. #define BSDTAR_FILESIZE_TYPE unsigned long
  1733. void
  1734. list_item_verbose(FILE *out, struct archive_entry *entry)
  1735. {
  1736. char tmp[100];
  1737. size_t w;
  1738. const char *p;
  1739. const char *fmt;
  1740. time_t tim;
  1741. static time_t now;
  1742. size_t u_width = 6;
  1743. size_t gs_width = 13;
  1744. /*
  1745. * We avoid collecting the entire list in memory at once by
  1746. * listing things as we see them. However, that also means we can't
  1747. * just pre-compute the field widths. Instead, we start with guesses
  1748. * and just widen them as necessary. These numbers are completely
  1749. * arbitrary.
  1750. */
  1751. if (!now)
  1752. {
  1753. time(&now);
  1754. }
  1755. fprintf(out, "%s %d ",
  1756. archive_entry_strmode(entry),
  1757. archive_entry_nlink(entry));
  1758. /* Use uname if it's present, else uid. */
  1759. p = archive_entry_uname(entry);
  1760. if ((p == NULL) || (*p == '\0'))
  1761. {
  1762. sprintf(tmp, "%lu ",
  1763. (unsigned long)archive_entry_uid(entry));
  1764. p = tmp;
  1765. }
  1766. w = strlen(p);
  1767. if (w > u_width)
  1768. {
  1769. u_width = w;
  1770. }
  1771. fprintf(out, "%-*s ", (int)u_width, p);
  1772. /* Use gname if it's present, else gid. */
  1773. p = archive_entry_gname(entry);
  1774. if (p != NULL && p[0] != '\0')
  1775. {
  1776. fprintf(out, "%s", p);
  1777. w = strlen(p);
  1778. }
  1779. else
  1780. {
  1781. sprintf(tmp, "%lu",
  1782. (unsigned long)archive_entry_gid(entry));
  1783. w = strlen(tmp);
  1784. fprintf(out, "%s", tmp);
  1785. }
  1786. /*
  1787. * Print device number or file size, right-aligned so as to make
  1788. * total width of group and devnum/filesize fields be gs_width.
  1789. * If gs_width is too small, grow it.
  1790. */
  1791. if (archive_entry_filetype(entry) == AE_IFCHR
  1792. || archive_entry_filetype(entry) == AE_IFBLK)
  1793. {
  1794. sprintf(tmp, "%lu,%lu",
  1795. (unsigned long)archive_entry_rdevmajor(entry),
  1796. (unsigned long)archive_entry_rdevminor(entry));
  1797. }
  1798. else
  1799. {
  1800. /*
  1801. * Note the use of platform-dependent macros to format
  1802. * the filesize here. We need the format string and the
  1803. * corresponding type for the cast.
  1804. */
  1805. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1806. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1807. }
  1808. if (w + strlen(tmp) >= gs_width)
  1809. {
  1810. gs_width = w+strlen(tmp)+1;
  1811. }
  1812. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1813. /* Format the time using 'ls -l' conventions. */
  1814. tim = archive_entry_mtime(entry);
  1815. #define HALF_YEAR (time_t)365 * 86400 / 2
  1816. #if defined(_WIN32) && !defined(__CYGWIN__)
  1817. /* Windows' strftime function does not support %e format. */
  1818. #define DAY_FMT "%d"
  1819. #else
  1820. #define DAY_FMT "%e" /* Day number without leading zeros */
  1821. #endif
  1822. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1823. {
  1824. fmt = DAY_FMT " %b %Y";
  1825. }
  1826. else
  1827. {
  1828. fmt = DAY_FMT " %b %H:%M";
  1829. }
  1830. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1831. fprintf(out, " %s ", tmp);
  1832. fprintf(out, "%s", archive_entry_pathname(entry));
  1833. /* Extra information for links. */
  1834. if (archive_entry_hardlink(entry)) /* Hard link */
  1835. {
  1836. fprintf(out, " link to %s",
  1837. archive_entry_hardlink(entry));
  1838. }
  1839. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1840. {
  1841. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1842. }
  1843. }
  1844. int copy_data(struct archive *ar, struct archive *aw)
  1845. {
  1846. int r;
  1847. const void *buff;
  1848. size_t size;
  1849. off_t offset;
  1850. for (;;)
  1851. {
  1852. r = archive_read_data_block(ar, &buff, &size, &offset);
  1853. if (r == ARCHIVE_EOF)
  1854. {
  1855. return (ARCHIVE_OK);
  1856. }
  1857. if (r != ARCHIVE_OK)
  1858. {
  1859. return (r);
  1860. }
  1861. r = archive_write_data_block(aw, buff, size, offset);
  1862. if (r != ARCHIVE_OK)
  1863. {
  1864. cmSystemTools::Message("archive_write_data_block()",
  1865. archive_error_string(aw));
  1866. return (r);
  1867. }
  1868. }
  1869. }
  1870. bool extract_tar(const char* outFileName, bool verbose,
  1871. bool extract)
  1872. {
  1873. struct archive* a = archive_read_new();
  1874. struct archive *ext = archive_write_disk_new();
  1875. archive_read_support_compression_all(a);
  1876. archive_read_support_format_all(a);
  1877. struct archive_entry *entry;
  1878. int r = archive_read_open_file(a, outFileName, 10240);
  1879. if(r)
  1880. {
  1881. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1882. archive_error_string(a));
  1883. return false;
  1884. }
  1885. for (;;)
  1886. {
  1887. r = archive_read_next_header(a, &entry);
  1888. if (r == ARCHIVE_EOF)
  1889. {
  1890. break;
  1891. }
  1892. if (r != ARCHIVE_OK)
  1893. {
  1894. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1895. archive_error_string(a));
  1896. }
  1897. if (verbose && extract)
  1898. {
  1899. cmSystemTools::Stdout("x ");
  1900. }
  1901. if(verbose && !extract)
  1902. {
  1903. list_item_verbose(stdout, entry);
  1904. }
  1905. else
  1906. {
  1907. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1908. }
  1909. if(extract)
  1910. {
  1911. r = archive_write_header(ext, entry);
  1912. if (r != ARCHIVE_OK)
  1913. {
  1914. cmSystemTools::Error("Problem with archive_write_header(): ",
  1915. archive_error_string(a));
  1916. }
  1917. else
  1918. {
  1919. copy_data(a, ext);
  1920. r = archive_write_finish_entry(ext);
  1921. if (r != ARCHIVE_OK)
  1922. {
  1923. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1924. archive_error_string(ext));
  1925. }
  1926. }
  1927. }
  1928. if (verbose || !extract)
  1929. {
  1930. cmSystemTools::Stdout("\n");
  1931. }
  1932. }
  1933. archive_read_close(a);
  1934. archive_read_finish(a);
  1935. return true;
  1936. }
  1937. }
  1938. #endif
  1939. bool cmSystemTools::ExtractTar(const char* outFileName,
  1940. bool , bool verbose)
  1941. {
  1942. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1943. return extract_tar(outFileName, verbose, true);
  1944. #else
  1945. (void)outFileName;
  1946. (void)verbose;
  1947. return false;
  1948. #endif
  1949. }
  1950. bool cmSystemTools::ListTar(const char* outFileName,
  1951. bool ,
  1952. bool verbose)
  1953. {
  1954. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1955. return extract_tar(outFileName, verbose, false);
  1956. #else
  1957. (void)outFileName;
  1958. (void)verbose;
  1959. return false;
  1960. #endif
  1961. }
  1962. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1963. double timeout,
  1964. std::vector<char>& out,
  1965. std::vector<char>& err)
  1966. {
  1967. line = "";
  1968. std::vector<char>::iterator outiter = out.begin();
  1969. std::vector<char>::iterator erriter = err.begin();
  1970. while(1)
  1971. {
  1972. // Check for a newline in stdout.
  1973. for(;outiter != out.end(); ++outiter)
  1974. {
  1975. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1976. {
  1977. break;
  1978. }
  1979. else if(*outiter == '\n' || *outiter == '\0')
  1980. {
  1981. int length = outiter-out.begin();
  1982. if(length > 1 && *(outiter-1) == '\r')
  1983. {
  1984. --length;
  1985. }
  1986. if(length > 0)
  1987. {
  1988. line.append(&out[0], length);
  1989. }
  1990. out.erase(out.begin(), outiter+1);
  1991. return cmsysProcess_Pipe_STDOUT;
  1992. }
  1993. }
  1994. // Check for a newline in stderr.
  1995. for(;erriter != err.end(); ++erriter)
  1996. {
  1997. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1998. {
  1999. break;
  2000. }
  2001. else if(*erriter == '\n' || *erriter == '\0')
  2002. {
  2003. int length = erriter-err.begin();
  2004. if(length > 1 && *(erriter-1) == '\r')
  2005. {
  2006. --length;
  2007. }
  2008. if(length > 0)
  2009. {
  2010. line.append(&err[0], length);
  2011. }
  2012. err.erase(err.begin(), erriter+1);
  2013. return cmsysProcess_Pipe_STDERR;
  2014. }
  2015. }
  2016. // No newlines found. Wait for more data from the process.
  2017. int length;
  2018. char* data;
  2019. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  2020. if(pipe == cmsysProcess_Pipe_Timeout)
  2021. {
  2022. // Timeout has been exceeded.
  2023. return pipe;
  2024. }
  2025. else if(pipe == cmsysProcess_Pipe_STDOUT)
  2026. {
  2027. // Append to the stdout buffer.
  2028. std::vector<char>::size_type size = out.size();
  2029. out.insert(out.end(), data, data+length);
  2030. outiter = out.begin()+size;
  2031. }
  2032. else if(pipe == cmsysProcess_Pipe_STDERR)
  2033. {
  2034. // Append to the stderr buffer.
  2035. std::vector<char>::size_type size = err.size();
  2036. err.insert(err.end(), data, data+length);
  2037. erriter = err.begin()+size;
  2038. }
  2039. else if(pipe == cmsysProcess_Pipe_None)
  2040. {
  2041. // Both stdout and stderr pipes have broken. Return leftover data.
  2042. if(!out.empty())
  2043. {
  2044. line.append(&out[0], outiter-out.begin());
  2045. out.erase(out.begin(), out.end());
  2046. return cmsysProcess_Pipe_STDOUT;
  2047. }
  2048. else if(!err.empty())
  2049. {
  2050. line.append(&err[0], erriter-err.begin());
  2051. err.erase(err.begin(), err.end());
  2052. return cmsysProcess_Pipe_STDERR;
  2053. }
  2054. else
  2055. {
  2056. return cmsysProcess_Pipe_None;
  2057. }
  2058. }
  2059. }
  2060. }
  2061. void cmSystemTools::DoNotInheritStdPipes()
  2062. {
  2063. #ifdef _WIN32
  2064. // Check to see if we are attached to a console
  2065. // if so, then do not stop the inherited pipes
  2066. // or stdout and stderr will not show up in dos
  2067. // shell windows
  2068. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  2069. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  2070. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  2071. {
  2072. return;
  2073. }
  2074. {
  2075. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  2076. DuplicateHandle(GetCurrentProcess(), out,
  2077. GetCurrentProcess(), &out, 0, FALSE,
  2078. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2079. SetStdHandle(STD_OUTPUT_HANDLE, out);
  2080. }
  2081. {
  2082. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  2083. DuplicateHandle(GetCurrentProcess(), out,
  2084. GetCurrentProcess(), &out, 0, FALSE,
  2085. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  2086. SetStdHandle(STD_ERROR_HANDLE, out);
  2087. }
  2088. #endif
  2089. }
  2090. //----------------------------------------------------------------------------
  2091. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  2092. {
  2093. #if defined(_WIN32) && !defined(__CYGWIN__)
  2094. cmSystemToolsWindowsHandle hFrom =
  2095. CreateFile(fromFile, GENERIC_READ, FILE_SHARE_READ, 0,
  2096. OPEN_EXISTING, 0, 0);
  2097. cmSystemToolsWindowsHandle hTo =
  2098. CreateFile(toFile, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2099. if(!hFrom || !hTo)
  2100. {
  2101. return false;
  2102. }
  2103. FILETIME timeCreation;
  2104. FILETIME timeLastAccess;
  2105. FILETIME timeLastWrite;
  2106. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  2107. {
  2108. return false;
  2109. }
  2110. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  2111. {
  2112. return false;
  2113. }
  2114. #else
  2115. struct stat fromStat;
  2116. if(stat(fromFile, &fromStat) < 0)
  2117. {
  2118. return false;
  2119. }
  2120. struct utimbuf buf;
  2121. buf.actime = fromStat.st_atime;
  2122. buf.modtime = fromStat.st_mtime;
  2123. if(utime(toFile, &buf) < 0)
  2124. {
  2125. return false;
  2126. }
  2127. #endif
  2128. return true;
  2129. }
  2130. //----------------------------------------------------------------------------
  2131. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  2132. {
  2133. return new cmSystemToolsFileTime;
  2134. }
  2135. //----------------------------------------------------------------------------
  2136. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  2137. {
  2138. delete t;
  2139. }
  2140. //----------------------------------------------------------------------------
  2141. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  2142. {
  2143. #if defined(_WIN32) && !defined(__CYGWIN__)
  2144. cmSystemToolsWindowsHandle h =
  2145. CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  2146. if(!h)
  2147. {
  2148. return false;
  2149. }
  2150. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2151. {
  2152. return false;
  2153. }
  2154. #else
  2155. struct stat st;
  2156. if(stat(fname, &st) < 0)
  2157. {
  2158. return false;
  2159. }
  2160. t->timeBuf.actime = st.st_atime;
  2161. t->timeBuf.modtime = st.st_mtime;
  2162. #endif
  2163. return true;
  2164. }
  2165. //----------------------------------------------------------------------------
  2166. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2167. {
  2168. #if defined(_WIN32) && !defined(__CYGWIN__)
  2169. cmSystemToolsWindowsHandle h =
  2170. CreateFile(fname, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2171. if(!h)
  2172. {
  2173. return false;
  2174. }
  2175. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2176. {
  2177. return false;
  2178. }
  2179. #else
  2180. if(utime(fname, &t->timeBuf) < 0)
  2181. {
  2182. return false;
  2183. }
  2184. #endif
  2185. return true;
  2186. }
  2187. //----------------------------------------------------------------------------
  2188. static std::string cmSystemToolsExecutableDirectory;
  2189. void cmSystemTools::FindExecutableDirectory(const char* argv0)
  2190. {
  2191. #if defined(_WIN32) && !defined(__CYGWIN__)
  2192. (void)argv0; // ignore this on windows
  2193. char modulepath[_MAX_PATH];
  2194. ::GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  2195. cmSystemToolsExecutableDirectory =
  2196. cmSystemTools::GetFilenamePath(modulepath);
  2197. return;
  2198. #else
  2199. std::string errorMsg;
  2200. std::string exe;
  2201. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2202. {
  2203. // remove symlinks
  2204. exe = cmSystemTools::GetRealPath(exe.c_str());
  2205. cmSystemToolsExecutableDirectory =
  2206. cmSystemTools::GetFilenamePath(exe.c_str());
  2207. }
  2208. else
  2209. {
  2210. // ???
  2211. }
  2212. #endif
  2213. }
  2214. //----------------------------------------------------------------------------
  2215. const char* cmSystemTools::GetExecutableDirectory()
  2216. {
  2217. return cmSystemToolsExecutableDirectory.c_str();
  2218. }
  2219. //----------------------------------------------------------------------------
  2220. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2221. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2222. bool newline, bool enabled)
  2223. {
  2224. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2225. // to determine whether the stream is displayed on a tty. In this
  2226. // case it assumes no unless we tell it otherwise. Since we want
  2227. // color messages to be displayed for users we will assume yes.
  2228. // However, we can test for some situations when the answer is most
  2229. // likely no.
  2230. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2231. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2232. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2233. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2234. {
  2235. // Avoid printing color escapes during dashboard builds.
  2236. assumeTTY = 0;
  2237. }
  2238. if(enabled)
  2239. {
  2240. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2241. message, newline? "\n" : "");
  2242. }
  2243. else
  2244. {
  2245. // Color is disabled. Print without color.
  2246. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2247. }
  2248. }
  2249. #endif
  2250. //----------------------------------------------------------------------------
  2251. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2252. std::string& soname)
  2253. {
  2254. // For ELF shared libraries use a real parser to get the correct
  2255. // soname.
  2256. #if defined(CMAKE_USE_ELF_PARSER)
  2257. cmELF elf(fullPath.c_str());
  2258. if(elf)
  2259. {
  2260. return elf.GetSOName(soname);
  2261. }
  2262. #endif
  2263. // If the file is not a symlink we have no guess for its soname.
  2264. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2265. {
  2266. return false;
  2267. }
  2268. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2269. {
  2270. return false;
  2271. }
  2272. // If the symlink has a path component we have no guess for the soname.
  2273. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2274. {
  2275. return false;
  2276. }
  2277. // If the symlink points at an extended version of the same name
  2278. // assume it is the soname.
  2279. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2280. if(soname.length() > name.length() &&
  2281. soname.substr(0, name.length()) == name)
  2282. {
  2283. return true;
  2284. }
  2285. return false;
  2286. }
  2287. //----------------------------------------------------------------------------
  2288. #if defined(CMAKE_USE_ELF_PARSER)
  2289. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2290. std::string const& want)
  2291. {
  2292. // Search for the desired rpath.
  2293. std::string::size_type pos = have.find(want);
  2294. // If the path is not present we are done.
  2295. if(pos == std::string::npos)
  2296. {
  2297. return pos;
  2298. }
  2299. // Build a regex to match a properly separated path instance.
  2300. std::string regex_str = "(^|:)(";
  2301. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2302. {
  2303. int ch = *i;
  2304. if(!(('a' <= ch && ch <= 'z') ||
  2305. ('A' <= ch && ch <= 'Z') ||
  2306. ('0' <= ch && ch <= '9')))
  2307. {
  2308. // Escape the non-alphanumeric character.
  2309. regex_str += "\\";
  2310. }
  2311. // Store the character.
  2312. regex_str.append(1, static_cast<char>(ch));
  2313. }
  2314. regex_str += ")(:|$)";
  2315. // Look for the separated path.
  2316. cmsys::RegularExpression regex(regex_str.c_str());
  2317. if(regex.find(have))
  2318. {
  2319. // Return the position of the path portion.
  2320. return regex.start(2);
  2321. }
  2322. else
  2323. {
  2324. // The desired rpath was not found.
  2325. return std::string::npos;
  2326. }
  2327. }
  2328. #endif
  2329. #if defined(CMAKE_USE_ELF_PARSER)
  2330. struct cmSystemToolsRPathInfo
  2331. {
  2332. unsigned long Position;
  2333. unsigned long Size;
  2334. std::string Name;
  2335. std::string Value;
  2336. };
  2337. #endif
  2338. //----------------------------------------------------------------------------
  2339. bool cmSystemTools::ChangeRPath(std::string const& file,
  2340. std::string const& oldRPath,
  2341. std::string const& newRPath,
  2342. std::string* emsg,
  2343. bool* changed)
  2344. {
  2345. #if defined(CMAKE_USE_ELF_PARSER)
  2346. if(changed)
  2347. {
  2348. *changed = false;
  2349. }
  2350. int rp_count = 0;
  2351. cmSystemToolsRPathInfo rp[2];
  2352. {
  2353. // Parse the ELF binary.
  2354. cmELF elf(file.c_str());
  2355. // Get the RPATH and RUNPATH entries from it.
  2356. int se_count = 0;
  2357. cmELF::StringEntry const* se[2] = {0, 0};
  2358. const char* se_name[2] = {0, 0};
  2359. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2360. {
  2361. se[se_count] = se_rpath;
  2362. se_name[se_count] = "RPATH";
  2363. ++se_count;
  2364. }
  2365. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2366. {
  2367. se[se_count] = se_runpath;
  2368. se_name[se_count] = "RUNPATH";
  2369. ++se_count;
  2370. }
  2371. if(se_count == 0)
  2372. {
  2373. if(newRPath.empty())
  2374. {
  2375. // The new rpath is empty and there is no rpath anyway so it is
  2376. // okay.
  2377. return true;
  2378. }
  2379. else
  2380. {
  2381. if(emsg)
  2382. {
  2383. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2384. *emsg += elf.GetErrorMessage();
  2385. }
  2386. return false;
  2387. }
  2388. }
  2389. for(int i=0; i < se_count; ++i)
  2390. {
  2391. // If both RPATH and RUNPATH refer to the same string literal it
  2392. // needs to be changed only once.
  2393. if(rp_count && rp[0].Position == se[i]->Position)
  2394. {
  2395. continue;
  2396. }
  2397. // Make sure the current rpath contains the old rpath.
  2398. std::string::size_type pos =
  2399. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2400. if(pos == std::string::npos)
  2401. {
  2402. // If it contains the new rpath instead then it is okay.
  2403. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2404. {
  2405. continue;
  2406. }
  2407. if(emsg)
  2408. {
  2409. cmOStringStream e;
  2410. e << "The current " << se_name[i] << " is:\n"
  2411. << " " << se[i]->Value << "\n"
  2412. << "which does not contain:\n"
  2413. << " " << oldRPath << "\n"
  2414. << "as was expected.";
  2415. *emsg = e.str();
  2416. }
  2417. return false;
  2418. }
  2419. // Store information about the entry in the file.
  2420. rp[rp_count].Position = se[i]->Position;
  2421. rp[rp_count].Size = se[i]->Size;
  2422. rp[rp_count].Name = se_name[i];
  2423. // Construct the new value which preserves the part of the path
  2424. // not being changed.
  2425. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2426. rp[rp_count].Value += newRPath;
  2427. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2428. oldRPath.npos);
  2429. // Make sure there is enough room to store the new rpath and at
  2430. // least one null terminator.
  2431. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2432. {
  2433. if(emsg)
  2434. {
  2435. *emsg = "The replacement path is too long for the ";
  2436. *emsg += se_name[i];
  2437. *emsg += " entry.";
  2438. }
  2439. return false;
  2440. }
  2441. // This entry is ready for update.
  2442. ++rp_count;
  2443. }
  2444. }
  2445. // If no runtime path needs to be changed, we are done.
  2446. if(rp_count == 0)
  2447. {
  2448. return true;
  2449. }
  2450. {
  2451. // Open the file for update.
  2452. std::ofstream f(file.c_str(),
  2453. std::ios::in | std::ios::out | std::ios::binary);
  2454. if(!f)
  2455. {
  2456. if(emsg)
  2457. {
  2458. *emsg = "Error opening file for update.";
  2459. }
  2460. return false;
  2461. }
  2462. // Store the new RPATH and RUNPATH strings.
  2463. for(int i=0; i < rp_count; ++i)
  2464. {
  2465. // Seek to the RPATH position.
  2466. if(!f.seekp(rp[i].Position))
  2467. {
  2468. if(emsg)
  2469. {
  2470. *emsg = "Error seeking to ";
  2471. *emsg += rp[i].Name;
  2472. *emsg += " position.";
  2473. }
  2474. return false;
  2475. }
  2476. // Write the new rpath. Follow it with enough null terminators to
  2477. // fill the string table entry.
  2478. f << rp[i].Value;
  2479. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2480. {
  2481. f << '\0';
  2482. }
  2483. // Make sure it wrote correctly.
  2484. if(!f)
  2485. {
  2486. if(emsg)
  2487. {
  2488. *emsg = "Error writing the new ";
  2489. *emsg += rp[i].Name;
  2490. *emsg += " string to the file.";
  2491. }
  2492. return false;
  2493. }
  2494. }
  2495. }
  2496. // Everything was updated successfully.
  2497. if(changed)
  2498. {
  2499. *changed = true;
  2500. }
  2501. return true;
  2502. #else
  2503. (void)file;
  2504. (void)oldRPath;
  2505. (void)newRPath;
  2506. (void)emsg;
  2507. (void)changed;
  2508. return false;
  2509. #endif
  2510. }
  2511. //----------------------------------------------------------------------------
  2512. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2513. bool* removed)
  2514. {
  2515. #if defined(CMAKE_USE_ELF_PARSER)
  2516. if(removed)
  2517. {
  2518. *removed = false;
  2519. }
  2520. int zeroCount = 0;
  2521. unsigned long zeroPosition[2] = {0,0};
  2522. unsigned long zeroSize[2] = {0,0};
  2523. unsigned long bytesBegin = 0;
  2524. std::vector<char> bytes;
  2525. {
  2526. // Parse the ELF binary.
  2527. cmELF elf(file.c_str());
  2528. // Get the RPATH and RUNPATH entries from it and sort them by index
  2529. // in the dynamic section header.
  2530. int se_count = 0;
  2531. cmELF::StringEntry const* se[2] = {0, 0};
  2532. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2533. {
  2534. se[se_count++] = se_rpath;
  2535. }
  2536. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2537. {
  2538. se[se_count++] = se_runpath;
  2539. }
  2540. if(se_count == 0)
  2541. {
  2542. // There is no RPATH or RUNPATH anyway.
  2543. return true;
  2544. }
  2545. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2546. {
  2547. cmsys_stl::swap(se[0], se[1]);
  2548. }
  2549. // Get the size of the dynamic section header.
  2550. unsigned int count = elf.GetDynamicEntryCount();
  2551. if(count == 0)
  2552. {
  2553. // This should happen only for invalid ELF files where a DT_NULL
  2554. // appears before the end of the table.
  2555. if(emsg)
  2556. {
  2557. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2558. }
  2559. return false;
  2560. }
  2561. // Save information about the string entries to be zeroed.
  2562. zeroCount = se_count;
  2563. for(int i=0; i < se_count; ++i)
  2564. {
  2565. zeroPosition[i] = se[i]->Position;
  2566. zeroSize[i] = se[i]->Size;
  2567. }
  2568. // Get the range of file positions corresponding to each entry and
  2569. // the rest of the table after them.
  2570. unsigned long entryBegin[3] = {0,0,0};
  2571. unsigned long entryEnd[2] = {0,0};
  2572. for(int i=0; i < se_count; ++i)
  2573. {
  2574. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2575. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2576. }
  2577. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2578. // The data are to be written over the old table entries starting at
  2579. // the first one being removed.
  2580. bytesBegin = entryBegin[0];
  2581. unsigned long bytesEnd = entryBegin[se_count];
  2582. // Allocate a buffer to hold the part of the file to be written.
  2583. // Initialize it with zeros.
  2584. bytes.resize(bytesEnd - bytesBegin, 0);
  2585. // Read the part of the DYNAMIC section header that will move.
  2586. // The remainder of the buffer will be left with zeros which
  2587. // represent a DT_NULL entry.
  2588. char* data = &bytes[0];
  2589. for(int i=0; i < se_count; ++i)
  2590. {
  2591. // Read data between the entries being removed.
  2592. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2593. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2594. {
  2595. if(emsg)
  2596. {
  2597. *emsg = "Failed to read DYNAMIC section header.";
  2598. }
  2599. return false;
  2600. }
  2601. data += sz;
  2602. }
  2603. }
  2604. // Open the file for update.
  2605. std::ofstream f(file.c_str(),
  2606. std::ios::in | std::ios::out | std::ios::binary);
  2607. if(!f)
  2608. {
  2609. if(emsg)
  2610. {
  2611. *emsg = "Error opening file for update.";
  2612. }
  2613. return false;
  2614. }
  2615. // Write the new DYNAMIC table header.
  2616. if(!f.seekp(bytesBegin))
  2617. {
  2618. if(emsg)
  2619. {
  2620. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2621. }
  2622. return false;
  2623. }
  2624. if(!f.write(&bytes[0], bytes.size()))
  2625. {
  2626. if(emsg)
  2627. {
  2628. *emsg = "Error replacing DYNAMIC table header.";
  2629. }
  2630. return false;
  2631. }
  2632. // Fill the RPATH and RUNPATH strings with zero bytes.
  2633. for(int i=0; i < zeroCount; ++i)
  2634. {
  2635. if(!f.seekp(zeroPosition[i]))
  2636. {
  2637. if(emsg)
  2638. {
  2639. *emsg = "Error seeking to RPATH position.";
  2640. }
  2641. return false;
  2642. }
  2643. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2644. {
  2645. f << '\0';
  2646. }
  2647. if(!f)
  2648. {
  2649. if(emsg)
  2650. {
  2651. *emsg = "Error writing the empty rpath string to the file.";
  2652. }
  2653. return false;
  2654. }
  2655. }
  2656. // Everything was updated successfully.
  2657. if(removed)
  2658. {
  2659. *removed = true;
  2660. }
  2661. return true;
  2662. #else
  2663. (void)file;
  2664. (void)emsg;
  2665. (void)removed;
  2666. return false;
  2667. #endif
  2668. }
  2669. //----------------------------------------------------------------------------
  2670. bool cmSystemTools::CheckRPath(std::string const& file,
  2671. std::string const& newRPath)
  2672. {
  2673. #if defined(CMAKE_USE_ELF_PARSER)
  2674. // Parse the ELF binary.
  2675. cmELF elf(file.c_str());
  2676. // Get the RPATH or RUNPATH entry from it.
  2677. cmELF::StringEntry const* se = elf.GetRPath();
  2678. if(!se)
  2679. {
  2680. se = elf.GetRunPath();
  2681. }
  2682. // Make sure the current rpath contains the new rpath.
  2683. if(newRPath.empty())
  2684. {
  2685. if(!se)
  2686. {
  2687. return true;
  2688. }
  2689. }
  2690. else
  2691. {
  2692. if(se &&
  2693. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2694. {
  2695. return true;
  2696. }
  2697. }
  2698. return false;
  2699. #else
  2700. (void)file;
  2701. (void)newRPath;
  2702. return false;
  2703. #endif
  2704. }