cmSystemTools.cxx 76 KB

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