cmSystemTools.cxx 76 KB

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