cmSystemTools.cxx 81 KB

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