cmSystemTools.cxx 76 KB

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