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