cmSystemTools.cxx 76 KB

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