cmSystemTools.cxx 76 KB

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