cmSystemTools.cxx 79 KB

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