cmSystemTools.cxx 79 KB

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