cmSystemTools.cxx 76 KB

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