cmSystemTools.cxx 79 KB

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