cmSystemTools.cxx 76 KB

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