cmSystemTools.cxx 81 KB

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