cmSystemTools.cxx 77 KB

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