cmSystemTools.cxx 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070
  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. # ifndef __LA_INT64_T
  30. # define __LA_INT64_T la_int64_t
  31. # endif
  32. #endif
  33. #include <cmsys/FStream.hxx>
  34. #include <cmsys/Terminal.h>
  35. #if defined(_WIN32)
  36. # include <windows.h>
  37. # include <wincrypt.h>
  38. #else
  39. # include <sys/time.h>
  40. # include <sys/types.h>
  41. # include <unistd.h>
  42. # include <utime.h>
  43. # include <sys/wait.h>
  44. #endif
  45. #if defined(__APPLE__)
  46. # include <mach-o/dyld.h>
  47. #endif
  48. #include <sys/stat.h>
  49. #if defined(_WIN32) && \
  50. (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
  51. # include <io.h>
  52. #endif
  53. #if defined(CMAKE_BUILD_WITH_CMAKE)
  54. # include <fcntl.h>
  55. # include "cmCryptoHash.h"
  56. #endif
  57. #if defined(CMAKE_USE_ELF_PARSER)
  58. # include "cmELF.h"
  59. #endif
  60. #if defined(CMAKE_USE_MACH_PARSER)
  61. # include "cmMachO.h"
  62. #endif
  63. static bool cm_isspace(char c)
  64. {
  65. return ((c & 0x80) == 0) && isspace(c);
  66. }
  67. class cmSystemToolsFileTime
  68. {
  69. public:
  70. #if defined(_WIN32) && !defined(__CYGWIN__)
  71. FILETIME timeCreation;
  72. FILETIME timeLastAccess;
  73. FILETIME timeLastWrite;
  74. #else
  75. struct utimbuf timeBuf;
  76. #endif
  77. };
  78. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  79. // For GetEnvironmentVariables
  80. # if defined(_WIN32)
  81. extern __declspec( dllimport ) char** environ;
  82. # else
  83. extern char** environ;
  84. # endif
  85. #endif
  86. #if defined(CMAKE_BUILD_WITH_CMAKE)
  87. static std::string
  88. cm_archive_entry_pathname(struct archive_entry *entry)
  89. {
  90. #if cmsys_STL_HAS_WSTRING
  91. return cmsys::Encoding::ToNarrow(
  92. archive_entry_pathname_w(entry));
  93. #else
  94. return archive_entry_pathname(entry);
  95. #endif
  96. }
  97. static int cm_archive_read_open_file(struct archive* a,
  98. const char* file,
  99. int block_size)
  100. {
  101. #if cmsys_STL_HAS_WSTRING
  102. std::wstring wfile = cmsys::Encoding::ToWide(file);
  103. return archive_read_open_filename_w(a, wfile.c_str(), block_size);
  104. #else
  105. return archive_read_open_filename(a, file, block_size);
  106. #endif
  107. }
  108. #endif
  109. #ifdef _WIN32
  110. class cmSystemToolsWindowsHandle
  111. {
  112. public:
  113. cmSystemToolsWindowsHandle(HANDLE h): handle_(h) {}
  114. ~cmSystemToolsWindowsHandle()
  115. {
  116. if(this->handle_ != INVALID_HANDLE_VALUE)
  117. {
  118. CloseHandle(this->handle_);
  119. }
  120. }
  121. operator bool() const { return this->handle_ != INVALID_HANDLE_VALUE; }
  122. bool operator !() const { return this->handle_ == INVALID_HANDLE_VALUE; }
  123. operator HANDLE() const { return this->handle_; }
  124. private:
  125. HANDLE handle_;
  126. };
  127. #elif defined(__APPLE__)
  128. #include <crt_externs.h>
  129. #define environ (*_NSGetEnviron())
  130. #endif
  131. bool cmSystemTools::s_RunCommandHideConsole = false;
  132. bool cmSystemTools::s_DisableRunCommandOutput = false;
  133. bool cmSystemTools::s_ErrorOccured = false;
  134. bool cmSystemTools::s_FatalErrorOccured = false;
  135. bool cmSystemTools::s_DisableMessages = false;
  136. bool cmSystemTools::s_ForceUnixPaths = false;
  137. cmSystemTools::MessageCallback cmSystemTools::s_MessageCallback;
  138. cmSystemTools::OutputCallback cmSystemTools::s_StdoutCallback;
  139. cmSystemTools::OutputCallback cmSystemTools::s_StderrCallback;
  140. cmSystemTools::InterruptCallback cmSystemTools::s_InterruptCallback;
  141. void* cmSystemTools::s_MessageCallbackClientData;
  142. void* cmSystemTools::s_StdoutCallbackClientData;
  143. void* cmSystemTools::s_StderrCallbackClientData;
  144. void* cmSystemTools::s_InterruptCallbackClientData;
  145. // replace replace with with as many times as it shows up in source.
  146. // write the result into source.
  147. #if defined(_WIN32) && !defined(__CYGWIN__)
  148. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  149. {
  150. // Regular expression to match anything inside [...] that begins in HKEY.
  151. // Note that there is a special rule for regular expressions to match a
  152. // close square-bracket inside a list delimited by square brackets.
  153. // The "[^]]" part of this expression will match any character except
  154. // a close square-bracket. The ']' character must be the first in the
  155. // list of characters inside the [^...] block of the expression.
  156. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  157. // check for black line or comment
  158. while (regEntry.find(source))
  159. {
  160. // the arguments are the second match
  161. std::string key = regEntry.match(1);
  162. std::string val;
  163. if (ReadRegistryValue(key.c_str(), val, view))
  164. {
  165. std::string reg = "[";
  166. reg += key + "]";
  167. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  168. }
  169. else
  170. {
  171. std::string reg = "[";
  172. reg += key + "]";
  173. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  174. }
  175. }
  176. }
  177. #else
  178. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64)
  179. {
  180. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  181. while (regEntry.find(source))
  182. {
  183. // the arguments are the second match
  184. std::string key = regEntry.match(1);
  185. std::string val;
  186. std::string reg = "[";
  187. reg += key + "]";
  188. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  189. }
  190. }
  191. #endif
  192. std::string cmSystemTools::EscapeQuotes(const std::string& str)
  193. {
  194. std::string result;
  195. result.reserve(str.size());
  196. for(const char* ch = str.c_str(); *ch != '\0'; ++ch)
  197. {
  198. if(*ch == '"')
  199. {
  200. result += '\\';
  201. }
  202. result += *ch;
  203. }
  204. return result;
  205. }
  206. std::string cmSystemTools::HelpFileName(std::string name)
  207. {
  208. cmSystemTools::ReplaceString(name, "<", "");
  209. cmSystemTools::ReplaceString(name, ">", "");
  210. return name;
  211. }
  212. std::string cmSystemTools::TrimWhitespace(const std::string& s)
  213. {
  214. std::string::const_iterator start = s.begin();
  215. while (start != s.end() && cm_isspace(*start))
  216. ++start;
  217. if (start == s.end())
  218. return "";
  219. std::string::const_iterator stop = s.end()-1;
  220. while (cm_isspace(*stop))
  221. --stop;
  222. return std::string(start, stop+1);
  223. }
  224. void cmSystemTools::Error(const char* m1, const char* m2,
  225. const char* m3, const char* m4)
  226. {
  227. std::string message = "CMake Error: ";
  228. if(m1)
  229. {
  230. message += m1;
  231. }
  232. if(m2)
  233. {
  234. message += m2;
  235. }
  236. if(m3)
  237. {
  238. message += m3;
  239. }
  240. if(m4)
  241. {
  242. message += m4;
  243. }
  244. cmSystemTools::s_ErrorOccured = true;
  245. cmSystemTools::Message(message.c_str(),"Error");
  246. }
  247. void cmSystemTools::SetInterruptCallback(InterruptCallback f, void* clientData)
  248. {
  249. s_InterruptCallback = f;
  250. s_InterruptCallbackClientData = clientData;
  251. }
  252. bool cmSystemTools::GetInterruptFlag()
  253. {
  254. if(s_InterruptCallback)
  255. {
  256. return (*s_InterruptCallback)(s_InterruptCallbackClientData);
  257. }
  258. return false;
  259. }
  260. void cmSystemTools::SetMessageCallback(MessageCallback f, void* clientData)
  261. {
  262. s_MessageCallback = f;
  263. s_MessageCallbackClientData = clientData;
  264. }
  265. void cmSystemTools::SetStdoutCallback(OutputCallback f, void* clientData)
  266. {
  267. s_StdoutCallback = f;
  268. s_StdoutCallbackClientData = clientData;
  269. }
  270. void cmSystemTools::SetStderrCallback(OutputCallback f, void* clientData)
  271. {
  272. s_StderrCallback = f;
  273. s_StderrCallbackClientData = clientData;
  274. }
  275. void cmSystemTools::Stdout(const char* s)
  276. {
  277. cmSystemTools::Stdout(s, strlen(s));
  278. }
  279. void cmSystemTools::Stderr(const char* s)
  280. {
  281. cmSystemTools::Stderr(s, strlen(s));
  282. }
  283. void cmSystemTools::Stderr(const char* s, size_t length)
  284. {
  285. if(s_StderrCallback)
  286. {
  287. (*s_StderrCallback)(s, length, s_StderrCallbackClientData);
  288. }
  289. else
  290. {
  291. std::cerr.write(s, length);
  292. std::cerr.flush();
  293. }
  294. }
  295. void cmSystemTools::Stdout(const char* s, size_t length)
  296. {
  297. if(s_StdoutCallback)
  298. {
  299. (*s_StdoutCallback)(s, length, s_StdoutCallbackClientData);
  300. }
  301. else
  302. {
  303. std::cout.write(s, length);
  304. std::cout.flush();
  305. }
  306. }
  307. void cmSystemTools::Message(const char* m1, const char *title)
  308. {
  309. if(s_DisableMessages)
  310. {
  311. return;
  312. }
  313. if(s_MessageCallback)
  314. {
  315. (*s_MessageCallback)(m1, title, s_DisableMessages,
  316. s_MessageCallbackClientData);
  317. return;
  318. }
  319. else
  320. {
  321. std::cerr << m1 << std::endl << std::flush;
  322. }
  323. }
  324. void cmSystemTools::ReportLastSystemError(const char* msg)
  325. {
  326. std::string m = msg;
  327. m += ": System Error: ";
  328. m += Superclass::GetLastSystemError();
  329. cmSystemTools::Error(m.c_str());
  330. }
  331. bool cmSystemTools::IsInternallyOn(const char* val)
  332. {
  333. if (!val)
  334. {
  335. return false;
  336. }
  337. std::basic_string<char> v = val;
  338. if (v.size() > 4)
  339. {
  340. return false;
  341. }
  342. for(std::basic_string<char>::iterator c = v.begin();
  343. c != v.end(); c++)
  344. {
  345. *c = static_cast<char>(toupper(*c));
  346. }
  347. return v == "I_ON";
  348. }
  349. bool cmSystemTools::IsOn(const char* val)
  350. {
  351. if (!val)
  352. {
  353. return false;
  354. }
  355. size_t len = strlen(val);
  356. if (len > 4)
  357. {
  358. return false;
  359. }
  360. std::basic_string<char> v(val, len);
  361. static std::set<std::string> onValues;
  362. if(onValues.empty())
  363. {
  364. onValues.insert("ON");
  365. onValues.insert("1");
  366. onValues.insert("YES");
  367. onValues.insert("TRUE");
  368. onValues.insert("Y");
  369. }
  370. for(std::basic_string<char>::iterator c = v.begin();
  371. c != v.end(); c++)
  372. {
  373. *c = static_cast<char>(toupper(*c));
  374. }
  375. return (onValues.count(v) > 0);
  376. }
  377. bool cmSystemTools::IsNOTFOUND(const char* val)
  378. {
  379. if(strcmp(val, "NOTFOUND") == 0)
  380. {
  381. return true;
  382. }
  383. return cmHasLiteralSuffix(val, "-NOTFOUND");
  384. }
  385. bool cmSystemTools::IsOff(const char* val)
  386. {
  387. if (!val || !*val)
  388. {
  389. return true;
  390. }
  391. size_t len = strlen(val);
  392. // Try and avoid toupper() for large strings.
  393. if (len > 6)
  394. {
  395. return cmSystemTools::IsNOTFOUND(val);
  396. }
  397. static std::set<std::string> offValues;
  398. if(offValues.empty())
  399. {
  400. offValues.insert("OFF");
  401. offValues.insert("0");
  402. offValues.insert("NO");
  403. offValues.insert("FALSE");
  404. offValues.insert("N");
  405. offValues.insert("IGNORE");
  406. }
  407. // Try and avoid toupper().
  408. std::basic_string<char> v(val, len);
  409. for(std::basic_string<char>::iterator c = v.begin();
  410. c != v.end(); c++)
  411. {
  412. *c = static_cast<char>(toupper(*c));
  413. }
  414. return (offValues.count(v) > 0);
  415. }
  416. //----------------------------------------------------------------------------
  417. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  418. std::vector<std::string>& args)
  419. {
  420. // See the MSDN document "Parsing C Command-Line Arguments" at
  421. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  422. // of parsing the windows command line.
  423. bool in_argument = false;
  424. bool in_quotes = false;
  425. int backslashes = 0;
  426. std::string arg;
  427. for(const char* c = command;*c; ++c)
  428. {
  429. if(*c == '\\')
  430. {
  431. ++backslashes;
  432. in_argument = true;
  433. }
  434. else if(*c == '"')
  435. {
  436. int backslash_pairs = backslashes >> 1;
  437. int backslash_escaped = backslashes & 1;
  438. arg.append(backslash_pairs, '\\');
  439. backslashes = 0;
  440. if(backslash_escaped)
  441. {
  442. /* An odd number of backslashes precede this quote.
  443. It is escaped. */
  444. arg.append(1, '"');
  445. }
  446. else
  447. {
  448. /* An even number of backslashes precede this quote.
  449. It is not escaped. */
  450. in_quotes = !in_quotes;
  451. }
  452. in_argument = true;
  453. }
  454. else
  455. {
  456. arg.append(backslashes, '\\');
  457. backslashes = 0;
  458. if (cm_isspace(*c))
  459. {
  460. if(in_quotes)
  461. {
  462. arg.append(1, *c);
  463. }
  464. else if(in_argument)
  465. {
  466. args.push_back(arg);
  467. arg = "";
  468. in_argument = false;
  469. }
  470. }
  471. else
  472. {
  473. in_argument = true;
  474. arg.append(1, *c);
  475. }
  476. }
  477. }
  478. arg.append(backslashes, '\\');
  479. if(in_argument)
  480. {
  481. args.push_back(arg);
  482. }
  483. }
  484. //----------------------------------------------------------------------------
  485. class cmSystemToolsArgV
  486. {
  487. char** ArgV;
  488. public:
  489. cmSystemToolsArgV(char** argv): ArgV(argv) {}
  490. ~cmSystemToolsArgV()
  491. {
  492. for(char** arg = this->ArgV; arg && *arg; ++arg)
  493. {
  494. free(*arg);
  495. }
  496. free(this->ArgV);
  497. }
  498. void Store(std::vector<std::string>& args) const
  499. {
  500. for(char** arg = this->ArgV; arg && *arg; ++arg)
  501. {
  502. args.push_back(*arg);
  503. }
  504. }
  505. };
  506. //----------------------------------------------------------------------------
  507. void cmSystemTools::ParseUnixCommandLine(const char* command,
  508. std::vector<std::string>& args)
  509. {
  510. // Invoke the underlying parser.
  511. cmSystemToolsArgV argv = cmsysSystem_Parse_CommandForUnix(command, 0);
  512. argv.Store(args);
  513. }
  514. std::vector<std::string> cmSystemTools::ParseArguments(const char* command)
  515. {
  516. std::vector<std::string> args;
  517. std::string arg;
  518. bool win_path = false;
  519. if ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  520. (command[0] == '\"' && command[1] != '/' && command[2] == ':'
  521. && command[3] == '\\') ||
  522. (command[0] == '\'' && command[1] != '/' && command[2] == ':'
  523. && command[3] == '\\') ||
  524. (command[0] == '\\' && command[1] == '\\'))
  525. {
  526. win_path = true;
  527. }
  528. // Split the command into an argv array.
  529. for(const char* c = command; *c;)
  530. {
  531. // Skip over whitespace.
  532. while(*c == ' ' || *c == '\t')
  533. {
  534. ++c;
  535. }
  536. arg = "";
  537. if(*c == '"')
  538. {
  539. // Parse a quoted argument.
  540. ++c;
  541. while(*c && *c != '"')
  542. {
  543. arg.append(1, *c);
  544. ++c;
  545. }
  546. if(*c)
  547. {
  548. ++c;
  549. }
  550. args.push_back(arg);
  551. }
  552. else if(*c == '\'')
  553. {
  554. // Parse a quoted argument.
  555. ++c;
  556. while(*c && *c != '\'')
  557. {
  558. arg.append(1, *c);
  559. ++c;
  560. }
  561. if(*c)
  562. {
  563. ++c;
  564. }
  565. args.push_back(arg);
  566. }
  567. else if(*c)
  568. {
  569. // Parse an unquoted argument.
  570. while(*c && *c != ' ' && *c != '\t')
  571. {
  572. if(*c == '\\' && !win_path)
  573. {
  574. ++c;
  575. if(*c)
  576. {
  577. arg.append(1, *c);
  578. ++c;
  579. }
  580. }
  581. else
  582. {
  583. arg.append(1, *c);
  584. ++c;
  585. }
  586. }
  587. args.push_back(arg);
  588. }
  589. }
  590. return args;
  591. }
  592. bool cmSystemTools::RunSingleCommand(std::vector<std::string>const& command,
  593. std::string* captureStdOut,
  594. std::string* captureStdErr,
  595. int* retVal , const char* dir ,
  596. OutputOption outputflag ,
  597. double timeout )
  598. {
  599. std::vector<const char*> argv;
  600. for(std::vector<std::string>::const_iterator a = command.begin();
  601. a != command.end(); ++a)
  602. {
  603. argv.push_back(a->c_str());
  604. }
  605. argv.push_back(0);
  606. if ( captureStdOut )
  607. {
  608. *captureStdOut = "";
  609. }
  610. if (captureStdErr && captureStdErr != captureStdOut)
  611. {
  612. *captureStdErr = "";
  613. }
  614. cmsysProcess* cp = cmsysProcess_New();
  615. cmsysProcess_SetCommand(cp, &*argv.begin());
  616. cmsysProcess_SetWorkingDirectory(cp, dir);
  617. if(cmSystemTools::GetRunCommandHideConsole())
  618. {
  619. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  620. }
  621. if (outputflag == OUTPUT_PASSTHROUGH)
  622. {
  623. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  624. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  625. }
  626. cmsysProcess_SetTimeout(cp, timeout);
  627. cmsysProcess_Execute(cp);
  628. std::vector<char> tempStdOut;
  629. std::vector<char> tempStdErr;
  630. char* data;
  631. int length;
  632. int pipe;
  633. if(outputflag != OUTPUT_PASSTHROUGH &&
  634. (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE))
  635. {
  636. while((pipe = cmsysProcess_WaitForData(cp, &data, &length, 0)) > 0)
  637. {
  638. if(captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)
  639. {
  640. // Translate NULL characters in the output into valid text.
  641. // Visual Studio 7 puts these characters in the output of its
  642. // build process.
  643. for(int i=0; i < length; ++i)
  644. {
  645. if(data[i] == '\0')
  646. {
  647. data[i] = ' ';
  648. }
  649. }
  650. }
  651. if(pipe == cmsysProcess_Pipe_STDOUT ||
  652. (pipe == cmsysProcess_Pipe_STDERR &&
  653. captureStdOut == captureStdErr))
  654. {
  655. if (captureStdOut)
  656. {
  657. tempStdOut.insert(tempStdOut.end(), data, data+length);
  658. }
  659. }
  660. else if(pipe == cmsysProcess_Pipe_STDERR)
  661. {
  662. if (captureStdErr)
  663. {
  664. tempStdErr.insert(tempStdErr.end(), data, data+length);
  665. }
  666. }
  667. if(outputflag != OUTPUT_NONE)
  668. {
  669. if(outputflag == OUTPUT_MERGE)
  670. {
  671. cmSystemTools::Stdout(data, length);
  672. }
  673. else
  674. {
  675. if(pipe == cmsysProcess_Pipe_STDERR)
  676. {
  677. cmSystemTools::Stderr(data, length);
  678. }
  679. else if(pipe == cmsysProcess_Pipe_STDOUT)
  680. {
  681. cmSystemTools::Stdout(data, length);
  682. }
  683. }
  684. }
  685. }
  686. }
  687. cmsysProcess_WaitForExit(cp, 0);
  688. if ( captureStdOut && tempStdOut.begin() != tempStdOut.end())
  689. {
  690. captureStdOut->append(&*tempStdOut.begin(), tempStdOut.size());
  691. }
  692. if ( captureStdErr && captureStdErr != captureStdOut &&
  693. tempStdErr.begin() != tempStdErr.end())
  694. {
  695. captureStdErr->append(&*tempStdErr.begin(), tempStdErr.size());
  696. }
  697. bool result = true;
  698. if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
  699. {
  700. if ( retVal )
  701. {
  702. *retVal = cmsysProcess_GetExitValue(cp);
  703. }
  704. else
  705. {
  706. if ( cmsysProcess_GetExitValue(cp) != 0 )
  707. {
  708. result = false;
  709. }
  710. }
  711. }
  712. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
  713. {
  714. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  715. if ( outputflag != OUTPUT_NONE )
  716. {
  717. std::cerr << exception_str << std::endl;
  718. }
  719. if ( captureStdErr )
  720. {
  721. captureStdErr->append(exception_str, strlen(exception_str));
  722. }
  723. result = false;
  724. }
  725. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  726. {
  727. const char* error_str = cmsysProcess_GetErrorString(cp);
  728. if ( outputflag != OUTPUT_NONE )
  729. {
  730. std::cerr << error_str << std::endl;
  731. }
  732. if ( captureStdErr )
  733. {
  734. captureStdErr->append(error_str, strlen(error_str));
  735. }
  736. result = false;
  737. }
  738. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  739. {
  740. const char* error_str = "Process terminated due to timeout\n";
  741. if ( outputflag != OUTPUT_NONE )
  742. {
  743. std::cerr << error_str << std::endl;
  744. }
  745. if ( captureStdErr )
  746. {
  747. captureStdErr->append(error_str, strlen(error_str));
  748. }
  749. result = false;
  750. }
  751. cmsysProcess_Delete(cp);
  752. return result;
  753. }
  754. bool cmSystemTools::RunSingleCommand(
  755. const char* command,
  756. std::string* captureStdOut,
  757. std::string* captureStdErr,
  758. int *retVal,
  759. const char* dir,
  760. OutputOption outputflag,
  761. double timeout)
  762. {
  763. if(s_DisableRunCommandOutput)
  764. {
  765. outputflag = OUTPUT_NONE;
  766. }
  767. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  768. if(args.size() < 1)
  769. {
  770. return false;
  771. }
  772. return cmSystemTools::RunSingleCommand(args, captureStdOut, captureStdErr,
  773. retVal, dir, outputflag, timeout);
  774. }
  775. std::string
  776. cmSystemTools::PrintSingleCommand(std::vector<std::string> const& command)
  777. {
  778. if (command.empty())
  779. {
  780. return std::string();
  781. }
  782. return cmWrap('"', command, '"', " ");
  783. }
  784. bool cmSystemTools::DoesFileExistWithExtensions(
  785. const char* name,
  786. const std::vector<std::string>& headerExts)
  787. {
  788. std::string hname;
  789. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  790. ext != headerExts.end(); ++ext )
  791. {
  792. hname = name;
  793. hname += ".";
  794. hname += *ext;
  795. if(cmSystemTools::FileExists(hname.c_str()))
  796. {
  797. return true;
  798. }
  799. }
  800. return false;
  801. }
  802. std::string cmSystemTools::FileExistsInParentDirectories(const char* fname,
  803. const char* directory, const char* toplevel)
  804. {
  805. std::string file = fname;
  806. cmSystemTools::ConvertToUnixSlashes(file);
  807. std::string dir = directory;
  808. cmSystemTools::ConvertToUnixSlashes(dir);
  809. std::string prevDir;
  810. while(dir != prevDir)
  811. {
  812. std::string path = dir + "/" + file;
  813. if ( cmSystemTools::FileExists(path.c_str()) )
  814. {
  815. return path;
  816. }
  817. if ( dir.size() < strlen(toplevel) )
  818. {
  819. break;
  820. }
  821. prevDir = dir;
  822. dir = cmSystemTools::GetParentDirectory(dir);
  823. }
  824. return "";
  825. }
  826. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  827. {
  828. return Superclass::CopyFileAlways(source, destination);
  829. }
  830. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  831. const char* destination)
  832. {
  833. return Superclass::CopyFileIfDifferent(source, destination);
  834. }
  835. //----------------------------------------------------------------------------
  836. #ifdef _WIN32
  837. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  838. {
  839. static WindowsFileRetry retry = {0,0};
  840. if(!retry.Count)
  841. {
  842. unsigned int data[2] = {0,0};
  843. HKEY const keys[2] = {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
  844. wchar_t const* const values[2] = {L"FilesystemRetryCount",
  845. L"FilesystemRetryDelay"};
  846. for(int k=0; k < 2; ++k)
  847. {
  848. HKEY hKey;
  849. if(RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config",
  850. 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
  851. {
  852. for(int v=0; v < 2; ++v)
  853. {
  854. DWORD dwData, dwType, dwSize = 4;
  855. if(!data[v] &&
  856. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE *)&dwData,
  857. &dwSize) == ERROR_SUCCESS &&
  858. dwType == REG_DWORD && dwSize == 4)
  859. {
  860. data[v] = static_cast<unsigned int>(dwData);
  861. }
  862. }
  863. RegCloseKey(hKey);
  864. }
  865. }
  866. retry.Count = data[0]? data[0] : 5;
  867. retry.Delay = data[1]? data[1] : 500;
  868. }
  869. return retry;
  870. }
  871. #endif
  872. //----------------------------------------------------------------------------
  873. bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
  874. {
  875. #ifdef _WIN32
  876. # ifndef INVALID_FILE_ATTRIBUTES
  877. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  878. # endif
  879. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  880. fails then remove the read-only attribute from any existing destination.
  881. Try multiple times since we may be racing against another process
  882. creating/opening the destination file just before our MoveFileEx. */
  883. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  884. while(!MoveFileExW(
  885. SystemTools::ConvertToWindowsExtendedPath(oldname).c_str(),
  886. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  887. MOVEFILE_REPLACE_EXISTING) && --retry.Count)
  888. {
  889. DWORD last_error = GetLastError();
  890. // Try again only if failure was due to access/sharing permissions.
  891. if(last_error != ERROR_ACCESS_DENIED &&
  892. last_error != ERROR_SHARING_VIOLATION)
  893. {
  894. return false;
  895. }
  896. DWORD attrs =
  897. GetFileAttributesW(
  898. SystemTools::ConvertToWindowsExtendedPath(newname).c_str());
  899. if((attrs != INVALID_FILE_ATTRIBUTES) &&
  900. (attrs & FILE_ATTRIBUTE_READONLY))
  901. {
  902. // Remove the read-only attribute from the destination file.
  903. SetFileAttributesW(
  904. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  905. attrs & ~FILE_ATTRIBUTE_READONLY);
  906. }
  907. else
  908. {
  909. // The file may be temporarily in use so wait a bit.
  910. cmSystemTools::Delay(retry.Delay);
  911. }
  912. }
  913. return retry.Count > 0;
  914. #else
  915. /* On UNIX we have an OS-provided call to do this atomically. */
  916. return rename(oldname, newname) == 0;
  917. #endif
  918. }
  919. bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
  920. {
  921. #if defined(CMAKE_BUILD_WITH_CMAKE)
  922. cmCryptoHashMD5 md5;
  923. std::string str = md5.HashFile(source);
  924. strncpy(md5out, str.c_str(), 32);
  925. return !str.empty();
  926. #else
  927. (void)source;
  928. (void)md5out;
  929. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  930. return false;
  931. #endif
  932. }
  933. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  934. {
  935. #if defined(CMAKE_BUILD_WITH_CMAKE)
  936. cmCryptoHashMD5 md5;
  937. return md5.HashString(input);
  938. #else
  939. (void)input;
  940. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  941. return "";
  942. #endif
  943. }
  944. //----------------------------------------------------------------------------
  945. std::string cmSystemTools::ComputeCertificateThumbprint(
  946. const std::string& source)
  947. {
  948. std::string thumbprint;
  949. #if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32)
  950. BYTE* certData = NULL;
  951. CRYPT_INTEGER_BLOB cryptBlob;
  952. HCERTSTORE certStore = NULL;
  953. PCCERT_CONTEXT certContext = NULL;
  954. HANDLE certFile =
  955. CreateFileW(cmsys::Encoding::ToWide(source.c_str()).c_str(),
  956. GENERIC_READ,
  957. FILE_SHARE_READ,
  958. NULL,
  959. OPEN_EXISTING,
  960. FILE_ATTRIBUTE_NORMAL,
  961. NULL);
  962. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL)
  963. {
  964. DWORD fileSize = GetFileSize(certFile, NULL);
  965. if (fileSize != INVALID_FILE_SIZE)
  966. {
  967. certData = new BYTE[fileSize];
  968. if (certData != NULL)
  969. {
  970. DWORD dwRead = 0;
  971. if (ReadFile(certFile, certData, fileSize, &dwRead, NULL))
  972. {
  973. cryptBlob.cbData = fileSize;
  974. cryptBlob.pbData = certData;
  975. // Verify that this is a valid cert
  976. if (PFXIsPFXBlob(&cryptBlob))
  977. {
  978. // Open the certificate as a store
  979. certStore = PFXImportCertStore(
  980. &cryptBlob, NULL, CRYPT_EXPORTABLE);
  981. if (certStore != NULL)
  982. {
  983. // There should only be 1 cert.
  984. certContext = CertEnumCertificatesInStore(certStore,
  985. certContext);
  986. if (certContext != NULL)
  987. {
  988. // The hash is 20 bytes
  989. BYTE hashData[20];
  990. DWORD hashLength = 20;
  991. // Buffer to print the hash. Each byte takes 2 chars +
  992. // terminating character
  993. char hashPrint[41];
  994. char *pHashPrint = hashPrint;
  995. // Get the hash property from the certificate
  996. if (CertGetCertificateContextProperty(certContext,
  997. CERT_HASH_PROP_ID, hashData, &hashLength))
  998. {
  999. for (DWORD i = 0; i < hashLength; i++)
  1000. {
  1001. // Convert each byte to hexadecimal
  1002. sprintf(pHashPrint, "%02X", hashData[i]);
  1003. pHashPrint += 2;
  1004. }
  1005. *pHashPrint = '\0';
  1006. thumbprint = hashPrint;
  1007. }
  1008. CertFreeCertificateContext(certContext);
  1009. }
  1010. CertCloseStore(certStore, 0);
  1011. }
  1012. }
  1013. }
  1014. delete[] certData;
  1015. }
  1016. }
  1017. CloseHandle(certFile);
  1018. }
  1019. #else
  1020. (void)source;
  1021. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  1022. "Error");
  1023. #endif
  1024. return thumbprint;
  1025. }
  1026. void cmSystemTools::Glob(const std::string& directory,
  1027. const std::string& regexp,
  1028. std::vector<std::string>& files)
  1029. {
  1030. cmsys::Directory d;
  1031. cmsys::RegularExpression reg(regexp.c_str());
  1032. if (d.Load(directory))
  1033. {
  1034. size_t numf;
  1035. unsigned int i;
  1036. numf = d.GetNumberOfFiles();
  1037. for (i = 0; i < numf; i++)
  1038. {
  1039. std::string fname = d.GetFile(i);
  1040. if (reg.find(fname))
  1041. {
  1042. files.push_back(fname);
  1043. }
  1044. }
  1045. }
  1046. }
  1047. void cmSystemTools::GlobDirs(const std::string& path,
  1048. std::vector<std::string>& files)
  1049. {
  1050. std::string::size_type pos = path.find("/*");
  1051. if(pos == std::string::npos)
  1052. {
  1053. files.push_back(path);
  1054. return;
  1055. }
  1056. std::string startPath = path.substr(0, pos);
  1057. std::string finishPath = path.substr(pos+2);
  1058. cmsys::Directory d;
  1059. if (d.Load(startPath))
  1060. {
  1061. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1062. {
  1063. if((std::string(d.GetFile(i)) != ".")
  1064. && (std::string(d.GetFile(i)) != ".."))
  1065. {
  1066. std::string fname = startPath;
  1067. fname +="/";
  1068. fname += d.GetFile(i);
  1069. if(cmSystemTools::FileIsDirectory(fname))
  1070. {
  1071. fname += finishPath;
  1072. cmSystemTools::GlobDirs(fname, files);
  1073. }
  1074. }
  1075. }
  1076. }
  1077. }
  1078. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1079. std::vector<std::string>& newargs)
  1080. {
  1081. std::vector<std::string>::const_iterator i;
  1082. for(i = arguments.begin();i != arguments.end(); ++i)
  1083. {
  1084. cmSystemTools::ExpandListArgument(*i, newargs);
  1085. }
  1086. }
  1087. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1088. std::vector<std::string>& newargs,
  1089. bool emptyArgs)
  1090. {
  1091. // If argument is empty, it is an empty list.
  1092. if(!emptyArgs && arg.empty())
  1093. {
  1094. return;
  1095. }
  1096. // if there are no ; in the name then just copy the current string
  1097. if(arg.find(';') == std::string::npos)
  1098. {
  1099. newargs.push_back(arg);
  1100. return;
  1101. }
  1102. std::string newArg;
  1103. const char *last = arg.c_str();
  1104. // Break the string at non-escaped semicolons not nested in [].
  1105. int squareNesting = 0;
  1106. for(const char* c = last; *c; ++c)
  1107. {
  1108. switch(*c)
  1109. {
  1110. case '\\':
  1111. {
  1112. // We only want to allow escaping of semicolons. Other
  1113. // escapes should not be processed here.
  1114. const char* next = c + 1;
  1115. if(*next == ';')
  1116. {
  1117. newArg.append(last, c - last);
  1118. // Skip over the escape character
  1119. last = c = next;
  1120. }
  1121. } break;
  1122. case '[':
  1123. {
  1124. ++squareNesting;
  1125. } break;
  1126. case ']':
  1127. {
  1128. --squareNesting;
  1129. } break;
  1130. case ';':
  1131. {
  1132. // Break the string here if we are not nested inside square
  1133. // brackets.
  1134. if(squareNesting == 0)
  1135. {
  1136. newArg.append(last, c - last);
  1137. // Skip over the semicolon
  1138. last = c + 1;
  1139. if ( !newArg.empty() || emptyArgs )
  1140. {
  1141. // Add the last argument if the string is not empty.
  1142. newargs.push_back(newArg);
  1143. newArg = "";
  1144. }
  1145. }
  1146. } break;
  1147. default:
  1148. {
  1149. // Just append this character.
  1150. } break;
  1151. }
  1152. }
  1153. newArg.append(last);
  1154. if ( !newArg.empty() || emptyArgs )
  1155. {
  1156. // Add the last argument if the string is not empty.
  1157. newargs.push_back(newArg);
  1158. }
  1159. }
  1160. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1161. std::vector<std::string>& files,
  1162. int type /* = 0 */)
  1163. {
  1164. files.clear();
  1165. if ( glob[glob.size()-1] != '*' )
  1166. {
  1167. return false;
  1168. }
  1169. std::string path = cmSystemTools::GetFilenamePath(glob);
  1170. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1171. ppath = ppath.substr(0, ppath.size()-1);
  1172. if (path.empty())
  1173. {
  1174. path = "/";
  1175. }
  1176. bool res = false;
  1177. cmsys::Directory d;
  1178. if (d.Load(path))
  1179. {
  1180. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1181. {
  1182. if((std::string(d.GetFile(i)) != ".")
  1183. && (std::string(d.GetFile(i)) != ".."))
  1184. {
  1185. std::string fname = path;
  1186. if ( path[path.size()-1] != '/' )
  1187. {
  1188. fname +="/";
  1189. }
  1190. fname += d.GetFile(i);
  1191. std::string sfname = d.GetFile(i);
  1192. if ( type > 0 && cmSystemTools::FileIsDirectory(fname) )
  1193. {
  1194. continue;
  1195. }
  1196. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname) )
  1197. {
  1198. continue;
  1199. }
  1200. if ( sfname.size() >= ppath.size() &&
  1201. sfname.substr(0, ppath.size()) ==
  1202. ppath )
  1203. {
  1204. files.push_back(fname);
  1205. res = true;
  1206. }
  1207. }
  1208. }
  1209. }
  1210. return res;
  1211. }
  1212. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1213. {
  1214. if ( ! cext || *cext == 0 )
  1215. {
  1216. return cmSystemTools::NO_FILE_FORMAT;
  1217. }
  1218. //std::string ext = cmSystemTools::LowerCase(cext);
  1219. std::string ext = cext;
  1220. if ( ext == "c" || ext == ".c" ||
  1221. ext == "m" || ext == ".m"
  1222. ) { return cmSystemTools::C_FILE_FORMAT; }
  1223. if (
  1224. ext == "C" || ext == ".C" ||
  1225. ext == "M" || ext == ".M" ||
  1226. ext == "c++" || ext == ".c++" ||
  1227. ext == "cc" || ext == ".cc" ||
  1228. ext == "cpp" || ext == ".cpp" ||
  1229. ext == "cxx" || ext == ".cxx" ||
  1230. ext == "mm" || ext == ".mm"
  1231. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1232. if (
  1233. ext == "f" || ext == ".f" ||
  1234. ext == "F" || ext == ".F" ||
  1235. ext == "f77" || ext == ".f77" ||
  1236. ext == "f90" || ext == ".f90" ||
  1237. ext == "for" || ext == ".for" ||
  1238. ext == "f95" || ext == ".f95"
  1239. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1240. if ( ext == "java" || ext == ".java" )
  1241. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1242. if (
  1243. ext == "H" || ext == ".H" ||
  1244. ext == "h" || ext == ".h" ||
  1245. ext == "h++" || ext == ".h++" ||
  1246. ext == "hm" || ext == ".hm" ||
  1247. ext == "hpp" || ext == ".hpp" ||
  1248. ext == "hxx" || ext == ".hxx" ||
  1249. ext == "in" || ext == ".in" ||
  1250. ext == "txx" || ext == ".txx"
  1251. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1252. if ( ext == "rc" || ext == ".rc" )
  1253. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1254. if ( ext == "def" || ext == ".def" )
  1255. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1256. if ( ext == "lib" || ext == ".lib" ||
  1257. ext == "a" || ext == ".a")
  1258. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1259. if ( ext == "o" || ext == ".o" ||
  1260. ext == "obj" || ext == ".obj")
  1261. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1262. #ifdef __APPLE__
  1263. if ( ext == "dylib" || ext == ".dylib" )
  1264. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1265. if ( ext == "so" || ext == ".so" ||
  1266. ext == "bundle" || ext == ".bundle" )
  1267. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1268. #else // __APPLE__
  1269. if ( ext == "so" || ext == ".so" ||
  1270. ext == "sl" || ext == ".sl" ||
  1271. ext == "dll" || ext == ".dll" )
  1272. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1273. #endif // __APPLE__
  1274. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1275. }
  1276. bool cmSystemTools::Split(const char* s, std::vector<std::string>& l)
  1277. {
  1278. std::vector<std::string> temp;
  1279. bool res = Superclass::Split(s, temp);
  1280. l.insert(l.end(), temp.begin(), temp.end());
  1281. return res;
  1282. }
  1283. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1284. {
  1285. #if defined(_WIN32) && !defined(__CYGWIN__)
  1286. if(s_ForceUnixPaths)
  1287. {
  1288. return cmSystemTools::ConvertToUnixOutputPath(path);
  1289. }
  1290. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1291. #else
  1292. return cmSystemTools::ConvertToUnixOutputPath(path);
  1293. #endif
  1294. }
  1295. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1296. {
  1297. #if defined(_WIN32) && !defined(__CYGWIN__)
  1298. if(!s_ForceUnixPaths)
  1299. {
  1300. // Convert to windows slashes.
  1301. std::string::size_type pos = 0;
  1302. while((pos = path.find('/', pos)) != std::string::npos)
  1303. {
  1304. path[pos++] = '\\';
  1305. }
  1306. }
  1307. #else
  1308. static_cast<void>(path);
  1309. #endif
  1310. }
  1311. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1312. {
  1313. #if defined(_WIN32) && !defined(__CYGWIN__)
  1314. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1315. #else
  1316. return cmSystemTools::ConvertToUnixOutputPath(path);
  1317. #endif
  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, FILE_FLAG_BACKUP_SEMANTICS, 0);
  1915. cmSystemToolsWindowsHandle hTo =
  1916. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(toFile).c_str(),
  1917. FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING,
  1918. FILE_FLAG_BACKUP_SEMANTICS, 0);
  1919. if(!hFrom || !hTo)
  1920. {
  1921. return false;
  1922. }
  1923. FILETIME timeCreation;
  1924. FILETIME timeLastAccess;
  1925. FILETIME timeLastWrite;
  1926. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  1927. {
  1928. return false;
  1929. }
  1930. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  1931. {
  1932. return false;
  1933. }
  1934. #else
  1935. struct stat fromStat;
  1936. if(stat(fromFile, &fromStat) < 0)
  1937. {
  1938. return false;
  1939. }
  1940. struct utimbuf buf;
  1941. buf.actime = fromStat.st_atime;
  1942. buf.modtime = fromStat.st_mtime;
  1943. if(utime(toFile, &buf) < 0)
  1944. {
  1945. return false;
  1946. }
  1947. #endif
  1948. return true;
  1949. }
  1950. //----------------------------------------------------------------------------
  1951. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  1952. {
  1953. return new cmSystemToolsFileTime;
  1954. }
  1955. //----------------------------------------------------------------------------
  1956. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  1957. {
  1958. delete t;
  1959. }
  1960. //----------------------------------------------------------------------------
  1961. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  1962. {
  1963. #if defined(_WIN32) && !defined(__CYGWIN__)
  1964. cmSystemToolsWindowsHandle h =
  1965. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(fname).c_str(),
  1966. GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING,
  1967. FILE_FLAG_BACKUP_SEMANTICS, 0);
  1968. if(!h)
  1969. {
  1970. return false;
  1971. }
  1972. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  1973. {
  1974. return false;
  1975. }
  1976. #else
  1977. struct stat st;
  1978. if(stat(fname, &st) < 0)
  1979. {
  1980. return false;
  1981. }
  1982. t->timeBuf.actime = st.st_atime;
  1983. t->timeBuf.modtime = st.st_mtime;
  1984. #endif
  1985. return true;
  1986. }
  1987. //----------------------------------------------------------------------------
  1988. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  1989. {
  1990. #if defined(_WIN32) && !defined(__CYGWIN__)
  1991. cmSystemToolsWindowsHandle h =
  1992. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(fname).c_str(),
  1993. FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING,
  1994. FILE_FLAG_BACKUP_SEMANTICS, 0);
  1995. if(!h)
  1996. {
  1997. return false;
  1998. }
  1999. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2000. {
  2001. return false;
  2002. }
  2003. #else
  2004. if(utime(fname, &t->timeBuf) < 0)
  2005. {
  2006. return false;
  2007. }
  2008. #endif
  2009. return true;
  2010. }
  2011. //----------------------------------------------------------------------------
  2012. #ifdef _WIN32
  2013. # ifndef CRYPT_SILENT
  2014. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2015. # endif
  2016. static int WinCryptRandom(void* data, size_t size)
  2017. {
  2018. int result = 0;
  2019. HCRYPTPROV hProvider = 0;
  2020. if(CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2021. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2022. {
  2023. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data)? 1:0;
  2024. CryptReleaseContext(hProvider, 0);
  2025. }
  2026. return result;
  2027. }
  2028. #endif
  2029. //----------------------------------------------------------------------------
  2030. unsigned int cmSystemTools::RandomSeed()
  2031. {
  2032. #if defined(_WIN32) && !defined(__CYGWIN__)
  2033. unsigned int seed = 0;
  2034. // Try using a real random source.
  2035. if(WinCryptRandom(&seed, sizeof(seed)))
  2036. {
  2037. return seed;
  2038. }
  2039. // Fall back to the time and pid.
  2040. FILETIME ft;
  2041. GetSystemTimeAsFileTime(&ft);
  2042. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2043. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2044. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2045. return t1 ^ t2 ^ pid;
  2046. #else
  2047. union
  2048. {
  2049. unsigned int integer;
  2050. char bytes[sizeof(unsigned int)];
  2051. } seed;
  2052. // Try using a real random source.
  2053. cmsys::ifstream fin("/dev/urandom");
  2054. if(fin && fin.read(seed.bytes, sizeof(seed)) &&
  2055. fin.gcount() == sizeof(seed))
  2056. {
  2057. return seed.integer;
  2058. }
  2059. // Fall back to the time and pid.
  2060. struct timeval t;
  2061. gettimeofday(&t, 0);
  2062. unsigned int pid = static_cast<unsigned int>(getpid());
  2063. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2064. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2065. // Since tv_usec never fills more than 11 bits we shift it to fill
  2066. // in the slow-changing high-order bits of tv_sec.
  2067. return tv_sec ^ (tv_usec << 21) ^ pid;
  2068. #endif
  2069. }
  2070. //----------------------------------------------------------------------------
  2071. static std::string cmSystemToolsCMakeCommand;
  2072. static std::string cmSystemToolsCTestCommand;
  2073. static std::string cmSystemToolsCPackCommand;
  2074. static std::string cmSystemToolsCMakeCursesCommand;
  2075. static std::string cmSystemToolsCMakeGUICommand;
  2076. static std::string cmSystemToolsCMClDepsCommand;
  2077. static std::string cmSystemToolsCMakeRoot;
  2078. void cmSystemTools::FindCMakeResources(const char* argv0)
  2079. {
  2080. std::string exe_dir;
  2081. #if defined(_WIN32) && !defined(__CYGWIN__)
  2082. (void)argv0; // ignore this on windows
  2083. wchar_t modulepath[_MAX_PATH];
  2084. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  2085. exe_dir =
  2086. cmSystemTools::GetFilenamePath(cmsys::Encoding::ToNarrow(modulepath));
  2087. #elif defined(__APPLE__)
  2088. (void)argv0; // ignore this on OS X
  2089. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2090. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2091. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2092. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2093. # else
  2094. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2095. # endif
  2096. # undef CM_EXE_PATH_LOCAL_SIZE
  2097. char* exe_path = exe_path_local;
  2098. if(_NSGetExecutablePath(exe_path, &exe_path_size) < 0)
  2099. {
  2100. exe_path = (char*)malloc(exe_path_size);
  2101. _NSGetExecutablePath(exe_path, &exe_path_size);
  2102. }
  2103. exe_dir =
  2104. cmSystemTools::GetFilenamePath(
  2105. cmSystemTools::GetRealPath(exe_path));
  2106. if(exe_path != exe_path_local)
  2107. {
  2108. free(exe_path);
  2109. }
  2110. if(cmSystemTools::GetFilenameName(exe_dir) == "MacOS")
  2111. {
  2112. // The executable is inside an application bundle.
  2113. // Look for ../bin (install tree) and then fall back to
  2114. // ../../../bin (build tree).
  2115. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2116. if(cmSystemTools::FileExists((exe_dir+"/bin/cmake").c_str()))
  2117. {
  2118. exe_dir += "/bin";
  2119. }
  2120. else
  2121. {
  2122. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2123. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2124. }
  2125. }
  2126. #else
  2127. std::string errorMsg;
  2128. std::string exe;
  2129. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2130. {
  2131. // remove symlinks
  2132. exe = cmSystemTools::GetRealPath(exe);
  2133. exe_dir =
  2134. cmSystemTools::GetFilenamePath(exe);
  2135. }
  2136. else
  2137. {
  2138. // ???
  2139. }
  2140. #endif
  2141. cmSystemToolsCMakeCommand = exe_dir;
  2142. cmSystemToolsCMakeCommand += "/cmake";
  2143. cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
  2144. #ifndef CMAKE_BUILD_WITH_CMAKE
  2145. // The bootstrap cmake does not provide the other tools,
  2146. // so use the directory where they are about to be built.
  2147. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2148. #endif
  2149. cmSystemToolsCTestCommand = exe_dir;
  2150. cmSystemToolsCTestCommand += "/ctest";
  2151. cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
  2152. cmSystemToolsCPackCommand = exe_dir;
  2153. cmSystemToolsCPackCommand += "/cpack";
  2154. cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension();
  2155. cmSystemToolsCMakeGUICommand = exe_dir;
  2156. cmSystemToolsCMakeGUICommand += "/cmake-gui";
  2157. cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
  2158. if(!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str()))
  2159. {
  2160. cmSystemToolsCMakeGUICommand = "";
  2161. }
  2162. cmSystemToolsCMakeCursesCommand = exe_dir;
  2163. cmSystemToolsCMakeCursesCommand += "/ccmake";
  2164. cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
  2165. if(!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str()))
  2166. {
  2167. cmSystemToolsCMakeCursesCommand = "";
  2168. }
  2169. cmSystemToolsCMClDepsCommand = exe_dir;
  2170. cmSystemToolsCMClDepsCommand += "/cmcldeps";
  2171. cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension();
  2172. if(!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand.c_str()))
  2173. {
  2174. cmSystemToolsCMClDepsCommand = "";
  2175. }
  2176. #ifdef CMAKE_BUILD_WITH_CMAKE
  2177. // Install tree has "<prefix>/bin/cmake" and "<prefix><CMAKE_DATA_DIR>".
  2178. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2179. cmSystemToolsCMakeRoot = dir + CMAKE_DATA_DIR;
  2180. if(!cmSystemTools::FileExists(
  2181. (cmSystemToolsCMakeRoot+"/Modules/CMake.cmake").c_str()))
  2182. {
  2183. // Build tree has "<build>/bin[/<config>]/cmake" and
  2184. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2185. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2186. cmsys::ifstream fin(src_dir_txt.c_str());
  2187. std::string src_dir;
  2188. if(fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2189. cmSystemTools::FileIsDirectory(src_dir))
  2190. {
  2191. cmSystemToolsCMakeRoot = src_dir;
  2192. }
  2193. else
  2194. {
  2195. dir = cmSystemTools::GetFilenamePath(dir);
  2196. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2197. cmsys::ifstream fin2(src_dir_txt.c_str());
  2198. if(fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2199. cmSystemTools::FileIsDirectory(src_dir))
  2200. {
  2201. cmSystemToolsCMakeRoot = src_dir;
  2202. }
  2203. }
  2204. }
  2205. #else
  2206. // Bootstrap build knows its source.
  2207. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2208. #endif
  2209. }
  2210. //----------------------------------------------------------------------------
  2211. std::string const& cmSystemTools::GetCMakeCommand()
  2212. {
  2213. return cmSystemToolsCMakeCommand;
  2214. }
  2215. //----------------------------------------------------------------------------
  2216. std::string const& cmSystemTools::GetCTestCommand()
  2217. {
  2218. return cmSystemToolsCTestCommand;
  2219. }
  2220. //----------------------------------------------------------------------------
  2221. std::string const& cmSystemTools::GetCPackCommand()
  2222. {
  2223. return cmSystemToolsCPackCommand;
  2224. }
  2225. //----------------------------------------------------------------------------
  2226. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2227. {
  2228. return cmSystemToolsCMakeCursesCommand;
  2229. }
  2230. //----------------------------------------------------------------------------
  2231. std::string const& cmSystemTools::GetCMakeGUICommand()
  2232. {
  2233. return cmSystemToolsCMakeGUICommand;
  2234. }
  2235. //----------------------------------------------------------------------------
  2236. std::string const& cmSystemTools::GetCMClDepsCommand()
  2237. {
  2238. return cmSystemToolsCMClDepsCommand;
  2239. }
  2240. //----------------------------------------------------------------------------
  2241. std::string const& cmSystemTools::GetCMakeRoot()
  2242. {
  2243. return cmSystemToolsCMakeRoot;
  2244. }
  2245. //----------------------------------------------------------------------------
  2246. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2247. bool newline, bool enabled)
  2248. {
  2249. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2250. // to determine whether the stream is displayed on a tty. In this
  2251. // case it assumes no unless we tell it otherwise. Since we want
  2252. // color messages to be displayed for users we will assume yes.
  2253. // However, we can test for some situations when the answer is most
  2254. // likely no.
  2255. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2256. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2257. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2258. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2259. {
  2260. // Avoid printing color escapes during dashboard builds.
  2261. assumeTTY = 0;
  2262. }
  2263. if(enabled && color != cmsysTerminal_Color_Normal)
  2264. {
  2265. // Print with color. Delay the newline until later so that
  2266. // all color restore sequences appear before it.
  2267. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2268. }
  2269. else
  2270. {
  2271. // Color is disabled. Print without color.
  2272. fprintf(stdout, "%s", message);
  2273. }
  2274. if(newline)
  2275. {
  2276. fprintf(stdout, "\n");
  2277. }
  2278. }
  2279. //----------------------------------------------------------------------------
  2280. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2281. std::string& soname)
  2282. {
  2283. // For ELF shared libraries use a real parser to get the correct
  2284. // soname.
  2285. #if defined(CMAKE_USE_ELF_PARSER)
  2286. cmELF elf(fullPath.c_str());
  2287. if(elf)
  2288. {
  2289. return elf.GetSOName(soname);
  2290. }
  2291. #endif
  2292. // If the file is not a symlink we have no guess for its soname.
  2293. if(!cmSystemTools::FileIsSymlink(fullPath))
  2294. {
  2295. return false;
  2296. }
  2297. if(!cmSystemTools::ReadSymlink(fullPath, soname))
  2298. {
  2299. return false;
  2300. }
  2301. // If the symlink has a path component we have no guess for the soname.
  2302. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2303. {
  2304. return false;
  2305. }
  2306. // If the symlink points at an extended version of the same name
  2307. // assume it is the soname.
  2308. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2309. if(soname.length() > name.length() &&
  2310. soname.substr(0, name.length()) == name)
  2311. {
  2312. return true;
  2313. }
  2314. return false;
  2315. }
  2316. //----------------------------------------------------------------------------
  2317. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2318. std::string& soname)
  2319. {
  2320. #if defined(CMAKE_USE_MACH_PARSER)
  2321. cmMachO macho(fullPath.c_str());
  2322. if(macho)
  2323. {
  2324. return macho.GetInstallName(soname);
  2325. }
  2326. #else
  2327. (void)fullPath;
  2328. (void)soname;
  2329. #endif
  2330. return false;
  2331. }
  2332. //----------------------------------------------------------------------------
  2333. #if defined(CMAKE_USE_ELF_PARSER)
  2334. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2335. std::string const& want)
  2336. {
  2337. // Search for the desired rpath.
  2338. std::string::size_type pos = have.find(want);
  2339. // If the path is not present we are done.
  2340. if(pos == std::string::npos)
  2341. {
  2342. return pos;
  2343. }
  2344. // Build a regex to match a properly separated path instance.
  2345. std::string regex_str = "(^|:)(";
  2346. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2347. {
  2348. int ch = *i;
  2349. if(!(('a' <= ch && ch <= 'z') ||
  2350. ('A' <= ch && ch <= 'Z') ||
  2351. ('0' <= ch && ch <= '9')))
  2352. {
  2353. // Escape the non-alphanumeric character.
  2354. regex_str += "\\";
  2355. }
  2356. // Store the character.
  2357. regex_str.append(1, static_cast<char>(ch));
  2358. }
  2359. regex_str += ")(:|$)";
  2360. // Look for the separated path.
  2361. cmsys::RegularExpression regex(regex_str.c_str());
  2362. if(regex.find(have))
  2363. {
  2364. // Return the position of the path portion.
  2365. return regex.start(2);
  2366. }
  2367. else
  2368. {
  2369. // The desired rpath was not found.
  2370. return std::string::npos;
  2371. }
  2372. }
  2373. #endif
  2374. #if defined(CMAKE_USE_ELF_PARSER)
  2375. struct cmSystemToolsRPathInfo
  2376. {
  2377. unsigned long Position;
  2378. unsigned long Size;
  2379. std::string Name;
  2380. std::string Value;
  2381. };
  2382. #endif
  2383. //----------------------------------------------------------------------------
  2384. bool cmSystemTools::ChangeRPath(std::string const& file,
  2385. std::string const& oldRPath,
  2386. std::string const& newRPath,
  2387. std::string* emsg,
  2388. bool* changed)
  2389. {
  2390. #if defined(CMAKE_USE_ELF_PARSER)
  2391. if(changed)
  2392. {
  2393. *changed = false;
  2394. }
  2395. int rp_count = 0;
  2396. cmSystemToolsRPathInfo rp[2];
  2397. {
  2398. // Parse the ELF binary.
  2399. cmELF elf(file.c_str());
  2400. // Get the RPATH and RUNPATH entries from it.
  2401. int se_count = 0;
  2402. cmELF::StringEntry const* se[2] = {0, 0};
  2403. const char* se_name[2] = {0, 0};
  2404. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2405. {
  2406. se[se_count] = se_rpath;
  2407. se_name[se_count] = "RPATH";
  2408. ++se_count;
  2409. }
  2410. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2411. {
  2412. se[se_count] = se_runpath;
  2413. se_name[se_count] = "RUNPATH";
  2414. ++se_count;
  2415. }
  2416. if(se_count == 0)
  2417. {
  2418. if(newRPath.empty())
  2419. {
  2420. // The new rpath is empty and there is no rpath anyway so it is
  2421. // okay.
  2422. return true;
  2423. }
  2424. else
  2425. {
  2426. if(emsg)
  2427. {
  2428. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2429. *emsg += elf.GetErrorMessage();
  2430. }
  2431. return false;
  2432. }
  2433. }
  2434. for(int i=0; i < se_count; ++i)
  2435. {
  2436. // If both RPATH and RUNPATH refer to the same string literal it
  2437. // needs to be changed only once.
  2438. if(rp_count && rp[0].Position == se[i]->Position)
  2439. {
  2440. continue;
  2441. }
  2442. // Make sure the current rpath contains the old rpath.
  2443. std::string::size_type pos =
  2444. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2445. if(pos == std::string::npos)
  2446. {
  2447. // If it contains the new rpath instead then it is okay.
  2448. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2449. {
  2450. continue;
  2451. }
  2452. if(emsg)
  2453. {
  2454. std::ostringstream e;
  2455. e << "The current " << se_name[i] << " is:\n"
  2456. << " " << se[i]->Value << "\n"
  2457. << "which does not contain:\n"
  2458. << " " << oldRPath << "\n"
  2459. << "as was expected.";
  2460. *emsg = e.str();
  2461. }
  2462. return false;
  2463. }
  2464. // Store information about the entry in the file.
  2465. rp[rp_count].Position = se[i]->Position;
  2466. rp[rp_count].Size = se[i]->Size;
  2467. rp[rp_count].Name = se_name[i];
  2468. // Construct the new value which preserves the part of the path
  2469. // not being changed.
  2470. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2471. rp[rp_count].Value += newRPath;
  2472. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2473. oldRPath.npos);
  2474. // Make sure there is enough room to store the new rpath and at
  2475. // least one null terminator.
  2476. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2477. {
  2478. if(emsg)
  2479. {
  2480. *emsg = "The replacement path is too long for the ";
  2481. *emsg += se_name[i];
  2482. *emsg += " entry.";
  2483. }
  2484. return false;
  2485. }
  2486. // This entry is ready for update.
  2487. ++rp_count;
  2488. }
  2489. }
  2490. // If no runtime path needs to be changed, we are done.
  2491. if(rp_count == 0)
  2492. {
  2493. return true;
  2494. }
  2495. {
  2496. // Open the file for update.
  2497. cmsys::ofstream f(file.c_str(),
  2498. std::ios::in | std::ios::out | std::ios::binary);
  2499. if(!f)
  2500. {
  2501. if(emsg)
  2502. {
  2503. *emsg = "Error opening file for update.";
  2504. }
  2505. return false;
  2506. }
  2507. // Store the new RPATH and RUNPATH strings.
  2508. for(int i=0; i < rp_count; ++i)
  2509. {
  2510. // Seek to the RPATH position.
  2511. if(!f.seekp(rp[i].Position))
  2512. {
  2513. if(emsg)
  2514. {
  2515. *emsg = "Error seeking to ";
  2516. *emsg += rp[i].Name;
  2517. *emsg += " position.";
  2518. }
  2519. return false;
  2520. }
  2521. // Write the new rpath. Follow it with enough null terminators to
  2522. // fill the string table entry.
  2523. f << rp[i].Value;
  2524. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2525. {
  2526. f << '\0';
  2527. }
  2528. // Make sure it wrote correctly.
  2529. if(!f)
  2530. {
  2531. if(emsg)
  2532. {
  2533. *emsg = "Error writing the new ";
  2534. *emsg += rp[i].Name;
  2535. *emsg += " string to the file.";
  2536. }
  2537. return false;
  2538. }
  2539. }
  2540. }
  2541. // Everything was updated successfully.
  2542. if(changed)
  2543. {
  2544. *changed = true;
  2545. }
  2546. return true;
  2547. #else
  2548. (void)file;
  2549. (void)oldRPath;
  2550. (void)newRPath;
  2551. (void)emsg;
  2552. (void)changed;
  2553. return false;
  2554. #endif
  2555. }
  2556. //----------------------------------------------------------------------------
  2557. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2558. const char* lhss, const char* rhss)
  2559. {
  2560. const char *endl = lhss;
  2561. const char *endr = rhss;
  2562. unsigned long lhs, rhs;
  2563. while (((*endl >= '0') && (*endl <= '9')) ||
  2564. ((*endr >= '0') && (*endr <= '9')))
  2565. {
  2566. // Do component-wise comparison.
  2567. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2568. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2569. if(lhs < rhs)
  2570. {
  2571. // lhs < rhs, so true if operation is LESS
  2572. return op == cmSystemTools::OP_LESS;
  2573. }
  2574. else if(lhs > rhs)
  2575. {
  2576. // lhs > rhs, so true if operation is GREATER
  2577. return op == cmSystemTools::OP_GREATER;
  2578. }
  2579. if (*endr == '.')
  2580. {
  2581. endr++;
  2582. }
  2583. if (*endl == '.')
  2584. {
  2585. endl++;
  2586. }
  2587. }
  2588. // lhs == rhs, so true if operation is EQUAL
  2589. return op == cmSystemTools::OP_EQUAL;
  2590. }
  2591. //----------------------------------------------------------------------------
  2592. bool cmSystemTools::VersionCompareEqual(std::string const& lhs,
  2593. std::string const& rhs)
  2594. {
  2595. return cmSystemTools::VersionCompare(
  2596. cmSystemTools::OP_EQUAL, lhs.c_str(), rhs.c_str());
  2597. }
  2598. //----------------------------------------------------------------------------
  2599. bool cmSystemTools::VersionCompareGreater(std::string const& lhs,
  2600. std::string const& rhs)
  2601. {
  2602. return cmSystemTools::VersionCompare(
  2603. cmSystemTools::OP_GREATER, lhs.c_str(), rhs.c_str());
  2604. }
  2605. //----------------------------------------------------------------------------
  2606. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2607. bool* removed)
  2608. {
  2609. #if defined(CMAKE_USE_ELF_PARSER)
  2610. if(removed)
  2611. {
  2612. *removed = false;
  2613. }
  2614. int zeroCount = 0;
  2615. unsigned long zeroPosition[2] = {0,0};
  2616. unsigned long zeroSize[2] = {0,0};
  2617. unsigned long bytesBegin = 0;
  2618. std::vector<char> bytes;
  2619. {
  2620. // Parse the ELF binary.
  2621. cmELF elf(file.c_str());
  2622. // Get the RPATH and RUNPATH entries from it and sort them by index
  2623. // in the dynamic section header.
  2624. int se_count = 0;
  2625. cmELF::StringEntry const* se[2] = {0, 0};
  2626. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2627. {
  2628. se[se_count++] = se_rpath;
  2629. }
  2630. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2631. {
  2632. se[se_count++] = se_runpath;
  2633. }
  2634. if(se_count == 0)
  2635. {
  2636. // There is no RPATH or RUNPATH anyway.
  2637. return true;
  2638. }
  2639. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2640. {
  2641. std::swap(se[0], se[1]);
  2642. }
  2643. // Get the size of the dynamic section header.
  2644. unsigned int count = elf.GetDynamicEntryCount();
  2645. if(count == 0)
  2646. {
  2647. // This should happen only for invalid ELF files where a DT_NULL
  2648. // appears before the end of the table.
  2649. if(emsg)
  2650. {
  2651. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2652. }
  2653. return false;
  2654. }
  2655. // Save information about the string entries to be zeroed.
  2656. zeroCount = se_count;
  2657. for(int i=0; i < se_count; ++i)
  2658. {
  2659. zeroPosition[i] = se[i]->Position;
  2660. zeroSize[i] = se[i]->Size;
  2661. }
  2662. // Get the range of file positions corresponding to each entry and
  2663. // the rest of the table after them.
  2664. unsigned long entryBegin[3] = {0,0,0};
  2665. unsigned long entryEnd[2] = {0,0};
  2666. for(int i=0; i < se_count; ++i)
  2667. {
  2668. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2669. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2670. }
  2671. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2672. // The data are to be written over the old table entries starting at
  2673. // the first one being removed.
  2674. bytesBegin = entryBegin[0];
  2675. unsigned long bytesEnd = entryBegin[se_count];
  2676. // Allocate a buffer to hold the part of the file to be written.
  2677. // Initialize it with zeros.
  2678. bytes.resize(bytesEnd - bytesBegin, 0);
  2679. // Read the part of the DYNAMIC section header that will move.
  2680. // The remainder of the buffer will be left with zeros which
  2681. // represent a DT_NULL entry.
  2682. char* data = &bytes[0];
  2683. for(int i=0; i < se_count; ++i)
  2684. {
  2685. // Read data between the entries being removed.
  2686. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2687. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2688. {
  2689. if(emsg)
  2690. {
  2691. *emsg = "Failed to read DYNAMIC section header.";
  2692. }
  2693. return false;
  2694. }
  2695. data += sz;
  2696. }
  2697. }
  2698. // Open the file for update.
  2699. cmsys::ofstream f(file.c_str(),
  2700. std::ios::in | std::ios::out | std::ios::binary);
  2701. if(!f)
  2702. {
  2703. if(emsg)
  2704. {
  2705. *emsg = "Error opening file for update.";
  2706. }
  2707. return false;
  2708. }
  2709. // Write the new DYNAMIC table header.
  2710. if(!f.seekp(bytesBegin))
  2711. {
  2712. if(emsg)
  2713. {
  2714. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2715. }
  2716. return false;
  2717. }
  2718. if(!f.write(&bytes[0], bytes.size()))
  2719. {
  2720. if(emsg)
  2721. {
  2722. *emsg = "Error replacing DYNAMIC table header.";
  2723. }
  2724. return false;
  2725. }
  2726. // Fill the RPATH and RUNPATH strings with zero bytes.
  2727. for(int i=0; i < zeroCount; ++i)
  2728. {
  2729. if(!f.seekp(zeroPosition[i]))
  2730. {
  2731. if(emsg)
  2732. {
  2733. *emsg = "Error seeking to RPATH position.";
  2734. }
  2735. return false;
  2736. }
  2737. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2738. {
  2739. f << '\0';
  2740. }
  2741. if(!f)
  2742. {
  2743. if(emsg)
  2744. {
  2745. *emsg = "Error writing the empty rpath string to the file.";
  2746. }
  2747. return false;
  2748. }
  2749. }
  2750. // Everything was updated successfully.
  2751. if(removed)
  2752. {
  2753. *removed = true;
  2754. }
  2755. return true;
  2756. #else
  2757. (void)file;
  2758. (void)emsg;
  2759. (void)removed;
  2760. return false;
  2761. #endif
  2762. }
  2763. //----------------------------------------------------------------------------
  2764. bool cmSystemTools::CheckRPath(std::string const& file,
  2765. std::string const& newRPath)
  2766. {
  2767. #if defined(CMAKE_USE_ELF_PARSER)
  2768. // Parse the ELF binary.
  2769. cmELF elf(file.c_str());
  2770. // Get the RPATH or RUNPATH entry from it.
  2771. cmELF::StringEntry const* se = elf.GetRPath();
  2772. if(!se)
  2773. {
  2774. se = elf.GetRunPath();
  2775. }
  2776. // Make sure the current rpath contains the new rpath.
  2777. if(newRPath.empty())
  2778. {
  2779. if(!se)
  2780. {
  2781. return true;
  2782. }
  2783. }
  2784. else
  2785. {
  2786. if(se &&
  2787. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2788. {
  2789. return true;
  2790. }
  2791. }
  2792. return false;
  2793. #else
  2794. (void)file;
  2795. (void)newRPath;
  2796. return false;
  2797. #endif
  2798. }
  2799. //----------------------------------------------------------------------------
  2800. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2801. {
  2802. // Windows sometimes locks files temporarily so try a few times.
  2803. for(int i = 0; i < 10; ++i)
  2804. {
  2805. if(cmSystemTools::RemoveADirectory(dir))
  2806. {
  2807. return true;
  2808. }
  2809. cmSystemTools::Delay(100);
  2810. }
  2811. return false;
  2812. }
  2813. //----------------------------------------------------------------------------
  2814. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2815. const std::string& sep)
  2816. {
  2817. std::vector<std::string> tokens;
  2818. std::string::size_type tokend = 0;
  2819. do
  2820. {
  2821. std::string::size_type tokstart=str.find_first_not_of(sep, tokend);
  2822. if (tokstart==std::string::npos)
  2823. {
  2824. break; // no more tokens
  2825. }
  2826. tokend=str.find_first_of(sep,tokstart);
  2827. if (tokend==std::string::npos)
  2828. {
  2829. tokens.push_back(str.substr(tokstart));
  2830. }
  2831. else
  2832. {
  2833. tokens.push_back(str.substr(tokstart,tokend-tokstart));
  2834. }
  2835. } while (tokend!=std::string::npos);
  2836. if (tokens.empty())
  2837. {
  2838. tokens.push_back("");
  2839. }
  2840. return tokens;
  2841. }
  2842. //----------------------------------------------------------------------------
  2843. bool cmSystemTools::StringToLong(const char* str, long* value)
  2844. {
  2845. errno = 0;
  2846. char *endp;
  2847. *value = strtol(str, &endp, 10);
  2848. return (*endp == '\0') && (endp != str) && (errno == 0);
  2849. }
  2850. //----------------------------------------------------------------------------
  2851. bool cmSystemTools::StringToULong(const char* str, unsigned long* value)
  2852. {
  2853. errno = 0;
  2854. char *endp;
  2855. *value = strtoul(str, &endp, 10);
  2856. return (*endp == '\0') && (endp != str) && (errno == 0);
  2857. }