cmFileCommand.cxx 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757
  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 "cmFileCommand.h"
  11. #include "cmCryptoHash.h"
  12. #include "cmake.h"
  13. #include "cmHexFileConverter.h"
  14. #include "cmInstallType.h"
  15. #include "cmFileTimeComparison.h"
  16. #include "cmCryptoHash.h"
  17. #include "cmTimestamp.h"
  18. #if defined(CMAKE_BUILD_WITH_CMAKE)
  19. #include "cm_curl.h"
  20. #include "cmFileLockResult.h"
  21. #endif
  22. #undef GetCurrentDirectory
  23. #include <assert.h>
  24. #include <sys/types.h>
  25. #include <sys/stat.h>
  26. #include <cmsys/auto_ptr.hxx>
  27. #include <cmsys/Directory.hxx>
  28. #include <cmsys/Glob.hxx>
  29. #include <cmsys/RegularExpression.hxx>
  30. #include <cmsys/FStream.hxx>
  31. #include <cmsys/Encoding.hxx>
  32. // Table of permissions flags.
  33. #if defined(_WIN32) && !defined(__CYGWIN__)
  34. static mode_t mode_owner_read = S_IREAD;
  35. static mode_t mode_owner_write = S_IWRITE;
  36. static mode_t mode_owner_execute = S_IEXEC;
  37. static mode_t mode_group_read = 0;
  38. static mode_t mode_group_write = 0;
  39. static mode_t mode_group_execute = 0;
  40. static mode_t mode_world_read = 0;
  41. static mode_t mode_world_write = 0;
  42. static mode_t mode_world_execute = 0;
  43. static mode_t mode_setuid = 0;
  44. static mode_t mode_setgid = 0;
  45. #else
  46. static mode_t mode_owner_read = S_IRUSR;
  47. static mode_t mode_owner_write = S_IWUSR;
  48. static mode_t mode_owner_execute = S_IXUSR;
  49. static mode_t mode_group_read = S_IRGRP;
  50. static mode_t mode_group_write = S_IWGRP;
  51. static mode_t mode_group_execute = S_IXGRP;
  52. static mode_t mode_world_read = S_IROTH;
  53. static mode_t mode_world_write = S_IWOTH;
  54. static mode_t mode_world_execute = S_IXOTH;
  55. static mode_t mode_setuid = S_ISUID;
  56. static mode_t mode_setgid = S_ISGID;
  57. #endif
  58. #if defined(WIN32) && defined(CMAKE_ENCODING_UTF8)
  59. // libcurl doesn't support file:// urls for unicode filenames on Windows.
  60. // Convert string from UTF-8 to ACP if this is a file:// URL.
  61. static std::string fix_file_url_windows(const std::string& url)
  62. {
  63. std::string ret = url;
  64. if(strncmp(url.c_str(), "file://", 7) == 0)
  65. {
  66. cmsys_stl::wstring wurl = cmsys::Encoding::ToWide(url);
  67. if(!wurl.empty())
  68. {
  69. int mblen = WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1,
  70. NULL, 0, NULL, NULL);
  71. if(mblen > 0)
  72. {
  73. std::vector<char> chars(mblen);
  74. mblen = WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1,
  75. &chars[0], mblen, NULL, NULL);
  76. if(mblen > 0)
  77. {
  78. ret = &chars[0];
  79. }
  80. }
  81. }
  82. }
  83. return ret;
  84. }
  85. #endif
  86. // cmLibraryCommand
  87. bool cmFileCommand
  88. ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
  89. {
  90. if(args.size() < 2 )
  91. {
  92. this->SetError("must be called with at least two arguments.");
  93. return false;
  94. }
  95. std::string subCommand = args[0];
  96. if ( subCommand == "WRITE" )
  97. {
  98. return this->HandleWriteCommand(args, false);
  99. }
  100. else if ( subCommand == "APPEND" )
  101. {
  102. return this->HandleWriteCommand(args, true);
  103. }
  104. else if ( subCommand == "DOWNLOAD" )
  105. {
  106. return this->HandleDownloadCommand(args);
  107. }
  108. else if ( subCommand == "UPLOAD" )
  109. {
  110. return this->HandleUploadCommand(args);
  111. }
  112. else if ( subCommand == "READ" )
  113. {
  114. return this->HandleReadCommand(args);
  115. }
  116. else if ( subCommand == "MD5" ||
  117. subCommand == "SHA1" ||
  118. subCommand == "SHA224" ||
  119. subCommand == "SHA256" ||
  120. subCommand == "SHA384" ||
  121. subCommand == "SHA512" )
  122. {
  123. return this->HandleHashCommand(args);
  124. }
  125. else if ( subCommand == "STRINGS" )
  126. {
  127. return this->HandleStringsCommand(args);
  128. }
  129. else if ( subCommand == "GLOB" )
  130. {
  131. return this->HandleGlobCommand(args, false);
  132. }
  133. else if ( subCommand == "GLOB_RECURSE" )
  134. {
  135. return this->HandleGlobCommand(args, true);
  136. }
  137. else if ( subCommand == "MAKE_DIRECTORY" )
  138. {
  139. return this->HandleMakeDirectoryCommand(args);
  140. }
  141. else if ( subCommand == "RENAME" )
  142. {
  143. return this->HandleRename(args);
  144. }
  145. else if ( subCommand == "REMOVE" )
  146. {
  147. return this->HandleRemove(args, false);
  148. }
  149. else if ( subCommand == "REMOVE_RECURSE" )
  150. {
  151. return this->HandleRemove(args, true);
  152. }
  153. else if ( subCommand == "COPY" )
  154. {
  155. return this->HandleCopyCommand(args);
  156. }
  157. else if ( subCommand == "INSTALL" )
  158. {
  159. return this->HandleInstallCommand(args);
  160. }
  161. else if ( subCommand == "DIFFERENT" )
  162. {
  163. return this->HandleDifferentCommand(args);
  164. }
  165. else if ( subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH" )
  166. {
  167. return this->HandleRPathChangeCommand(args);
  168. }
  169. else if ( subCommand == "RPATH_CHECK" )
  170. {
  171. return this->HandleRPathCheckCommand(args);
  172. }
  173. else if ( subCommand == "RPATH_REMOVE" )
  174. {
  175. return this->HandleRPathRemoveCommand(args);
  176. }
  177. else if ( subCommand == "RELATIVE_PATH" )
  178. {
  179. return this->HandleRelativePathCommand(args);
  180. }
  181. else if ( subCommand == "TO_CMAKE_PATH" )
  182. {
  183. return this->HandleCMakePathCommand(args, false);
  184. }
  185. else if ( subCommand == "TO_NATIVE_PATH" )
  186. {
  187. return this->HandleCMakePathCommand(args, true);
  188. }
  189. else if ( subCommand == "TIMESTAMP" )
  190. {
  191. return this->HandleTimestampCommand(args);
  192. }
  193. else if ( subCommand == "GENERATE" )
  194. {
  195. return this->HandleGenerateCommand(args);
  196. }
  197. else if ( subCommand == "LOCK" )
  198. {
  199. return this->HandleLockCommand(args);
  200. }
  201. std::string e = "does not recognize sub-command "+subCommand;
  202. this->SetError(e);
  203. return false;
  204. }
  205. //----------------------------------------------------------------------------
  206. bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args,
  207. bool append)
  208. {
  209. std::string message;
  210. std::vector<std::string>::const_iterator i = args.begin();
  211. i++; // Get rid of subcommand
  212. std::string fileName = *i;
  213. if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
  214. {
  215. fileName = this->Makefile->GetCurrentDirectory();
  216. fileName += "/" + *i;
  217. }
  218. i++;
  219. for(;i != args.end(); ++i)
  220. {
  221. message += *i;
  222. }
  223. if ( !this->Makefile->CanIWriteThisFile(fileName.c_str()) )
  224. {
  225. std::string e
  226. = "attempted to write a file: " + fileName +
  227. " into a source directory.";
  228. this->SetError(e);
  229. cmSystemTools::SetFatalErrorOccured();
  230. return false;
  231. }
  232. std::string dir = cmSystemTools::GetFilenamePath(fileName);
  233. cmSystemTools::MakeDirectory(dir.c_str());
  234. mode_t mode = 0;
  235. // Set permissions to writable
  236. if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) )
  237. {
  238. cmSystemTools::SetPermissions(fileName.c_str(),
  239. #if defined( _MSC_VER ) || defined( __MINGW32__ )
  240. mode | S_IWRITE
  241. #else
  242. mode | S_IWUSR | S_IWGRP
  243. #endif
  244. );
  245. }
  246. // If GetPermissions fails, pretend like it is ok. File open will fail if
  247. // the file is not writable
  248. cmsys::ofstream file(fileName.c_str(), append?std::ios::app: std::ios::out);
  249. if ( !file )
  250. {
  251. std::string error = "failed to open for writing (";
  252. error += cmSystemTools::GetLastSystemError();
  253. error += "):\n ";
  254. error += fileName;
  255. this->SetError(error);
  256. return false;
  257. }
  258. file << message;
  259. file.close();
  260. if(mode)
  261. {
  262. cmSystemTools::SetPermissions(fileName.c_str(), mode);
  263. }
  264. return true;
  265. }
  266. //----------------------------------------------------------------------------
  267. bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
  268. {
  269. if ( args.size() < 3 )
  270. {
  271. this->SetError("READ must be called with at least two additional "
  272. "arguments");
  273. return false;
  274. }
  275. cmCommandArgumentsHelper argHelper;
  276. cmCommandArgumentGroup group;
  277. cmCAString readArg (&argHelper, "READ");
  278. cmCAString fileNameArg (&argHelper, 0);
  279. cmCAString resultArg (&argHelper, 0);
  280. cmCAString offsetArg (&argHelper, "OFFSET", &group);
  281. cmCAString limitArg (&argHelper, "LIMIT", &group);
  282. cmCAEnabler hexOutputArg (&argHelper, "HEX", &group);
  283. readArg.Follows(0);
  284. fileNameArg.Follows(&readArg);
  285. resultArg.Follows(&fileNameArg);
  286. group.Follows(&resultArg);
  287. argHelper.Parse(&args, 0);
  288. std::string fileName = fileNameArg.GetString();
  289. if ( !cmsys::SystemTools::FileIsFullPath(fileName.c_str()) )
  290. {
  291. fileName = this->Makefile->GetCurrentDirectory();
  292. fileName += "/" + fileNameArg.GetString();
  293. }
  294. std::string variable = resultArg.GetString();
  295. // Open the specified file.
  296. #if defined(_WIN32) || defined(__CYGWIN__)
  297. cmsys::ifstream file(fileName.c_str(), std::ios::in |
  298. (hexOutputArg.IsEnabled() ? std::ios::binary : std::ios::in));
  299. #else
  300. cmsys::ifstream file(fileName.c_str(), std::ios::in);
  301. #endif
  302. if ( !file )
  303. {
  304. std::string error = "failed to open for reading (";
  305. error += cmSystemTools::GetLastSystemError();
  306. error += "):\n ";
  307. error += fileName;
  308. this->SetError(error);
  309. return false;
  310. }
  311. // is there a limit?
  312. long sizeLimit = -1;
  313. if (limitArg.GetString().size() > 0)
  314. {
  315. sizeLimit = atoi(limitArg.GetCString());
  316. }
  317. // is there an offset?
  318. long offset = 0;
  319. if (offsetArg.GetString().size() > 0)
  320. {
  321. offset = atoi(offsetArg.GetCString());
  322. }
  323. file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
  324. std::string output;
  325. if (hexOutputArg.IsEnabled())
  326. {
  327. // Convert part of the file into hex code
  328. char c;
  329. while((sizeLimit != 0) && (file.get(c)))
  330. {
  331. char hex[4];
  332. sprintf(hex, "%.2x", c&0xff);
  333. output += hex;
  334. if (sizeLimit > 0)
  335. {
  336. sizeLimit--;
  337. }
  338. }
  339. }
  340. else
  341. {
  342. std::string line;
  343. bool has_newline = false;
  344. while (sizeLimit != 0 &&
  345. cmSystemTools::GetLineFromStream(file, line, &has_newline,
  346. sizeLimit) )
  347. {
  348. if (sizeLimit > 0)
  349. {
  350. sizeLimit = sizeLimit - static_cast<long>(line.size());
  351. if (has_newline)
  352. {
  353. sizeLimit--;
  354. }
  355. if (sizeLimit < 0)
  356. {
  357. sizeLimit = 0;
  358. }
  359. }
  360. output += line;
  361. if ( has_newline )
  362. {
  363. output += "\n";
  364. }
  365. }
  366. }
  367. this->Makefile->AddDefinition(variable, output.c_str());
  368. return true;
  369. }
  370. //----------------------------------------------------------------------------
  371. bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
  372. {
  373. #if defined(CMAKE_BUILD_WITH_CMAKE)
  374. if(args.size() != 3)
  375. {
  376. std::ostringstream e;
  377. e << args[0] << " requires a file name and output variable";
  378. this->SetError(e.str());
  379. return false;
  380. }
  381. cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
  382. if(hash.get())
  383. {
  384. std::string out = hash->HashFile(args[1]);
  385. if(!out.empty())
  386. {
  387. this->Makefile->AddDefinition(args[2], out.c_str());
  388. return true;
  389. }
  390. std::ostringstream e;
  391. e << args[0] << " failed to read file \"" << args[1] << "\": "
  392. << cmSystemTools::GetLastSystemError();
  393. this->SetError(e.str());
  394. }
  395. return false;
  396. #else
  397. std::ostringstream e;
  398. e << args[0] << " not available during bootstrap";
  399. this->SetError(e.str().c_str());
  400. return false;
  401. #endif
  402. }
  403. //----------------------------------------------------------------------------
  404. bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
  405. {
  406. if(args.size() < 3)
  407. {
  408. this->SetError("STRINGS requires a file name and output variable");
  409. return false;
  410. }
  411. // Get the file to read.
  412. std::string fileName = args[1];
  413. if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
  414. {
  415. fileName = this->Makefile->GetCurrentDirectory();
  416. fileName += "/" + args[1];
  417. }
  418. // Get the variable in which to store the results.
  419. std::string outVar = args[2];
  420. // Parse the options.
  421. enum { arg_none,
  422. arg_limit_input,
  423. arg_limit_output,
  424. arg_limit_count,
  425. arg_length_minimum,
  426. arg_length_maximum,
  427. arg__maximum,
  428. arg_regex,
  429. arg_encoding };
  430. unsigned int minlen = 0;
  431. unsigned int maxlen = 0;
  432. int limit_input = -1;
  433. int limit_output = -1;
  434. unsigned int limit_count = 0;
  435. cmsys::RegularExpression regex;
  436. bool have_regex = false;
  437. bool newline_consume = false;
  438. bool hex_conversion_enabled = true;
  439. bool utf8_encoding = false;
  440. int arg_mode = arg_none;
  441. for(unsigned int i=3; i < args.size(); ++i)
  442. {
  443. if(args[i] == "LIMIT_INPUT")
  444. {
  445. arg_mode = arg_limit_input;
  446. }
  447. else if(args[i] == "LIMIT_OUTPUT")
  448. {
  449. arg_mode = arg_limit_output;
  450. }
  451. else if(args[i] == "LIMIT_COUNT")
  452. {
  453. arg_mode = arg_limit_count;
  454. }
  455. else if(args[i] == "LENGTH_MINIMUM")
  456. {
  457. arg_mode = arg_length_minimum;
  458. }
  459. else if(args[i] == "LENGTH_MAXIMUM")
  460. {
  461. arg_mode = arg_length_maximum;
  462. }
  463. else if(args[i] == "REGEX")
  464. {
  465. arg_mode = arg_regex;
  466. }
  467. else if(args[i] == "NEWLINE_CONSUME")
  468. {
  469. newline_consume = true;
  470. arg_mode = arg_none;
  471. }
  472. else if(args[i] == "NO_HEX_CONVERSION")
  473. {
  474. hex_conversion_enabled = false;
  475. arg_mode = arg_none;
  476. }
  477. else if(args[i] == "ENCODING")
  478. {
  479. arg_mode = arg_encoding;
  480. }
  481. else if(arg_mode == arg_limit_input)
  482. {
  483. if(sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
  484. limit_input < 0)
  485. {
  486. std::ostringstream e;
  487. e << "STRINGS option LIMIT_INPUT value \""
  488. << args[i] << "\" is not an unsigned integer.";
  489. this->SetError(e.str());
  490. return false;
  491. }
  492. arg_mode = arg_none;
  493. }
  494. else if(arg_mode == arg_limit_output)
  495. {
  496. if(sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
  497. limit_output < 0)
  498. {
  499. std::ostringstream e;
  500. e << "STRINGS option LIMIT_OUTPUT value \""
  501. << args[i] << "\" is not an unsigned integer.";
  502. this->SetError(e.str());
  503. return false;
  504. }
  505. arg_mode = arg_none;
  506. }
  507. else if(arg_mode == arg_limit_count)
  508. {
  509. int count;
  510. if(sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0)
  511. {
  512. std::ostringstream e;
  513. e << "STRINGS option LIMIT_COUNT value \""
  514. << args[i] << "\" is not an unsigned integer.";
  515. this->SetError(e.str());
  516. return false;
  517. }
  518. limit_count = count;
  519. arg_mode = arg_none;
  520. }
  521. else if(arg_mode == arg_length_minimum)
  522. {
  523. int len;
  524. if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
  525. {
  526. std::ostringstream e;
  527. e << "STRINGS option LENGTH_MINIMUM value \""
  528. << args[i] << "\" is not an unsigned integer.";
  529. this->SetError(e.str());
  530. return false;
  531. }
  532. minlen = len;
  533. arg_mode = arg_none;
  534. }
  535. else if(arg_mode == arg_length_maximum)
  536. {
  537. int len;
  538. if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
  539. {
  540. std::ostringstream e;
  541. e << "STRINGS option LENGTH_MAXIMUM value \""
  542. << args[i] << "\" is not an unsigned integer.";
  543. this->SetError(e.str());
  544. return false;
  545. }
  546. maxlen = len;
  547. arg_mode = arg_none;
  548. }
  549. else if(arg_mode == arg_regex)
  550. {
  551. if(!regex.compile(args[i].c_str()))
  552. {
  553. std::ostringstream e;
  554. e << "STRINGS option REGEX value \""
  555. << args[i] << "\" could not be compiled.";
  556. this->SetError(e.str());
  557. return false;
  558. }
  559. have_regex = true;
  560. arg_mode = arg_none;
  561. }
  562. else if(arg_mode == arg_encoding)
  563. {
  564. if(args[i] == "UTF-8")
  565. {
  566. utf8_encoding = true;
  567. }
  568. else
  569. {
  570. std::ostringstream e;
  571. e << "STRINGS option ENCODING \""
  572. << args[i] << "\" not recognized.";
  573. this->SetError(e.str());
  574. return false;
  575. }
  576. arg_mode = arg_none;
  577. }
  578. else
  579. {
  580. std::ostringstream e;
  581. e << "STRINGS given unknown argument \""
  582. << args[i] << "\"";
  583. this->SetError(e.str());
  584. return false;
  585. }
  586. }
  587. if (hex_conversion_enabled)
  588. {
  589. // TODO: should work without temp file, but just on a memory buffer
  590. std::string binaryFileName = this->Makefile->GetCurrentOutputDirectory();
  591. binaryFileName += cmake::GetCMakeFilesDirectory();
  592. binaryFileName += "/FileCommandStringsBinaryFile";
  593. if(cmHexFileConverter::TryConvert(fileName.c_str(),binaryFileName.c_str()))
  594. {
  595. fileName = binaryFileName;
  596. }
  597. }
  598. // Open the specified file.
  599. #if defined(_WIN32) || defined(__CYGWIN__)
  600. cmsys::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
  601. #else
  602. cmsys::ifstream fin(fileName.c_str(), std::ios::in);
  603. #endif
  604. if(!fin)
  605. {
  606. std::ostringstream e;
  607. e << "STRINGS file \"" << fileName << "\" cannot be read.";
  608. this->SetError(e.str());
  609. return false;
  610. }
  611. // Parse strings out of the file.
  612. int output_size = 0;
  613. std::vector<std::string> strings;
  614. std::string s;
  615. while((!limit_count || strings.size() < limit_count) &&
  616. (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
  617. fin)
  618. {
  619. std::string current_str;
  620. int c = fin.get();
  621. if(c == '\r')
  622. {
  623. // Ignore CR character to make output always have UNIX newlines.
  624. continue;
  625. }
  626. else if((c >= 0x20 && c < 0x7F) || c == '\t' ||
  627. (c == '\n' && newline_consume))
  628. {
  629. // This is an ASCII character that may be part of a string.
  630. // Cast added to avoid compiler warning. Cast is ok because
  631. // c is guaranteed to fit in char by the above if...
  632. current_str += static_cast<char>(c);
  633. }
  634. else if(utf8_encoding)
  635. {
  636. // Check for UTF-8 encoded string (up to 4 octets)
  637. static const unsigned char utf8_check_table[3][2] =
  638. {
  639. {0xE0, 0xC0},
  640. {0xF0, 0xE0},
  641. {0xF8, 0xF0},
  642. };
  643. // how many octets are there?
  644. unsigned int num_utf8_bytes = 0;
  645. for(unsigned int j=0; num_utf8_bytes == 0 && j<3; j++)
  646. {
  647. if((c & utf8_check_table[j][0]) == utf8_check_table[j][1])
  648. num_utf8_bytes = j+2;
  649. }
  650. // get subsequent octets and check that they are valid
  651. for(unsigned int j=0; j<num_utf8_bytes; j++)
  652. {
  653. if(j != 0)
  654. {
  655. c = fin.get();
  656. if(!fin || (c & 0xC0) != 0x80)
  657. {
  658. fin.putback(static_cast<char>(c));
  659. break;
  660. }
  661. }
  662. current_str += static_cast<char>(c);
  663. }
  664. // if this was an invalid utf8 sequence, discard the data, and put
  665. // back subsequent characters
  666. if((current_str.length() != num_utf8_bytes))
  667. {
  668. for(unsigned int j=0; j<current_str.size()-1; j++)
  669. {
  670. c = current_str[current_str.size() - 1 - j];
  671. fin.putback(static_cast<char>(c));
  672. }
  673. current_str = "";
  674. }
  675. }
  676. if(c == '\n' && !newline_consume)
  677. {
  678. // The current line has been terminated. Check if the current
  679. // string matches the requirements. The length may now be as
  680. // low as zero since blank lines are allowed.
  681. if(s.length() >= minlen &&
  682. (!have_regex || regex.find(s.c_str())))
  683. {
  684. output_size += static_cast<int>(s.size()) + 1;
  685. if(limit_output >= 0 && output_size >= limit_output)
  686. {
  687. s = "";
  688. break;
  689. }
  690. strings.push_back(s);
  691. }
  692. // Reset the string to empty.
  693. s = "";
  694. }
  695. else if(current_str.empty())
  696. {
  697. // A non-string character has been found. Check if the current
  698. // string matches the requirements. We require that the length
  699. // be at least one no matter what the user specified.
  700. if(s.length() >= minlen && s.length() >= 1 &&
  701. (!have_regex || regex.find(s.c_str())))
  702. {
  703. output_size += static_cast<int>(s.size()) + 1;
  704. if(limit_output >= 0 && output_size >= limit_output)
  705. {
  706. s = "";
  707. break;
  708. }
  709. strings.push_back(s);
  710. }
  711. // Reset the string to empty.
  712. s = "";
  713. }
  714. else
  715. {
  716. s += current_str;
  717. }
  718. if(maxlen > 0 && s.size() == maxlen)
  719. {
  720. // Terminate a string if the maximum length is reached.
  721. if(s.length() >= minlen &&
  722. (!have_regex || regex.find(s.c_str())))
  723. {
  724. output_size += static_cast<int>(s.size()) + 1;
  725. if(limit_output >= 0 && output_size >= limit_output)
  726. {
  727. s = "";
  728. break;
  729. }
  730. strings.push_back(s);
  731. }
  732. s = "";
  733. }
  734. }
  735. // If there is a non-empty current string we have hit the end of the
  736. // input file or the input size limit. Check if the current string
  737. // matches the requirements.
  738. if((!limit_count || strings.size() < limit_count) &&
  739. !s.empty() && s.length() >= minlen &&
  740. (!have_regex || regex.find(s.c_str())))
  741. {
  742. output_size += static_cast<int>(s.size()) + 1;
  743. if(limit_output < 0 || output_size < limit_output)
  744. {
  745. strings.push_back(s);
  746. }
  747. }
  748. // Encode the result in a CMake list.
  749. const char* sep = "";
  750. std::string output;
  751. for(std::vector<std::string>::const_iterator si = strings.begin();
  752. si != strings.end(); ++si)
  753. {
  754. // Separate the strings in the output to make it a list.
  755. output += sep;
  756. sep = ";";
  757. // Store the string in the output, but escape semicolons to
  758. // make sure it is a list.
  759. std::string const& sr = *si;
  760. for(unsigned int i=0; i < sr.size(); ++i)
  761. {
  762. if(sr[i] == ';')
  763. {
  764. output += '\\';
  765. }
  766. output += sr[i];
  767. }
  768. }
  769. // Save the output in a makefile variable.
  770. this->Makefile->AddDefinition(outVar, output.c_str());
  771. return true;
  772. }
  773. //----------------------------------------------------------------------------
  774. bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
  775. bool recurse)
  776. {
  777. // File commands has at least one argument
  778. assert(args.size() > 1);
  779. std::vector<std::string>::const_iterator i = args.begin();
  780. i++; // Get rid of subcommand
  781. std::string variable = *i;
  782. i++;
  783. cmsys::Glob g;
  784. g.SetRecurse(recurse);
  785. bool explicitFollowSymlinks = false;
  786. cmPolicies::PolicyStatus status =
  787. this->Makefile->GetPolicyStatus(cmPolicies::CMP0009);
  788. if(recurse)
  789. {
  790. switch(status)
  791. {
  792. case cmPolicies::NEW:
  793. g.RecurseThroughSymlinksOff();
  794. break;
  795. case cmPolicies::OLD:
  796. case cmPolicies::WARN:
  797. case cmPolicies::REQUIRED_IF_USED:
  798. case cmPolicies::REQUIRED_ALWAYS:
  799. g.RecurseThroughSymlinksOn();
  800. break;
  801. }
  802. }
  803. std::string output = "";
  804. bool first = true;
  805. for ( ; i != args.end(); ++i )
  806. {
  807. if ( recurse && (*i == "FOLLOW_SYMLINKS") )
  808. {
  809. explicitFollowSymlinks = true;
  810. g.RecurseThroughSymlinksOn();
  811. ++i;
  812. if ( i == args.end() )
  813. {
  814. this->SetError(
  815. "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS");
  816. return false;
  817. }
  818. }
  819. if ( *i == "RELATIVE" )
  820. {
  821. ++i; // skip RELATIVE
  822. if ( i == args.end() )
  823. {
  824. this->SetError("GLOB requires a directory after the RELATIVE tag");
  825. return false;
  826. }
  827. g.SetRelative(i->c_str());
  828. ++i;
  829. if(i == args.end())
  830. {
  831. this->SetError("GLOB requires a glob expression after the directory");
  832. return false;
  833. }
  834. }
  835. if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
  836. {
  837. std::string expr = this->Makefile->GetCurrentDirectory();
  838. // Handle script mode
  839. if ( expr.size() > 0 )
  840. {
  841. expr += "/" + *i;
  842. g.FindFiles(expr);
  843. }
  844. else
  845. {
  846. g.FindFiles(*i);
  847. }
  848. }
  849. else
  850. {
  851. g.FindFiles(*i);
  852. }
  853. std::vector<std::string>::size_type cc;
  854. std::vector<std::string>& files = g.GetFiles();
  855. for ( cc = 0; cc < files.size(); cc ++ )
  856. {
  857. if ( !first )
  858. {
  859. output += ";";
  860. }
  861. output += files[cc];
  862. first = false;
  863. }
  864. }
  865. if(recurse && !explicitFollowSymlinks)
  866. {
  867. switch (status)
  868. {
  869. case cmPolicies::NEW:
  870. // Correct behavior, yay!
  871. break;
  872. case cmPolicies::OLD:
  873. // Probably not really the expected behavior, but the author explicitly
  874. // asked for the old behavior... no warning.
  875. case cmPolicies::WARN:
  876. // Possibly unexpected old behavior *and* we actually traversed
  877. // symlinks without being explicitly asked to: warn the author.
  878. if(g.GetFollowedSymlinkCount() != 0)
  879. {
  880. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
  881. this->Makefile->GetPolicies()->
  882. GetPolicyWarning(cmPolicies::CMP0009));
  883. }
  884. break;
  885. case cmPolicies::REQUIRED_IF_USED:
  886. case cmPolicies::REQUIRED_ALWAYS:
  887. this->SetError("policy CMP0009 error");
  888. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  889. this->Makefile->GetPolicies()->
  890. GetRequiredPolicyError(cmPolicies::CMP0009));
  891. return false;
  892. }
  893. }
  894. this->Makefile->AddDefinition(variable, output.c_str());
  895. return true;
  896. }
  897. //----------------------------------------------------------------------------
  898. bool cmFileCommand::HandleMakeDirectoryCommand(
  899. std::vector<std::string> const& args)
  900. {
  901. // File command has at least one argument
  902. assert(args.size() > 1);
  903. std::vector<std::string>::const_iterator i = args.begin();
  904. i++; // Get rid of subcommand
  905. std::string expr;
  906. for ( ; i != args.end(); ++i )
  907. {
  908. const std::string* cdir = &(*i);
  909. if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
  910. {
  911. expr = this->Makefile->GetCurrentDirectory();
  912. expr += "/" + *i;
  913. cdir = &expr;
  914. }
  915. if ( !this->Makefile->CanIWriteThisFile(cdir->c_str()) )
  916. {
  917. std::string e = "attempted to create a directory: " + *cdir
  918. + " into a source directory.";
  919. this->SetError(e);
  920. cmSystemTools::SetFatalErrorOccured();
  921. return false;
  922. }
  923. if ( !cmSystemTools::MakeDirectory(cdir->c_str()) )
  924. {
  925. std::string error = "problem creating directory: " + *cdir;
  926. this->SetError(error);
  927. return false;
  928. }
  929. }
  930. return true;
  931. }
  932. //----------------------------------------------------------------------------
  933. bool
  934. cmFileCommand::HandleDifferentCommand(std::vector<std::string> const& args)
  935. {
  936. /*
  937. FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
  938. */
  939. // Evaluate arguments.
  940. const char* file_lhs = 0;
  941. const char* file_rhs = 0;
  942. const char* var = 0;
  943. enum Doing { DoingNone, DoingVar, DoingFileLHS, DoingFileRHS };
  944. Doing doing = DoingVar;
  945. for(unsigned int i=1; i < args.size(); ++i)
  946. {
  947. if(args[i] == "FILES")
  948. {
  949. doing = DoingFileLHS;
  950. }
  951. else if(doing == DoingVar)
  952. {
  953. var = args[i].c_str();
  954. doing = DoingNone;
  955. }
  956. else if(doing == DoingFileLHS)
  957. {
  958. file_lhs = args[i].c_str();
  959. doing = DoingFileRHS;
  960. }
  961. else if(doing == DoingFileRHS)
  962. {
  963. file_rhs = args[i].c_str();
  964. doing = DoingNone;
  965. }
  966. else
  967. {
  968. std::ostringstream e;
  969. e << "DIFFERENT given unknown argument " << args[i];
  970. this->SetError(e.str());
  971. return false;
  972. }
  973. }
  974. if(!var)
  975. {
  976. this->SetError("DIFFERENT not given result variable name.");
  977. return false;
  978. }
  979. if(!file_lhs || !file_rhs)
  980. {
  981. this->SetError("DIFFERENT not given FILES option with two file names.");
  982. return false;
  983. }
  984. // Compare the files.
  985. const char* result =
  986. cmSystemTools::FilesDiffer(file_lhs, file_rhs)? "1" : "0";
  987. this->Makefile->AddDefinition(var, result);
  988. return true;
  989. }
  990. //----------------------------------------------------------------------------
  991. // File installation helper class.
  992. struct cmFileCopier
  993. {
  994. cmFileCopier(cmFileCommand* command, const char* name = "COPY"):
  995. FileCommand(command),
  996. Makefile(command->GetMakefile()),
  997. Name(name),
  998. Always(false),
  999. MatchlessFiles(true),
  1000. FilePermissions(0),
  1001. DirPermissions(0),
  1002. CurrentMatchRule(0),
  1003. UseGivenPermissionsFile(false),
  1004. UseGivenPermissionsDir(false),
  1005. UseSourcePermissions(true),
  1006. Doing(DoingNone)
  1007. {
  1008. }
  1009. virtual ~cmFileCopier() {}
  1010. bool Run(std::vector<std::string> const& args);
  1011. protected:
  1012. cmFileCommand* FileCommand;
  1013. cmMakefile* Makefile;
  1014. const char* Name;
  1015. bool Always;
  1016. cmFileTimeComparison FileTimes;
  1017. // Whether to install a file not matching any expression.
  1018. bool MatchlessFiles;
  1019. // Permissions for files and directories installed by this object.
  1020. mode_t FilePermissions;
  1021. mode_t DirPermissions;
  1022. // Properties set by pattern and regex match rules.
  1023. struct MatchProperties
  1024. {
  1025. bool Exclude;
  1026. mode_t Permissions;
  1027. MatchProperties(): Exclude(false), Permissions(0) {}
  1028. };
  1029. struct MatchRule;
  1030. friend struct MatchRule;
  1031. struct MatchRule
  1032. {
  1033. cmsys::RegularExpression Regex;
  1034. MatchProperties Properties;
  1035. std::string RegexString;
  1036. MatchRule(std::string const& regex):
  1037. Regex(regex.c_str()), RegexString(regex) {}
  1038. };
  1039. std::vector<MatchRule> MatchRules;
  1040. // Get the properties from rules matching this input file.
  1041. MatchProperties CollectMatchProperties(const char* file)
  1042. {
  1043. // Match rules are case-insensitive on some platforms.
  1044. #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
  1045. std::string lower = cmSystemTools::LowerCase(file);
  1046. const char* file_to_match = lower.c_str();
  1047. #else
  1048. const char* file_to_match = file;
  1049. #endif
  1050. // Collect properties from all matching rules.
  1051. bool matched = false;
  1052. MatchProperties result;
  1053. for(std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
  1054. mr != this->MatchRules.end(); ++mr)
  1055. {
  1056. if(mr->Regex.find(file_to_match))
  1057. {
  1058. matched = true;
  1059. result.Exclude |= mr->Properties.Exclude;
  1060. result.Permissions |= mr->Properties.Permissions;
  1061. }
  1062. }
  1063. if(!matched && !this->MatchlessFiles)
  1064. {
  1065. result.Exclude = !cmSystemTools::FileIsDirectory(file);
  1066. }
  1067. return result;
  1068. }
  1069. bool SetPermissions(const char* toFile, mode_t permissions)
  1070. {
  1071. if(permissions && !cmSystemTools::SetPermissions(toFile, permissions))
  1072. {
  1073. std::ostringstream e;
  1074. e << this->Name << " cannot set permissions on \"" << toFile << "\"";
  1075. this->FileCommand->SetError(e.str());
  1076. return false;
  1077. }
  1078. return true;
  1079. }
  1080. // Translate an argument to a permissions bit.
  1081. bool CheckPermissions(std::string const& arg, mode_t& permissions)
  1082. {
  1083. if(arg == "OWNER_READ") { permissions |= mode_owner_read; }
  1084. else if(arg == "OWNER_WRITE") { permissions |= mode_owner_write; }
  1085. else if(arg == "OWNER_EXECUTE") { permissions |= mode_owner_execute; }
  1086. else if(arg == "GROUP_READ") { permissions |= mode_group_read; }
  1087. else if(arg == "GROUP_WRITE") { permissions |= mode_group_write; }
  1088. else if(arg == "GROUP_EXECUTE") { permissions |= mode_group_execute; }
  1089. else if(arg == "WORLD_READ") { permissions |= mode_world_read; }
  1090. else if(arg == "WORLD_WRITE") { permissions |= mode_world_write; }
  1091. else if(arg == "WORLD_EXECUTE") { permissions |= mode_world_execute; }
  1092. else if(arg == "SETUID") { permissions |= mode_setuid; }
  1093. else if(arg == "SETGID") { permissions |= mode_setgid; }
  1094. else
  1095. {
  1096. std::ostringstream e;
  1097. e << this->Name << " given invalid permission \"" << arg << "\".";
  1098. this->FileCommand->SetError(e.str());
  1099. return false;
  1100. }
  1101. return true;
  1102. }
  1103. bool InstallSymlink(const char* fromFile, const char* toFile);
  1104. bool InstallFile(const char* fromFile, const char* toFile,
  1105. MatchProperties const& match_properties);
  1106. bool InstallDirectory(const char* source, const char* destination,
  1107. MatchProperties const& match_properties);
  1108. virtual bool Install(const char* fromFile, const char* toFile);
  1109. virtual std::string const& ToName(std::string const& fromName)
  1110. { return fromName; }
  1111. enum Type
  1112. {
  1113. TypeFile,
  1114. TypeDir,
  1115. TypeLink
  1116. };
  1117. virtual void ReportCopy(const char*, Type, bool) {}
  1118. virtual bool ReportMissing(const char* fromFile)
  1119. {
  1120. // The input file does not exist and installation is not optional.
  1121. std::ostringstream e;
  1122. e << this->Name << " cannot find \"" << fromFile << "\".";
  1123. this->FileCommand->SetError(e.str());
  1124. return false;
  1125. }
  1126. MatchRule* CurrentMatchRule;
  1127. bool UseGivenPermissionsFile;
  1128. bool UseGivenPermissionsDir;
  1129. bool UseSourcePermissions;
  1130. std::string Destination;
  1131. std::vector<std::string> Files;
  1132. int Doing;
  1133. virtual bool Parse(std::vector<std::string> const& args);
  1134. enum
  1135. {
  1136. DoingNone,
  1137. DoingError,
  1138. DoingDestination,
  1139. DoingFiles,
  1140. DoingPattern,
  1141. DoingRegex,
  1142. DoingPermissionsFile,
  1143. DoingPermissionsDir,
  1144. DoingPermissionsMatch,
  1145. DoingLast1
  1146. };
  1147. virtual bool CheckKeyword(std::string const& arg);
  1148. virtual bool CheckValue(std::string const& arg);
  1149. void NotBeforeMatch(std::string const& arg)
  1150. {
  1151. std::ostringstream e;
  1152. e << "option " << arg << " may not appear before PATTERN or REGEX.";
  1153. this->FileCommand->SetError(e.str());
  1154. this->Doing = DoingError;
  1155. }
  1156. void NotAfterMatch(std::string const& arg)
  1157. {
  1158. std::ostringstream e;
  1159. e << "option " << arg << " may not appear after PATTERN or REGEX.";
  1160. this->FileCommand->SetError(e.str());
  1161. this->Doing = DoingError;
  1162. }
  1163. virtual void DefaultFilePermissions()
  1164. {
  1165. // Use read/write permissions.
  1166. this->FilePermissions = 0;
  1167. this->FilePermissions |= mode_owner_read;
  1168. this->FilePermissions |= mode_owner_write;
  1169. this->FilePermissions |= mode_group_read;
  1170. this->FilePermissions |= mode_world_read;
  1171. }
  1172. virtual void DefaultDirectoryPermissions()
  1173. {
  1174. // Use read/write/executable permissions.
  1175. this->DirPermissions = 0;
  1176. this->DirPermissions |= mode_owner_read;
  1177. this->DirPermissions |= mode_owner_write;
  1178. this->DirPermissions |= mode_owner_execute;
  1179. this->DirPermissions |= mode_group_read;
  1180. this->DirPermissions |= mode_group_execute;
  1181. this->DirPermissions |= mode_world_read;
  1182. this->DirPermissions |= mode_world_execute;
  1183. }
  1184. };
  1185. //----------------------------------------------------------------------------
  1186. bool cmFileCopier::Parse(std::vector<std::string> const& args)
  1187. {
  1188. this->Doing = DoingFiles;
  1189. for(unsigned int i=1; i < args.size(); ++i)
  1190. {
  1191. // Check this argument.
  1192. if(!this->CheckKeyword(args[i]) &&
  1193. !this->CheckValue(args[i]))
  1194. {
  1195. std::ostringstream e;
  1196. e << "called with unknown argument \"" << args[i] << "\".";
  1197. this->FileCommand->SetError(e.str());
  1198. return false;
  1199. }
  1200. // Quit if an argument is invalid.
  1201. if(this->Doing == DoingError)
  1202. {
  1203. return false;
  1204. }
  1205. }
  1206. // Require a destination.
  1207. if(this->Destination.empty())
  1208. {
  1209. std::ostringstream e;
  1210. e << this->Name << " given no DESTINATION";
  1211. this->FileCommand->SetError(e.str());
  1212. return false;
  1213. }
  1214. // If file permissions were not specified set default permissions.
  1215. if(!this->UseGivenPermissionsFile && !this->UseSourcePermissions)
  1216. {
  1217. this->DefaultFilePermissions();
  1218. }
  1219. // If directory permissions were not specified set default permissions.
  1220. if(!this->UseGivenPermissionsDir && !this->UseSourcePermissions)
  1221. {
  1222. this->DefaultDirectoryPermissions();
  1223. }
  1224. return true;
  1225. }
  1226. //----------------------------------------------------------------------------
  1227. bool cmFileCopier::CheckKeyword(std::string const& arg)
  1228. {
  1229. if(arg == "DESTINATION")
  1230. {
  1231. if(this->CurrentMatchRule)
  1232. {
  1233. this->NotAfterMatch(arg);
  1234. }
  1235. else
  1236. {
  1237. this->Doing = DoingDestination;
  1238. }
  1239. }
  1240. else if(arg == "PATTERN")
  1241. {
  1242. this->Doing = DoingPattern;
  1243. }
  1244. else if(arg == "REGEX")
  1245. {
  1246. this->Doing = DoingRegex;
  1247. }
  1248. else if(arg == "EXCLUDE")
  1249. {
  1250. // Add this property to the current match rule.
  1251. if(this->CurrentMatchRule)
  1252. {
  1253. this->CurrentMatchRule->Properties.Exclude = true;
  1254. this->Doing = DoingNone;
  1255. }
  1256. else
  1257. {
  1258. this->NotBeforeMatch(arg);
  1259. }
  1260. }
  1261. else if(arg == "PERMISSIONS")
  1262. {
  1263. if(this->CurrentMatchRule)
  1264. {
  1265. this->Doing = DoingPermissionsMatch;
  1266. }
  1267. else
  1268. {
  1269. this->NotBeforeMatch(arg);
  1270. }
  1271. }
  1272. else if(arg == "FILE_PERMISSIONS")
  1273. {
  1274. if(this->CurrentMatchRule)
  1275. {
  1276. this->NotAfterMatch(arg);
  1277. }
  1278. else
  1279. {
  1280. this->Doing = DoingPermissionsFile;
  1281. this->UseGivenPermissionsFile = true;
  1282. }
  1283. }
  1284. else if(arg == "DIRECTORY_PERMISSIONS")
  1285. {
  1286. if(this->CurrentMatchRule)
  1287. {
  1288. this->NotAfterMatch(arg);
  1289. }
  1290. else
  1291. {
  1292. this->Doing = DoingPermissionsDir;
  1293. this->UseGivenPermissionsDir = true;
  1294. }
  1295. }
  1296. else if(arg == "USE_SOURCE_PERMISSIONS")
  1297. {
  1298. if(this->CurrentMatchRule)
  1299. {
  1300. this->NotAfterMatch(arg);
  1301. }
  1302. else
  1303. {
  1304. this->Doing = DoingNone;
  1305. this->UseSourcePermissions = true;
  1306. }
  1307. }
  1308. else if(arg == "NO_SOURCE_PERMISSIONS")
  1309. {
  1310. if(this->CurrentMatchRule)
  1311. {
  1312. this->NotAfterMatch(arg);
  1313. }
  1314. else
  1315. {
  1316. this->Doing = DoingNone;
  1317. this->UseSourcePermissions = false;
  1318. }
  1319. }
  1320. else if(arg == "FILES_MATCHING")
  1321. {
  1322. if(this->CurrentMatchRule)
  1323. {
  1324. this->NotAfterMatch(arg);
  1325. }
  1326. else
  1327. {
  1328. this->Doing = DoingNone;
  1329. this->MatchlessFiles = false;
  1330. }
  1331. }
  1332. else
  1333. {
  1334. return false;
  1335. }
  1336. return true;
  1337. }
  1338. //----------------------------------------------------------------------------
  1339. bool cmFileCopier::CheckValue(std::string const& arg)
  1340. {
  1341. switch(this->Doing)
  1342. {
  1343. case DoingFiles:
  1344. if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
  1345. {
  1346. this->Files.push_back(arg);
  1347. }
  1348. else
  1349. {
  1350. std::string file = this->Makefile->GetCurrentDirectory();
  1351. file += "/" + arg;
  1352. this->Files.push_back(file);
  1353. }
  1354. break;
  1355. case DoingDestination:
  1356. if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
  1357. {
  1358. this->Destination = arg;
  1359. }
  1360. else
  1361. {
  1362. this->Destination = this->Makefile->GetCurrentOutputDirectory();
  1363. this->Destination += "/" + arg;
  1364. }
  1365. this->Doing = DoingNone;
  1366. break;
  1367. case DoingPattern:
  1368. {
  1369. // Convert the pattern to a regular expression. Require a
  1370. // leading slash and trailing end-of-string in the matched
  1371. // string to make sure the pattern matches only whole file
  1372. // names.
  1373. std::string regex = "/";
  1374. regex += cmsys::Glob::PatternToRegex(arg, false);
  1375. regex += "$";
  1376. this->MatchRules.push_back(MatchRule(regex));
  1377. this->CurrentMatchRule = &*(this->MatchRules.end()-1);
  1378. if(this->CurrentMatchRule->Regex.is_valid())
  1379. {
  1380. this->Doing = DoingNone;
  1381. }
  1382. else
  1383. {
  1384. std::ostringstream e;
  1385. e << "could not compile PATTERN \"" << arg << "\".";
  1386. this->FileCommand->SetError(e.str());
  1387. this->Doing = DoingError;
  1388. }
  1389. }
  1390. break;
  1391. case DoingRegex:
  1392. this->MatchRules.push_back(MatchRule(arg));
  1393. this->CurrentMatchRule = &*(this->MatchRules.end()-1);
  1394. if(this->CurrentMatchRule->Regex.is_valid())
  1395. {
  1396. this->Doing = DoingNone;
  1397. }
  1398. else
  1399. {
  1400. std::ostringstream e;
  1401. e << "could not compile REGEX \"" << arg << "\".";
  1402. this->FileCommand->SetError(e.str());
  1403. this->Doing = DoingError;
  1404. }
  1405. break;
  1406. case DoingPermissionsFile:
  1407. if(!this->CheckPermissions(arg, this->FilePermissions))
  1408. {
  1409. this->Doing = DoingError;
  1410. }
  1411. break;
  1412. case DoingPermissionsDir:
  1413. if(!this->CheckPermissions(arg, this->DirPermissions))
  1414. {
  1415. this->Doing = DoingError;
  1416. }
  1417. break;
  1418. case DoingPermissionsMatch:
  1419. if(!this->CheckPermissions(
  1420. arg, this->CurrentMatchRule->Properties.Permissions))
  1421. {
  1422. this->Doing = DoingError;
  1423. }
  1424. break;
  1425. default:
  1426. return false;
  1427. }
  1428. return true;
  1429. }
  1430. //----------------------------------------------------------------------------
  1431. bool cmFileCopier::Run(std::vector<std::string> const& args)
  1432. {
  1433. if(!this->Parse(args))
  1434. {
  1435. return false;
  1436. }
  1437. std::vector<std::string> const& files = this->Files;
  1438. for(std::vector<std::string>::size_type i = 0; i < files.size(); ++i)
  1439. {
  1440. // Split the input file into its directory and name components.
  1441. std::vector<std::string> fromPathComponents;
  1442. cmSystemTools::SplitPath(files[i], fromPathComponents);
  1443. std::string fromName = *(fromPathComponents.end()-1);
  1444. std::string fromDir = cmSystemTools::JoinPath(fromPathComponents.begin(),
  1445. fromPathComponents.end()-1);
  1446. // Compute the full path to the destination file.
  1447. std::string toFile = this->Destination;
  1448. std::string const& toName = this->ToName(fromName);
  1449. if(!toName.empty())
  1450. {
  1451. toFile += "/";
  1452. toFile += toName;
  1453. }
  1454. // Construct the full path to the source file. The file name may
  1455. // have been changed above.
  1456. std::string fromFile = fromDir;
  1457. if(!fromName.empty())
  1458. {
  1459. fromFile += "/";
  1460. fromFile += fromName;
  1461. }
  1462. if(!this->Install(fromFile.c_str(), toFile.c_str()))
  1463. {
  1464. return false;
  1465. }
  1466. }
  1467. return true;
  1468. }
  1469. //----------------------------------------------------------------------------
  1470. bool cmFileCopier::Install(const char* fromFile, const char* toFile)
  1471. {
  1472. if(!*fromFile)
  1473. {
  1474. std::ostringstream e;
  1475. e << "INSTALL encountered an empty string input file name.";
  1476. this->FileCommand->SetError(e.str());
  1477. return false;
  1478. }
  1479. // Collect any properties matching this file name.
  1480. MatchProperties match_properties = this->CollectMatchProperties(fromFile);
  1481. // Skip the file if it is excluded.
  1482. if(match_properties.Exclude)
  1483. {
  1484. return true;
  1485. }
  1486. if(cmSystemTools::SameFile(fromFile, toFile))
  1487. {
  1488. return true;
  1489. }
  1490. else if(cmSystemTools::FileIsSymlink(fromFile))
  1491. {
  1492. return this->InstallSymlink(fromFile, toFile);
  1493. }
  1494. else if(cmSystemTools::FileIsDirectory(fromFile))
  1495. {
  1496. return this->InstallDirectory(fromFile, toFile, match_properties);
  1497. }
  1498. else if(cmSystemTools::FileExists(fromFile))
  1499. {
  1500. return this->InstallFile(fromFile, toFile, match_properties);
  1501. }
  1502. return this->ReportMissing(fromFile);
  1503. }
  1504. //----------------------------------------------------------------------------
  1505. bool cmFileCopier::InstallSymlink(const char* fromFile, const char* toFile)
  1506. {
  1507. // Read the original symlink.
  1508. std::string symlinkTarget;
  1509. if(!cmSystemTools::ReadSymlink(fromFile, symlinkTarget))
  1510. {
  1511. std::ostringstream e;
  1512. e << this->Name << " cannot read symlink \"" << fromFile
  1513. << "\" to duplicate at \"" << toFile << "\".";
  1514. this->FileCommand->SetError(e.str());
  1515. return false;
  1516. }
  1517. // Compare the symlink value to that at the destination if not
  1518. // always installing.
  1519. bool copy = true;
  1520. if(!this->Always)
  1521. {
  1522. std::string oldSymlinkTarget;
  1523. if(cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget))
  1524. {
  1525. if(symlinkTarget == oldSymlinkTarget)
  1526. {
  1527. copy = false;
  1528. }
  1529. }
  1530. }
  1531. // Inform the user about this file installation.
  1532. this->ReportCopy(toFile, TypeLink, copy);
  1533. if(copy)
  1534. {
  1535. // Remove the destination file so we can always create the symlink.
  1536. cmSystemTools::RemoveFile(toFile);
  1537. // Create the symlink.
  1538. if(!cmSystemTools::CreateSymlink(symlinkTarget, toFile))
  1539. {
  1540. std::ostringstream e;
  1541. e << this->Name << " cannot duplicate symlink \"" << fromFile
  1542. << "\" at \"" << toFile << "\".";
  1543. this->FileCommand->SetError(e.str());
  1544. return false;
  1545. }
  1546. }
  1547. return true;
  1548. }
  1549. //----------------------------------------------------------------------------
  1550. bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile,
  1551. MatchProperties const& match_properties)
  1552. {
  1553. // Determine whether we will copy the file.
  1554. bool copy = true;
  1555. if(!this->Always)
  1556. {
  1557. // If both files exist with the same time do not copy.
  1558. if(!this->FileTimes.FileTimesDiffer(fromFile, toFile))
  1559. {
  1560. copy = false;
  1561. }
  1562. }
  1563. // Inform the user about this file installation.
  1564. this->ReportCopy(toFile, TypeFile, copy);
  1565. // Copy the file.
  1566. if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true))
  1567. {
  1568. std::ostringstream e;
  1569. e << this->Name << " cannot copy file \"" << fromFile
  1570. << "\" to \"" << toFile << "\".";
  1571. this->FileCommand->SetError(e.str());
  1572. return false;
  1573. }
  1574. // Set the file modification time of the destination file.
  1575. if(copy && !this->Always)
  1576. {
  1577. // Add write permission so we can set the file time.
  1578. // Permissions are set unconditionally below anyway.
  1579. mode_t perm = 0;
  1580. if(cmSystemTools::GetPermissions(toFile, perm))
  1581. {
  1582. cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
  1583. }
  1584. if (!cmSystemTools::CopyFileTime(fromFile, toFile))
  1585. {
  1586. std::ostringstream e;
  1587. e << this->Name << " cannot set modification time on \""
  1588. << toFile << "\"";
  1589. this->FileCommand->SetError(e.str());
  1590. return false;
  1591. }
  1592. }
  1593. // Set permissions of the destination file.
  1594. mode_t permissions = (match_properties.Permissions?
  1595. match_properties.Permissions : this->FilePermissions);
  1596. if(!permissions)
  1597. {
  1598. // No permissions were explicitly provided but the user requested
  1599. // that the source file permissions be used.
  1600. cmSystemTools::GetPermissions(fromFile, permissions);
  1601. }
  1602. return this->SetPermissions(toFile, permissions);
  1603. }
  1604. //----------------------------------------------------------------------------
  1605. bool cmFileCopier::InstallDirectory(const char* source,
  1606. const char* destination,
  1607. MatchProperties const& match_properties)
  1608. {
  1609. // Inform the user about this directory installation.
  1610. this->ReportCopy(destination, TypeDir,
  1611. !cmSystemTools::FileIsDirectory(destination));
  1612. // Make sure the destination directory exists.
  1613. if(!cmSystemTools::MakeDirectory(destination))
  1614. {
  1615. std::ostringstream e;
  1616. e << this->Name << " cannot make directory \"" << destination << "\": "
  1617. << cmSystemTools::GetLastSystemError();
  1618. this->FileCommand->SetError(e.str());
  1619. return false;
  1620. }
  1621. // Compute the requested permissions for the destination directory.
  1622. mode_t permissions = (match_properties.Permissions?
  1623. match_properties.Permissions : this->DirPermissions);
  1624. if(!permissions)
  1625. {
  1626. // No permissions were explicitly provided but the user requested
  1627. // that the source directory permissions be used.
  1628. cmSystemTools::GetPermissions(source, permissions);
  1629. }
  1630. // Compute the set of permissions required on this directory to
  1631. // recursively install files and subdirectories safely.
  1632. mode_t required_permissions =
  1633. mode_owner_read | mode_owner_write | mode_owner_execute;
  1634. // If the required permissions are specified it is safe to set the
  1635. // final permissions now. Otherwise we must add the required
  1636. // permissions temporarily during file installation.
  1637. mode_t permissions_before = 0;
  1638. mode_t permissions_after = 0;
  1639. if((permissions & required_permissions) == required_permissions)
  1640. {
  1641. permissions_before = permissions;
  1642. }
  1643. else
  1644. {
  1645. permissions_before = permissions | required_permissions;
  1646. permissions_after = permissions;
  1647. }
  1648. // Set the required permissions of the destination directory.
  1649. if(!this->SetPermissions(destination, permissions_before))
  1650. {
  1651. return false;
  1652. }
  1653. // Load the directory contents to traverse it recursively.
  1654. cmsys::Directory dir;
  1655. if(source && *source)
  1656. {
  1657. dir.Load(source);
  1658. }
  1659. unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
  1660. for(unsigned long fileNum = 0; fileNum < numFiles; ++fileNum)
  1661. {
  1662. if(!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
  1663. strcmp(dir.GetFile(fileNum), "..") == 0))
  1664. {
  1665. cmsys_stl::string fromPath = source;
  1666. fromPath += "/";
  1667. fromPath += dir.GetFile(fileNum);
  1668. std::string toPath = destination;
  1669. toPath += "/";
  1670. toPath += dir.GetFile(fileNum);
  1671. if(!this->Install(fromPath.c_str(), toPath.c_str()))
  1672. {
  1673. return false;
  1674. }
  1675. }
  1676. }
  1677. // Set the requested permissions of the destination directory.
  1678. return this->SetPermissions(destination, permissions_after);
  1679. }
  1680. //----------------------------------------------------------------------------
  1681. bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
  1682. {
  1683. cmFileCopier copier(this);
  1684. return copier.Run(args);
  1685. }
  1686. //----------------------------------------------------------------------------
  1687. struct cmFileInstaller: public cmFileCopier
  1688. {
  1689. cmFileInstaller(cmFileCommand* command):
  1690. cmFileCopier(command, "INSTALL"),
  1691. InstallType(cmInstallType_FILES),
  1692. Optional(false),
  1693. MessageAlways(false),
  1694. MessageLazy(false),
  1695. MessageNever(false),
  1696. DestDirLength(0)
  1697. {
  1698. // Installation does not use source permissions by default.
  1699. this->UseSourcePermissions = false;
  1700. // Check whether to copy files always or only if they have changed.
  1701. this->Always =
  1702. cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS"));
  1703. // Get the current manifest.
  1704. this->Manifest =
  1705. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
  1706. }
  1707. ~cmFileInstaller()
  1708. {
  1709. // Save the updated install manifest.
  1710. this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
  1711. this->Manifest.c_str());
  1712. }
  1713. protected:
  1714. cmInstallType InstallType;
  1715. bool Optional;
  1716. bool MessageAlways;
  1717. bool MessageLazy;
  1718. bool MessageNever;
  1719. int DestDirLength;
  1720. std::string Rename;
  1721. std::string Manifest;
  1722. void ManifestAppend(std::string const& file)
  1723. {
  1724. this->Manifest += ";";
  1725. this->Manifest += file.substr(this->DestDirLength);
  1726. }
  1727. virtual std::string const& ToName(std::string const& fromName)
  1728. { return this->Rename.empty()? fromName : this->Rename; }
  1729. virtual void ReportCopy(const char* toFile, Type type, bool copy)
  1730. {
  1731. if(!this->MessageNever && (copy || !this->MessageLazy))
  1732. {
  1733. std::string message = (copy? "Installing: " : "Up-to-date: ");
  1734. message += toFile;
  1735. this->Makefile->DisplayStatus(message.c_str(), -1);
  1736. }
  1737. if(type != TypeDir)
  1738. {
  1739. // Add the file to the manifest.
  1740. this->ManifestAppend(toFile);
  1741. }
  1742. }
  1743. virtual bool ReportMissing(const char* fromFile)
  1744. {
  1745. return (this->Optional ||
  1746. this->cmFileCopier::ReportMissing(fromFile));
  1747. }
  1748. virtual bool Install(const char* fromFile, const char* toFile)
  1749. {
  1750. // Support installing from empty source to make a directory.
  1751. if(this->InstallType == cmInstallType_DIRECTORY && !*fromFile)
  1752. {
  1753. return this->InstallDirectory(fromFile, toFile, MatchProperties());
  1754. }
  1755. return this->cmFileCopier::Install(fromFile, toFile);
  1756. }
  1757. virtual bool Parse(std::vector<std::string> const& args);
  1758. enum
  1759. {
  1760. DoingType = DoingLast1,
  1761. DoingRename,
  1762. DoingLast2
  1763. };
  1764. virtual bool CheckKeyword(std::string const& arg);
  1765. virtual bool CheckValue(std::string const& arg);
  1766. virtual void DefaultFilePermissions()
  1767. {
  1768. this->cmFileCopier::DefaultFilePermissions();
  1769. // Add execute permissions based on the target type.
  1770. switch(this->InstallType)
  1771. {
  1772. case cmInstallType_SHARED_LIBRARY:
  1773. case cmInstallType_MODULE_LIBRARY:
  1774. if(this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE"))
  1775. {
  1776. break;
  1777. }
  1778. case cmInstallType_EXECUTABLE:
  1779. case cmInstallType_PROGRAMS:
  1780. this->FilePermissions |= mode_owner_execute;
  1781. this->FilePermissions |= mode_group_execute;
  1782. this->FilePermissions |= mode_world_execute;
  1783. break;
  1784. default: break;
  1785. }
  1786. }
  1787. bool GetTargetTypeFromString(const std::string& stype);
  1788. bool HandleInstallDestination();
  1789. };
  1790. //----------------------------------------------------------------------------
  1791. bool cmFileInstaller::Parse(std::vector<std::string> const& args)
  1792. {
  1793. if(!this->cmFileCopier::Parse(args))
  1794. {
  1795. return false;
  1796. }
  1797. if(!this->Rename.empty())
  1798. {
  1799. if(this->InstallType != cmInstallType_FILES &&
  1800. this->InstallType != cmInstallType_PROGRAMS)
  1801. {
  1802. this->FileCommand->SetError("INSTALL option RENAME may be used "
  1803. "only with FILES or PROGRAMS.");
  1804. return false;
  1805. }
  1806. if(this->Files.size() > 1)
  1807. {
  1808. this->FileCommand->SetError("INSTALL option RENAME may be used "
  1809. "only with one file.");
  1810. return false;
  1811. }
  1812. }
  1813. if(!this->HandleInstallDestination())
  1814. {
  1815. return false;
  1816. }
  1817. if(((this->MessageAlways?1:0) +
  1818. (this->MessageLazy?1:0) +
  1819. (this->MessageNever?1:0)) > 1)
  1820. {
  1821. this->FileCommand->SetError("INSTALL options MESSAGE_ALWAYS, "
  1822. "MESSAGE_LAZY, and MESSAGE_NEVER "
  1823. "are mutually exclusive.");
  1824. return false;
  1825. }
  1826. return true;
  1827. }
  1828. //----------------------------------------------------------------------------
  1829. bool cmFileInstaller::CheckKeyword(std::string const& arg)
  1830. {
  1831. if(arg == "TYPE")
  1832. {
  1833. if(this->CurrentMatchRule)
  1834. {
  1835. this->NotAfterMatch(arg);
  1836. }
  1837. else
  1838. {
  1839. this->Doing = DoingType;
  1840. }
  1841. }
  1842. else if(arg == "FILES")
  1843. {
  1844. if(this->CurrentMatchRule)
  1845. {
  1846. this->NotAfterMatch(arg);
  1847. }
  1848. else
  1849. {
  1850. this->Doing = DoingFiles;
  1851. }
  1852. }
  1853. else if(arg == "RENAME")
  1854. {
  1855. if(this->CurrentMatchRule)
  1856. {
  1857. this->NotAfterMatch(arg);
  1858. }
  1859. else
  1860. {
  1861. this->Doing = DoingRename;
  1862. }
  1863. }
  1864. else if(arg == "OPTIONAL")
  1865. {
  1866. if(this->CurrentMatchRule)
  1867. {
  1868. this->NotAfterMatch(arg);
  1869. }
  1870. else
  1871. {
  1872. this->Doing = DoingNone;
  1873. this->Optional = true;
  1874. }
  1875. }
  1876. else if(arg == "MESSAGE_ALWAYS")
  1877. {
  1878. if(this->CurrentMatchRule)
  1879. {
  1880. this->NotAfterMatch(arg);
  1881. }
  1882. else
  1883. {
  1884. this->Doing = DoingNone;
  1885. this->MessageAlways = true;
  1886. }
  1887. }
  1888. else if(arg == "MESSAGE_LAZY")
  1889. {
  1890. if(this->CurrentMatchRule)
  1891. {
  1892. this->NotAfterMatch(arg);
  1893. }
  1894. else
  1895. {
  1896. this->Doing = DoingNone;
  1897. this->MessageLazy = true;
  1898. }
  1899. }
  1900. else if(arg == "MESSAGE_NEVER")
  1901. {
  1902. if(this->CurrentMatchRule)
  1903. {
  1904. this->NotAfterMatch(arg);
  1905. }
  1906. else
  1907. {
  1908. this->Doing = DoingNone;
  1909. this->MessageNever = true;
  1910. }
  1911. }
  1912. else if(arg == "PERMISSIONS")
  1913. {
  1914. if(this->CurrentMatchRule)
  1915. {
  1916. this->Doing = DoingPermissionsMatch;
  1917. }
  1918. else
  1919. {
  1920. // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
  1921. this->Doing = DoingPermissionsFile;
  1922. this->UseGivenPermissionsFile = true;
  1923. }
  1924. }
  1925. else if(arg == "DIR_PERMISSIONS")
  1926. {
  1927. if(this->CurrentMatchRule)
  1928. {
  1929. this->NotAfterMatch(arg);
  1930. }
  1931. else
  1932. {
  1933. // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
  1934. this->Doing = DoingPermissionsDir;
  1935. this->UseGivenPermissionsDir = true;
  1936. }
  1937. }
  1938. else if(arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
  1939. arg == "PROPERTIES")
  1940. {
  1941. std::ostringstream e;
  1942. e << "INSTALL called with old-style " << arg << " argument. "
  1943. << "This script was generated with an older version of CMake. "
  1944. << "Re-run this cmake version on your build tree.";
  1945. this->FileCommand->SetError(e.str());
  1946. this->Doing = DoingError;
  1947. }
  1948. else
  1949. {
  1950. return this->cmFileCopier::CheckKeyword(arg);
  1951. }
  1952. return true;
  1953. }
  1954. //----------------------------------------------------------------------------
  1955. bool cmFileInstaller::CheckValue(std::string const& arg)
  1956. {
  1957. switch(this->Doing)
  1958. {
  1959. case DoingType:
  1960. if(!this->GetTargetTypeFromString(arg))
  1961. {
  1962. this->Doing = DoingError;
  1963. }
  1964. break;
  1965. case DoingRename:
  1966. this->Rename = arg;
  1967. break;
  1968. default:
  1969. return this->cmFileCopier::CheckValue(arg);
  1970. }
  1971. return true;
  1972. }
  1973. //----------------------------------------------------------------------------
  1974. bool cmFileInstaller
  1975. ::GetTargetTypeFromString(const std::string& stype)
  1976. {
  1977. if ( stype == "EXECUTABLE" )
  1978. {
  1979. this->InstallType = cmInstallType_EXECUTABLE;
  1980. }
  1981. else if ( stype == "FILE" )
  1982. {
  1983. this->InstallType = cmInstallType_FILES;
  1984. }
  1985. else if ( stype == "PROGRAM" )
  1986. {
  1987. this->InstallType = cmInstallType_PROGRAMS;
  1988. }
  1989. else if ( stype == "STATIC_LIBRARY" )
  1990. {
  1991. this->InstallType = cmInstallType_STATIC_LIBRARY;
  1992. }
  1993. else if ( stype == "SHARED_LIBRARY" )
  1994. {
  1995. this->InstallType = cmInstallType_SHARED_LIBRARY;
  1996. }
  1997. else if ( stype == "MODULE" )
  1998. {
  1999. this->InstallType = cmInstallType_MODULE_LIBRARY;
  2000. }
  2001. else if ( stype == "DIRECTORY" )
  2002. {
  2003. this->InstallType = cmInstallType_DIRECTORY;
  2004. }
  2005. else
  2006. {
  2007. std::ostringstream e;
  2008. e << "Option TYPE given unknown value \"" << stype << "\".";
  2009. this->FileCommand->SetError(e.str());
  2010. return false;
  2011. }
  2012. return true;
  2013. }
  2014. //----------------------------------------------------------------------------
  2015. bool cmFileInstaller::HandleInstallDestination()
  2016. {
  2017. std::string& destination = this->Destination;
  2018. // allow for / to be a valid destination
  2019. if ( destination.size() < 2 && destination != "/" )
  2020. {
  2021. this->FileCommand->SetError("called with inappropriate arguments. "
  2022. "No DESTINATION provided or .");
  2023. return false;
  2024. }
  2025. const char* destdir = cmSystemTools::GetEnv("DESTDIR");
  2026. if ( destdir && *destdir )
  2027. {
  2028. std::string sdestdir = destdir;
  2029. cmSystemTools::ConvertToUnixSlashes(sdestdir);
  2030. char ch1 = destination[0];
  2031. char ch2 = destination[1];
  2032. char ch3 = 0;
  2033. if ( destination.size() > 2 )
  2034. {
  2035. ch3 = destination[2];
  2036. }
  2037. int skip = 0;
  2038. if ( ch1 != '/' )
  2039. {
  2040. int relative = 0;
  2041. if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
  2042. ch2 == ':' )
  2043. {
  2044. // Assume windows
  2045. // let's do some destdir magic:
  2046. skip = 2;
  2047. if ( ch3 != '/' )
  2048. {
  2049. relative = 1;
  2050. }
  2051. }
  2052. else
  2053. {
  2054. relative = 1;
  2055. }
  2056. if ( relative )
  2057. {
  2058. // This is relative path on unix or windows. Since we are doing
  2059. // destdir, this case does not make sense.
  2060. this->FileCommand->SetError(
  2061. "called with relative DESTINATION. This "
  2062. "does not make sense when using DESTDIR. Specify "
  2063. "absolute path or remove DESTDIR environment variable.");
  2064. return false;
  2065. }
  2066. }
  2067. else
  2068. {
  2069. if ( ch2 == '/' )
  2070. {
  2071. // looks like a network path.
  2072. std::string message = "called with network path DESTINATION. This "
  2073. "does not make sense when using DESTDIR. Specify local "
  2074. "absolute path or remove DESTDIR environment variable."
  2075. "\nDESTINATION=\n";
  2076. message += destination;
  2077. this->FileCommand->SetError(message);
  2078. return false;
  2079. }
  2080. }
  2081. destination = sdestdir + (destination.c_str() + skip);
  2082. this->DestDirLength = int(sdestdir.size());
  2083. }
  2084. if(this->InstallType != cmInstallType_DIRECTORY)
  2085. {
  2086. if ( !cmSystemTools::FileExists(destination.c_str()) )
  2087. {
  2088. if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
  2089. {
  2090. std::string errstring = "cannot create directory: " + destination +
  2091. ". Maybe need administrative privileges.";
  2092. this->FileCommand->SetError(errstring);
  2093. return false;
  2094. }
  2095. }
  2096. if ( !cmSystemTools::FileIsDirectory(destination) )
  2097. {
  2098. std::string errstring = "INSTALL destination: " + destination +
  2099. " is not a directory.";
  2100. this->FileCommand->SetError(errstring);
  2101. return false;
  2102. }
  2103. }
  2104. return true;
  2105. }
  2106. //----------------------------------------------------------------------------
  2107. bool
  2108. cmFileCommand::HandleRPathChangeCommand(std::vector<std::string> const& args)
  2109. {
  2110. // Evaluate arguments.
  2111. const char* file = 0;
  2112. const char* oldRPath = 0;
  2113. const char* newRPath = 0;
  2114. enum Doing { DoingNone, DoingFile, DoingOld, DoingNew };
  2115. Doing doing = DoingNone;
  2116. for(unsigned int i=1; i < args.size(); ++i)
  2117. {
  2118. if(args[i] == "OLD_RPATH")
  2119. {
  2120. doing = DoingOld;
  2121. }
  2122. else if(args[i] == "NEW_RPATH")
  2123. {
  2124. doing = DoingNew;
  2125. }
  2126. else if(args[i] == "FILE")
  2127. {
  2128. doing = DoingFile;
  2129. }
  2130. else if(doing == DoingFile)
  2131. {
  2132. file = args[i].c_str();
  2133. doing = DoingNone;
  2134. }
  2135. else if(doing == DoingOld)
  2136. {
  2137. oldRPath = args[i].c_str();
  2138. doing = DoingNone;
  2139. }
  2140. else if(doing == DoingNew)
  2141. {
  2142. newRPath = args[i].c_str();
  2143. doing = DoingNone;
  2144. }
  2145. else
  2146. {
  2147. std::ostringstream e;
  2148. e << "RPATH_CHANGE given unknown argument " << args[i];
  2149. this->SetError(e.str());
  2150. return false;
  2151. }
  2152. }
  2153. if(!file)
  2154. {
  2155. this->SetError("RPATH_CHANGE not given FILE option.");
  2156. return false;
  2157. }
  2158. if(!oldRPath)
  2159. {
  2160. this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
  2161. return false;
  2162. }
  2163. if(!newRPath)
  2164. {
  2165. this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
  2166. return false;
  2167. }
  2168. if(!cmSystemTools::FileExists(file, true))
  2169. {
  2170. std::ostringstream e;
  2171. e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
  2172. this->SetError(e.str());
  2173. return false;
  2174. }
  2175. bool success = true;
  2176. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  2177. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  2178. std::string emsg;
  2179. bool changed;
  2180. if(!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed))
  2181. {
  2182. std::ostringstream e;
  2183. e << "RPATH_CHANGE could not write new RPATH:\n"
  2184. << " " << newRPath << "\n"
  2185. << "to the file:\n"
  2186. << " " << file << "\n"
  2187. << emsg;
  2188. this->SetError(e.str());
  2189. success = false;
  2190. }
  2191. if(success)
  2192. {
  2193. if(changed)
  2194. {
  2195. std::string message = "Set runtime path of \"";
  2196. message += file;
  2197. message += "\" to \"";
  2198. message += newRPath;
  2199. message += "\"";
  2200. this->Makefile->DisplayStatus(message.c_str(), -1);
  2201. }
  2202. if(have_ft)
  2203. {
  2204. cmSystemTools::FileTimeSet(file, ft);
  2205. }
  2206. }
  2207. cmSystemTools::FileTimeDelete(ft);
  2208. return success;
  2209. }
  2210. //----------------------------------------------------------------------------
  2211. bool
  2212. cmFileCommand::HandleRPathRemoveCommand(std::vector<std::string> const& args)
  2213. {
  2214. // Evaluate arguments.
  2215. const char* file = 0;
  2216. enum Doing { DoingNone, DoingFile };
  2217. Doing doing = DoingNone;
  2218. for(unsigned int i=1; i < args.size(); ++i)
  2219. {
  2220. if(args[i] == "FILE")
  2221. {
  2222. doing = DoingFile;
  2223. }
  2224. else if(doing == DoingFile)
  2225. {
  2226. file = args[i].c_str();
  2227. doing = DoingNone;
  2228. }
  2229. else
  2230. {
  2231. std::ostringstream e;
  2232. e << "RPATH_REMOVE given unknown argument " << args[i];
  2233. this->SetError(e.str());
  2234. return false;
  2235. }
  2236. }
  2237. if(!file)
  2238. {
  2239. this->SetError("RPATH_REMOVE not given FILE option.");
  2240. return false;
  2241. }
  2242. if(!cmSystemTools::FileExists(file, true))
  2243. {
  2244. std::ostringstream e;
  2245. e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
  2246. this->SetError(e.str());
  2247. return false;
  2248. }
  2249. bool success = true;
  2250. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  2251. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  2252. std::string emsg;
  2253. bool removed;
  2254. if(!cmSystemTools::RemoveRPath(file, &emsg, &removed))
  2255. {
  2256. std::ostringstream e;
  2257. e << "RPATH_REMOVE could not remove RPATH from file:\n"
  2258. << " " << file << "\n"
  2259. << emsg;
  2260. this->SetError(e.str());
  2261. success = false;
  2262. }
  2263. if(success)
  2264. {
  2265. if(removed)
  2266. {
  2267. std::string message = "Removed runtime path from \"";
  2268. message += file;
  2269. message += "\"";
  2270. this->Makefile->DisplayStatus(message.c_str(), -1);
  2271. }
  2272. if(have_ft)
  2273. {
  2274. cmSystemTools::FileTimeSet(file, ft);
  2275. }
  2276. }
  2277. cmSystemTools::FileTimeDelete(ft);
  2278. return success;
  2279. }
  2280. //----------------------------------------------------------------------------
  2281. bool
  2282. cmFileCommand::HandleRPathCheckCommand(std::vector<std::string> const& args)
  2283. {
  2284. // Evaluate arguments.
  2285. const char* file = 0;
  2286. const char* rpath = 0;
  2287. enum Doing { DoingNone, DoingFile, DoingRPath };
  2288. Doing doing = DoingNone;
  2289. for(unsigned int i=1; i < args.size(); ++i)
  2290. {
  2291. if(args[i] == "RPATH")
  2292. {
  2293. doing = DoingRPath;
  2294. }
  2295. else if(args[i] == "FILE")
  2296. {
  2297. doing = DoingFile;
  2298. }
  2299. else if(doing == DoingFile)
  2300. {
  2301. file = args[i].c_str();
  2302. doing = DoingNone;
  2303. }
  2304. else if(doing == DoingRPath)
  2305. {
  2306. rpath = args[i].c_str();
  2307. doing = DoingNone;
  2308. }
  2309. else
  2310. {
  2311. std::ostringstream e;
  2312. e << "RPATH_CHECK given unknown argument " << args[i];
  2313. this->SetError(e.str());
  2314. return false;
  2315. }
  2316. }
  2317. if(!file)
  2318. {
  2319. this->SetError("RPATH_CHECK not given FILE option.");
  2320. return false;
  2321. }
  2322. if(!rpath)
  2323. {
  2324. this->SetError("RPATH_CHECK not given RPATH option.");
  2325. return false;
  2326. }
  2327. // If the file exists but does not have the desired RPath then
  2328. // delete it. This is used during installation to re-install a file
  2329. // if its RPath will change.
  2330. if(cmSystemTools::FileExists(file, true) &&
  2331. !cmSystemTools::CheckRPath(file, rpath))
  2332. {
  2333. cmSystemTools::RemoveFile(file);
  2334. }
  2335. return true;
  2336. }
  2337. //----------------------------------------------------------------------------
  2338. bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
  2339. {
  2340. cmFileInstaller installer(this);
  2341. return installer.Run(args);
  2342. }
  2343. //----------------------------------------------------------------------------
  2344. bool cmFileCommand::HandleRelativePathCommand(
  2345. std::vector<std::string> const& args)
  2346. {
  2347. if(args.size() != 4 )
  2348. {
  2349. this->SetError("RELATIVE_PATH called with incorrect number of arguments");
  2350. return false;
  2351. }
  2352. const std::string& outVar = args[1];
  2353. const std::string& directoryName = args[2];
  2354. const std::string& fileName = args[3];
  2355. if(!cmSystemTools::FileIsFullPath(directoryName.c_str()))
  2356. {
  2357. std::string errstring =
  2358. "RELATIVE_PATH must be passed a full path to the directory: "
  2359. + directoryName;
  2360. this->SetError(errstring);
  2361. return false;
  2362. }
  2363. if(!cmSystemTools::FileIsFullPath(fileName.c_str()))
  2364. {
  2365. std::string errstring =
  2366. "RELATIVE_PATH must be passed a full path to the file: "
  2367. + fileName;
  2368. this->SetError(errstring);
  2369. return false;
  2370. }
  2371. std::string res = cmSystemTools::RelativePath(directoryName.c_str(),
  2372. fileName.c_str());
  2373. this->Makefile->AddDefinition(outVar,
  2374. res.c_str());
  2375. return true;
  2376. }
  2377. //----------------------------------------------------------------------------
  2378. bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
  2379. {
  2380. if(args.size() != 3)
  2381. {
  2382. this->SetError("RENAME given incorrect number of arguments.");
  2383. return false;
  2384. }
  2385. // Compute full path for old and new names.
  2386. std::string oldname = args[1];
  2387. if(!cmsys::SystemTools::FileIsFullPath(oldname.c_str()))
  2388. {
  2389. oldname = this->Makefile->GetCurrentDirectory();
  2390. oldname += "/" + args[1];
  2391. }
  2392. std::string newname = args[2];
  2393. if(!cmsys::SystemTools::FileIsFullPath(newname.c_str()))
  2394. {
  2395. newname = this->Makefile->GetCurrentDirectory();
  2396. newname += "/" + args[2];
  2397. }
  2398. if(!cmSystemTools::RenameFile(oldname.c_str(), newname.c_str()))
  2399. {
  2400. std::string err = cmSystemTools::GetLastSystemError();
  2401. std::ostringstream e;
  2402. e << "RENAME failed to rename\n"
  2403. << " " << oldname << "\n"
  2404. << "to\n"
  2405. << " " << newname << "\n"
  2406. << "because: " << err << "\n";
  2407. this->SetError(e.str());
  2408. return false;
  2409. }
  2410. return true;
  2411. }
  2412. //----------------------------------------------------------------------------
  2413. bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
  2414. bool recurse)
  2415. {
  2416. std::string message;
  2417. std::vector<std::string>::const_iterator i = args.begin();
  2418. i++; // Get rid of subcommand
  2419. for(;i != args.end(); ++i)
  2420. {
  2421. std::string fileName = *i;
  2422. if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
  2423. {
  2424. fileName = this->Makefile->GetCurrentDirectory();
  2425. fileName += "/" + *i;
  2426. }
  2427. if(cmSystemTools::FileIsDirectory(fileName) &&
  2428. !cmSystemTools::FileIsSymlink(fileName) && recurse)
  2429. {
  2430. cmSystemTools::RemoveADirectory(fileName);
  2431. }
  2432. else
  2433. {
  2434. cmSystemTools::RemoveFile(fileName);
  2435. }
  2436. }
  2437. return true;
  2438. }
  2439. //----------------------------------------------------------------------------
  2440. bool cmFileCommand::HandleCMakePathCommand(std::vector<std::string>
  2441. const& args,
  2442. bool nativePath)
  2443. {
  2444. std::vector<std::string>::const_iterator i = args.begin();
  2445. if(args.size() != 3)
  2446. {
  2447. this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  2448. "called with exactly three arguments.");
  2449. return false;
  2450. }
  2451. i++; // Get rid of subcommand
  2452. #if defined(_WIN32) && !defined(__CYGWIN__)
  2453. char pathSep = ';';
  2454. #else
  2455. char pathSep = ':';
  2456. #endif
  2457. std::vector<cmsys::String> path = cmSystemTools::SplitString(*i,
  2458. pathSep);
  2459. i++;
  2460. const char* var = i->c_str();
  2461. std::string value;
  2462. for(std::vector<cmsys::String>::iterator j = path.begin();
  2463. j != path.end(); ++j)
  2464. {
  2465. if(j != path.begin())
  2466. {
  2467. value += ";";
  2468. }
  2469. if(!nativePath)
  2470. {
  2471. cmSystemTools::ConvertToUnixSlashes(*j);
  2472. }
  2473. else
  2474. {
  2475. *j = cmSystemTools::ConvertToOutputPath(j->c_str());
  2476. // remove double quotes in the path
  2477. cmsys::String& s = *j;
  2478. if(s.size() > 1 && s[0] == '\"' && s[s.size()-1] == '\"')
  2479. {
  2480. s = s.substr(1,s.size()-2);
  2481. }
  2482. }
  2483. value += *j;
  2484. }
  2485. this->Makefile->AddDefinition(var, value.c_str());
  2486. return true;
  2487. }
  2488. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2489. // Stuff for curl download/upload
  2490. typedef std::vector<char> cmFileCommandVectorOfChar;
  2491. namespace {
  2492. size_t
  2493. cmWriteToFileCallback(void *ptr, size_t size, size_t nmemb,
  2494. void *data)
  2495. {
  2496. int realsize = (int)(size * nmemb);
  2497. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  2498. const char* chPtr = static_cast<char*>(ptr);
  2499. fout->write(chPtr, realsize);
  2500. return realsize;
  2501. }
  2502. size_t
  2503. cmWriteToMemoryCallback(void *ptr, size_t size, size_t nmemb,
  2504. void *data)
  2505. {
  2506. int realsize = (int)(size * nmemb);
  2507. cmFileCommandVectorOfChar *vec
  2508. = static_cast<cmFileCommandVectorOfChar*>(data);
  2509. const char* chPtr = static_cast<char*>(ptr);
  2510. vec->insert(vec->end(), chPtr, chPtr + realsize);
  2511. return realsize;
  2512. }
  2513. static size_t
  2514. cmFileCommandCurlDebugCallback(CURL *, curl_infotype, char *chPtr,
  2515. size_t size, void *data)
  2516. {
  2517. cmFileCommandVectorOfChar *vec
  2518. = static_cast<cmFileCommandVectorOfChar*>(data);
  2519. vec->insert(vec->end(), chPtr, chPtr + size);
  2520. return size;
  2521. }
  2522. class cURLProgressHelper
  2523. {
  2524. public:
  2525. cURLProgressHelper(cmFileCommand *fc, const char *text)
  2526. {
  2527. this->CurrentPercentage = -1;
  2528. this->FileCommand = fc;
  2529. this->Text = text;
  2530. }
  2531. bool UpdatePercentage(double value, double total, std::string &status)
  2532. {
  2533. int OldPercentage = this->CurrentPercentage;
  2534. if (total > 0.0)
  2535. {
  2536. this->CurrentPercentage = static_cast<int>(value/total*100.0 + 0.5);
  2537. if(this->CurrentPercentage > 100)
  2538. {
  2539. // Avoid extra progress reports for unexpected data beyond total.
  2540. this->CurrentPercentage = 100;
  2541. }
  2542. }
  2543. bool updated = (OldPercentage != this->CurrentPercentage);
  2544. if (updated)
  2545. {
  2546. std::ostringstream oss;
  2547. oss << "[" << this->Text << " " << this->CurrentPercentage
  2548. << "% complete]";
  2549. status = oss.str();
  2550. }
  2551. return updated;
  2552. }
  2553. cmFileCommand *GetFileCommand()
  2554. {
  2555. return this->FileCommand;
  2556. }
  2557. private:
  2558. int CurrentPercentage;
  2559. cmFileCommand *FileCommand;
  2560. std::string Text;
  2561. };
  2562. static int
  2563. cmFileDownloadProgressCallback(void *clientp,
  2564. double dltotal, double dlnow,
  2565. double ultotal, double ulnow)
  2566. {
  2567. cURLProgressHelper *helper =
  2568. reinterpret_cast<cURLProgressHelper *>(clientp);
  2569. static_cast<void>(ultotal);
  2570. static_cast<void>(ulnow);
  2571. std::string status;
  2572. if (helper->UpdatePercentage(dlnow, dltotal, status))
  2573. {
  2574. cmFileCommand *fc = helper->GetFileCommand();
  2575. cmMakefile *mf = fc->GetMakefile();
  2576. mf->DisplayStatus(status.c_str(), -1);
  2577. }
  2578. return 0;
  2579. }
  2580. static int
  2581. cmFileUploadProgressCallback(void *clientp,
  2582. double dltotal, double dlnow,
  2583. double ultotal, double ulnow)
  2584. {
  2585. cURLProgressHelper *helper =
  2586. reinterpret_cast<cURLProgressHelper *>(clientp);
  2587. static_cast<void>(dltotal);
  2588. static_cast<void>(dlnow);
  2589. std::string status;
  2590. if (helper->UpdatePercentage(ulnow, ultotal, status))
  2591. {
  2592. cmFileCommand *fc = helper->GetFileCommand();
  2593. cmMakefile *mf = fc->GetMakefile();
  2594. mf->DisplayStatus(status.c_str(), -1);
  2595. }
  2596. return 0;
  2597. }
  2598. }
  2599. namespace {
  2600. class cURLEasyGuard
  2601. {
  2602. public:
  2603. cURLEasyGuard(CURL * easy)
  2604. : Easy(easy)
  2605. {}
  2606. ~cURLEasyGuard(void)
  2607. {
  2608. if (this->Easy)
  2609. {
  2610. ::curl_easy_cleanup(this->Easy);
  2611. }
  2612. }
  2613. inline void release(void)
  2614. {
  2615. this->Easy = 0;
  2616. return;
  2617. }
  2618. private:
  2619. ::CURL * Easy;
  2620. };
  2621. }
  2622. #endif
  2623. #define check_curl_result(result, errstr) \
  2624. if (result != CURLE_OK) \
  2625. { \
  2626. std::string e(errstr); \
  2627. e += ::curl_easy_strerror(result); \
  2628. this->SetError(e); \
  2629. return false; \
  2630. }
  2631. bool
  2632. cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
  2633. {
  2634. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2635. std::vector<std::string>::const_iterator i = args.begin();
  2636. if(args.size() < 3)
  2637. {
  2638. this->SetError("DOWNLOAD must be called with at least three arguments.");
  2639. return false;
  2640. }
  2641. ++i; // Get rid of subcommand
  2642. std::string url = *i;
  2643. ++i;
  2644. std::string file = *i;
  2645. ++i;
  2646. long timeout = 0;
  2647. long inactivity_timeout = 0;
  2648. std::string verboseLog;
  2649. std::string statusVar;
  2650. bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
  2651. const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
  2652. std::string expectedHash;
  2653. std::string hashMatchMSG;
  2654. cmsys::auto_ptr<cmCryptoHash> hash;
  2655. bool showProgress = false;
  2656. while(i != args.end())
  2657. {
  2658. if(*i == "TIMEOUT")
  2659. {
  2660. ++i;
  2661. if(i != args.end())
  2662. {
  2663. timeout = atol(i->c_str());
  2664. }
  2665. else
  2666. {
  2667. this->SetError("DOWNLOAD missing time for TIMEOUT.");
  2668. return false;
  2669. }
  2670. }
  2671. else if(*i == "INACTIVITY_TIMEOUT")
  2672. {
  2673. ++i;
  2674. if(i != args.end())
  2675. {
  2676. inactivity_timeout = atol(i->c_str());
  2677. }
  2678. else
  2679. {
  2680. this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  2681. return false;
  2682. }
  2683. }
  2684. else if(*i == "LOG")
  2685. {
  2686. ++i;
  2687. if( i == args.end())
  2688. {
  2689. this->SetError("DOWNLOAD missing VAR for LOG.");
  2690. return false;
  2691. }
  2692. verboseLog = *i;
  2693. }
  2694. else if(*i == "STATUS")
  2695. {
  2696. ++i;
  2697. if( i == args.end())
  2698. {
  2699. this->SetError("DOWNLOAD missing VAR for STATUS.");
  2700. return false;
  2701. }
  2702. statusVar = *i;
  2703. }
  2704. else if(*i == "TLS_VERIFY")
  2705. {
  2706. ++i;
  2707. if(i != args.end())
  2708. {
  2709. tls_verify = cmSystemTools::IsOn(i->c_str());
  2710. }
  2711. else
  2712. {
  2713. this->SetError("TLS_VERIFY missing bool value.");
  2714. return false;
  2715. }
  2716. }
  2717. else if(*i == "TLS_CAINFO")
  2718. {
  2719. ++i;
  2720. if(i != args.end())
  2721. {
  2722. cainfo = i->c_str();
  2723. }
  2724. else
  2725. {
  2726. this->SetError("TLS_CAFILE missing file value.");
  2727. return false;
  2728. }
  2729. }
  2730. else if(*i == "EXPECTED_MD5")
  2731. {
  2732. ++i;
  2733. if( i == args.end())
  2734. {
  2735. this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  2736. return false;
  2737. }
  2738. hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New("MD5"));
  2739. hashMatchMSG = "MD5 sum";
  2740. expectedHash = cmSystemTools::LowerCase(*i);
  2741. }
  2742. else if(*i == "SHOW_PROGRESS")
  2743. {
  2744. showProgress = true;
  2745. }
  2746. else if(*i == "EXPECTED_HASH")
  2747. {
  2748. ++i;
  2749. if(i == args.end())
  2750. {
  2751. this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  2752. return false;
  2753. }
  2754. std::string::size_type pos = i->find("=");
  2755. if(pos == std::string::npos)
  2756. {
  2757. std::string err =
  2758. "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
  2759. err += *i;
  2760. this->SetError(err);
  2761. return false;
  2762. }
  2763. std::string algo = i->substr(0, pos);
  2764. expectedHash = cmSystemTools::LowerCase(i->substr(pos+1));
  2765. hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
  2766. if(!hash.get())
  2767. {
  2768. std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
  2769. err += algo;
  2770. this->SetError(err);
  2771. return false;
  2772. }
  2773. hashMatchMSG = algo + " hash";
  2774. }
  2775. ++i;
  2776. }
  2777. // If file exists already, and caller specified an expected md5 or sha,
  2778. // and the existing file already has the expected hash, then simply
  2779. // return.
  2780. //
  2781. if(cmSystemTools::FileExists(file.c_str()) && hash.get())
  2782. {
  2783. std::string msg;
  2784. std::string actualHash = hash->HashFile(file);
  2785. if(actualHash == expectedHash)
  2786. {
  2787. msg = "returning early; file already exists with expected ";
  2788. msg += hashMatchMSG;
  2789. msg += "\"";
  2790. if(statusVar.size())
  2791. {
  2792. std::ostringstream result;
  2793. result << (int)0 << ";\"" << msg;
  2794. this->Makefile->AddDefinition(statusVar,
  2795. result.str().c_str());
  2796. }
  2797. return true;
  2798. }
  2799. }
  2800. // Make sure parent directory exists so we can write to the file
  2801. // as we receive downloaded bits from curl...
  2802. //
  2803. std::string dir = cmSystemTools::GetFilenamePath(file);
  2804. if(!cmSystemTools::FileExists(dir.c_str()) &&
  2805. !cmSystemTools::MakeDirectory(dir.c_str()))
  2806. {
  2807. std::string errstring = "DOWNLOAD error: cannot create directory '"
  2808. + dir + "' - Specify file by full path name and verify that you "
  2809. "have directory creation and file write privileges.";
  2810. this->SetError(errstring);
  2811. return false;
  2812. }
  2813. cmsys::ofstream fout(file.c_str(), std::ios::binary);
  2814. if(!fout)
  2815. {
  2816. this->SetError("DOWNLOAD cannot open file for write.");
  2817. return false;
  2818. }
  2819. #if defined(WIN32) && defined(CMAKE_ENCODING_UTF8)
  2820. url = fix_file_url_windows(url);
  2821. #endif
  2822. ::CURL *curl;
  2823. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2824. curl = ::curl_easy_init();
  2825. if(!curl)
  2826. {
  2827. this->SetError("DOWNLOAD error initializing curl.");
  2828. return false;
  2829. }
  2830. cURLEasyGuard g_curl(curl);
  2831. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2832. check_curl_result(res, "DOWNLOAD cannot set url: ");
  2833. // enable HTTP ERROR parsing
  2834. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2835. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  2836. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  2837. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  2838. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  2839. cmWriteToFileCallback);
  2840. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  2841. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2842. cmFileCommandCurlDebugCallback);
  2843. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  2844. // check to see if TLS verification is requested
  2845. if(tls_verify)
  2846. {
  2847. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2848. check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
  2849. }
  2850. else
  2851. {
  2852. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2853. check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
  2854. }
  2855. // check to see if a CAINFO file has been specified
  2856. // command arg comes first
  2857. if(cainfo && *cainfo)
  2858. {
  2859. res = ::curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo);
  2860. check_curl_result(res, "Unable to set TLS/SSL Verify CAINFO: ");
  2861. }
  2862. cmFileCommandVectorOfChar chunkDebug;
  2863. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&fout);
  2864. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  2865. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
  2866. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  2867. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2868. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  2869. if(verboseLog.size())
  2870. {
  2871. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2872. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  2873. }
  2874. if(timeout > 0)
  2875. {
  2876. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
  2877. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  2878. }
  2879. if(inactivity_timeout > 0)
  2880. {
  2881. // Give up if there is no progress for a long time.
  2882. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2883. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2884. }
  2885. // Need the progress helper's scope to last through the duration of
  2886. // the curl_easy_perform call... so this object is declared at function
  2887. // scope intentionally, rather than inside the "if(showProgress)"
  2888. // block...
  2889. //
  2890. cURLProgressHelper helper(this, "download");
  2891. if(showProgress)
  2892. {
  2893. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2894. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  2895. res = ::curl_easy_setopt(curl,
  2896. CURLOPT_PROGRESSFUNCTION, cmFileDownloadProgressCallback);
  2897. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  2898. res = ::curl_easy_setopt(curl,
  2899. CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
  2900. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  2901. }
  2902. res = ::curl_easy_perform(curl);
  2903. /* always cleanup */
  2904. g_curl.release();
  2905. ::curl_easy_cleanup(curl);
  2906. if(statusVar.size())
  2907. {
  2908. std::ostringstream result;
  2909. result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
  2910. this->Makefile->AddDefinition(statusVar,
  2911. result.str().c_str());
  2912. }
  2913. ::curl_global_cleanup();
  2914. // Explicitly flush/close so we can measure the md5 accurately.
  2915. //
  2916. fout.flush();
  2917. fout.close();
  2918. // Verify MD5 sum if requested:
  2919. //
  2920. if (hash.get())
  2921. {
  2922. std::string actualHash = hash->HashFile(file);
  2923. if (actualHash.size() == 0)
  2924. {
  2925. this->SetError("DOWNLOAD cannot compute hash on downloaded file");
  2926. return false;
  2927. }
  2928. if (expectedHash != actualHash)
  2929. {
  2930. std::ostringstream oss;
  2931. oss << "DOWNLOAD HASH mismatch" << std::endl
  2932. << " for file: [" << file << "]" << std::endl
  2933. << " expected hash: [" << expectedHash << "]" << std::endl
  2934. << " actual hash: [" << actualHash << "]" << std::endl
  2935. << " status: [" << (int)res << ";\""
  2936. << ::curl_easy_strerror(res) << "\"]" << std::endl
  2937. ;
  2938. this->SetError(oss.str());
  2939. return false;
  2940. }
  2941. }
  2942. if(chunkDebug.size())
  2943. {
  2944. chunkDebug.push_back(0);
  2945. if(CURLE_OPERATION_TIMEOUTED == res)
  2946. {
  2947. std::string output = &*chunkDebug.begin();
  2948. if(verboseLog.size())
  2949. {
  2950. this->Makefile->AddDefinition(verboseLog,
  2951. &*chunkDebug.begin());
  2952. }
  2953. }
  2954. this->Makefile->AddDefinition(verboseLog,
  2955. &*chunkDebug.begin());
  2956. }
  2957. return true;
  2958. #else
  2959. this->SetError("DOWNLOAD not supported by bootstrap cmake.");
  2960. return false;
  2961. #endif
  2962. }
  2963. bool
  2964. cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
  2965. {
  2966. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2967. if(args.size() < 3)
  2968. {
  2969. this->SetError("UPLOAD must be called with at least three arguments.");
  2970. return false;
  2971. }
  2972. std::vector<std::string>::const_iterator i = args.begin();
  2973. ++i;
  2974. std::string filename = *i;
  2975. ++i;
  2976. std::string url = *i;
  2977. ++i;
  2978. long timeout = 0;
  2979. long inactivity_timeout = 0;
  2980. std::string logVar;
  2981. std::string statusVar;
  2982. bool showProgress = false;
  2983. while(i != args.end())
  2984. {
  2985. if(*i == "TIMEOUT")
  2986. {
  2987. ++i;
  2988. if(i != args.end())
  2989. {
  2990. timeout = atol(i->c_str());
  2991. }
  2992. else
  2993. {
  2994. this->SetError("UPLOAD missing time for TIMEOUT.");
  2995. return false;
  2996. }
  2997. }
  2998. else if(*i == "INACTIVITY_TIMEOUT")
  2999. {
  3000. ++i;
  3001. if(i != args.end())
  3002. {
  3003. inactivity_timeout = atol(i->c_str());
  3004. }
  3005. else
  3006. {
  3007. this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  3008. return false;
  3009. }
  3010. }
  3011. else if(*i == "LOG")
  3012. {
  3013. ++i;
  3014. if( i == args.end())
  3015. {
  3016. this->SetError("UPLOAD missing VAR for LOG.");
  3017. return false;
  3018. }
  3019. logVar = *i;
  3020. }
  3021. else if(*i == "STATUS")
  3022. {
  3023. ++i;
  3024. if( i == args.end())
  3025. {
  3026. this->SetError("UPLOAD missing VAR for STATUS.");
  3027. return false;
  3028. }
  3029. statusVar = *i;
  3030. }
  3031. else if(*i == "SHOW_PROGRESS")
  3032. {
  3033. showProgress = true;
  3034. }
  3035. ++i;
  3036. }
  3037. // Open file for reading:
  3038. //
  3039. FILE *fin = cmsys::SystemTools::Fopen(filename, "rb");
  3040. if(!fin)
  3041. {
  3042. std::string errStr = "UPLOAD cannot open file '";
  3043. errStr += filename + "' for reading.";
  3044. this->SetError(errStr);
  3045. return false;
  3046. }
  3047. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  3048. #if defined(WIN32) && defined(CMAKE_ENCODING_UTF8)
  3049. url = fix_file_url_windows(url);
  3050. #endif
  3051. ::CURL *curl;
  3052. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  3053. curl = ::curl_easy_init();
  3054. if(!curl)
  3055. {
  3056. this->SetError("UPLOAD error initializing curl.");
  3057. fclose(fin);
  3058. return false;
  3059. }
  3060. cURLEasyGuard g_curl(curl);
  3061. // enable HTTP ERROR parsing
  3062. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  3063. // enable uploading
  3064. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  3065. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  3066. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  3067. check_curl_result(res, "UPLOAD cannot set url: ");
  3068. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  3069. cmWriteToMemoryCallback);
  3070. check_curl_result(res, "UPLOAD cannot set write function: ");
  3071. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  3072. cmFileCommandCurlDebugCallback);
  3073. check_curl_result(res, "UPLOAD cannot set debug function: ");
  3074. cmFileCommandVectorOfChar chunkResponse;
  3075. cmFileCommandVectorOfChar chunkDebug;
  3076. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunkResponse);
  3077. check_curl_result(res, "UPLOAD cannot set write data: ");
  3078. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
  3079. check_curl_result(res, "UPLOAD cannot set debug data: ");
  3080. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  3081. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  3082. if(logVar.size())
  3083. {
  3084. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  3085. check_curl_result(res, "UPLOAD cannot set verbose: ");
  3086. }
  3087. if(timeout > 0)
  3088. {
  3089. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
  3090. check_curl_result(res, "UPLOAD cannot set timeout: ");
  3091. }
  3092. if(inactivity_timeout > 0)
  3093. {
  3094. // Give up if there is no progress for a long time.
  3095. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  3096. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  3097. }
  3098. // Need the progress helper's scope to last through the duration of
  3099. // the curl_easy_perform call... so this object is declared at function
  3100. // scope intentionally, rather than inside the "if(showProgress)"
  3101. // block...
  3102. //
  3103. cURLProgressHelper helper(this, "upload");
  3104. if(showProgress)
  3105. {
  3106. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  3107. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  3108. res = ::curl_easy_setopt(curl,
  3109. CURLOPT_PROGRESSFUNCTION, cmFileUploadProgressCallback);
  3110. check_curl_result(res, "UPLOAD cannot set progress function: ");
  3111. res = ::curl_easy_setopt(curl,
  3112. CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
  3113. check_curl_result(res, "UPLOAD cannot set progress data: ");
  3114. }
  3115. // now specify which file to upload
  3116. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  3117. check_curl_result(res, "UPLOAD cannot set input file: ");
  3118. // and give the size of the upload (optional)
  3119. res = ::curl_easy_setopt(curl,
  3120. CURLOPT_INFILESIZE, static_cast<long>(file_size));
  3121. check_curl_result(res, "UPLOAD cannot set input file size: ");
  3122. res = ::curl_easy_perform(curl);
  3123. /* always cleanup */
  3124. g_curl.release();
  3125. ::curl_easy_cleanup(curl);
  3126. if(statusVar.size())
  3127. {
  3128. std::ostringstream result;
  3129. result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
  3130. this->Makefile->AddDefinition(statusVar,
  3131. result.str().c_str());
  3132. }
  3133. ::curl_global_cleanup();
  3134. fclose(fin);
  3135. fin = NULL;
  3136. if(logVar.size())
  3137. {
  3138. std::string log;
  3139. if(chunkResponse.size())
  3140. {
  3141. chunkResponse.push_back(0);
  3142. log += "Response:\n";
  3143. log += &*chunkResponse.begin();
  3144. log += "\n";
  3145. }
  3146. if(chunkDebug.size())
  3147. {
  3148. chunkDebug.push_back(0);
  3149. log += "Debug:\n";
  3150. log += &*chunkDebug.begin();
  3151. log += "\n";
  3152. }
  3153. this->Makefile->AddDefinition(logVar, log.c_str());
  3154. }
  3155. return true;
  3156. #else
  3157. this->SetError("UPLOAD not supported by bootstrap cmake.");
  3158. return false;
  3159. #endif
  3160. }
  3161. //----------------------------------------------------------------------------
  3162. void cmFileCommand::AddEvaluationFile(const std::string &inputName,
  3163. const std::string &outputExpr,
  3164. const std::string &condition,
  3165. bool inputIsContent
  3166. )
  3167. {
  3168. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  3169. cmGeneratorExpression outputGe(&lfbt);
  3170. cmsys::auto_ptr<cmCompiledGeneratorExpression> outputCge
  3171. = outputGe.Parse(outputExpr);
  3172. cmGeneratorExpression conditionGe(&lfbt);
  3173. cmsys::auto_ptr<cmCompiledGeneratorExpression> conditionCge
  3174. = conditionGe.Parse(condition);
  3175. this->Makefile->GetLocalGenerator()
  3176. ->GetGlobalGenerator()->AddEvaluationFile(inputName,
  3177. outputCge,
  3178. this->Makefile,
  3179. conditionCge,
  3180. inputIsContent);
  3181. }
  3182. //----------------------------------------------------------------------------
  3183. bool cmFileCommand::HandleGenerateCommand(
  3184. std::vector<std::string> const& args)
  3185. {
  3186. if (args.size() < 5)
  3187. {
  3188. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3189. return false;
  3190. }
  3191. if (args[1] != "OUTPUT")
  3192. {
  3193. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3194. return false;
  3195. }
  3196. std::string condition;
  3197. if (args.size() > 5)
  3198. {
  3199. if (args[5] != "CONDITION")
  3200. {
  3201. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3202. return false;
  3203. }
  3204. if (args.size() != 7)
  3205. {
  3206. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3207. return false;
  3208. }
  3209. condition = args[6];
  3210. if (condition.empty())
  3211. {
  3212. this->SetError("CONDITION of sub-command GENERATE must not be empty if "
  3213. "specified.");
  3214. return false;
  3215. }
  3216. }
  3217. std::string output = args[2];
  3218. const bool inputIsContent = args[3] != "INPUT";
  3219. if (inputIsContent && args[3] != "CONTENT")
  3220. {
  3221. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3222. return false;
  3223. }
  3224. std::string input = args[4];
  3225. this->AddEvaluationFile(input, output, condition, inputIsContent);
  3226. return true;
  3227. }
  3228. //----------------------------------------------------------------------------
  3229. bool cmFileCommand::HandleLockCommand(
  3230. std::vector<std::string> const& args)
  3231. {
  3232. #if defined(CMAKE_BUILD_WITH_CMAKE)
  3233. // Default values
  3234. bool directory = false;
  3235. bool release = false;
  3236. enum Guard {
  3237. GUARD_FUNCTION,
  3238. GUARD_FILE,
  3239. GUARD_PROCESS
  3240. };
  3241. Guard guard = GUARD_PROCESS;
  3242. std::string resultVariable;
  3243. unsigned long timeout = static_cast<unsigned long>(-1);
  3244. // Parse arguments
  3245. if(args.size() < 2)
  3246. {
  3247. this->Makefile->IssueMessage(
  3248. cmake::FATAL_ERROR,
  3249. "sub-command LOCK requires at least two arguments.");
  3250. return false;
  3251. }
  3252. std::string path = args[1];
  3253. for (unsigned i = 2; i < args.size(); ++i)
  3254. {
  3255. if (args[i] == "DIRECTORY")
  3256. {
  3257. directory = true;
  3258. }
  3259. else if (args[i] == "RELEASE")
  3260. {
  3261. release = true;
  3262. }
  3263. else if (args[i] == "GUARD")
  3264. {
  3265. ++i;
  3266. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  3267. if (i >= args.size())
  3268. {
  3269. this->Makefile->IssueMessage(cmake::FATAL_ERROR, merr);
  3270. return false;
  3271. }
  3272. else
  3273. {
  3274. if (args[i] == "FUNCTION")
  3275. {
  3276. guard = GUARD_FUNCTION;
  3277. }
  3278. else if (args[i] == "FILE")
  3279. {
  3280. guard = GUARD_FILE;
  3281. }
  3282. else if (args[i] == "PROCESS")
  3283. {
  3284. guard = GUARD_PROCESS;
  3285. }
  3286. else
  3287. {
  3288. std::ostringstream e;
  3289. e << merr << ", but got:\n \"" << args[i] << "\".";
  3290. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3291. return false;
  3292. }
  3293. }
  3294. }
  3295. else if (args[i] == "RESULT_VARIABLE")
  3296. {
  3297. ++i;
  3298. if (i >= args.size())
  3299. {
  3300. this->Makefile->IssueMessage(
  3301. cmake::FATAL_ERROR,
  3302. "expected variable name after RESULT_VARIABLE");
  3303. return false;
  3304. }
  3305. resultVariable = args[i];
  3306. }
  3307. else if (args[i] == "TIMEOUT")
  3308. {
  3309. ++i;
  3310. if (i >= args.size())
  3311. {
  3312. this->Makefile->IssueMessage(
  3313. cmake::FATAL_ERROR,
  3314. "expected timeout value after TIMEOUT");
  3315. return false;
  3316. }
  3317. long scanned;
  3318. if(!cmSystemTools::StringToLong(args[i].c_str(), &scanned)
  3319. || scanned < 0)
  3320. {
  3321. std::ostringstream e;
  3322. e << "TIMEOUT value \"" << args[i] << "\" is not an unsigned integer.";
  3323. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3324. return false;
  3325. }
  3326. timeout = static_cast<unsigned long>(scanned);
  3327. }
  3328. else
  3329. {
  3330. std::ostringstream e;
  3331. e << "expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or TIMEOUT\n";
  3332. e << "but got: \"" << args[i] << "\".";
  3333. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3334. return false;
  3335. }
  3336. }
  3337. if (directory)
  3338. {
  3339. path += "/cmake.lock";
  3340. }
  3341. if (!cmsys::SystemTools::FileIsFullPath(path))
  3342. {
  3343. path = this->Makefile->GetCurrentDirectory() + ("/" + path);
  3344. }
  3345. // Unify path (remove '//', '/../', ...)
  3346. path = cmSystemTools::CollapseFullPath(path);
  3347. // Create file and directories if needed
  3348. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  3349. if (!cmSystemTools::MakeDirectory(parentDir))
  3350. {
  3351. std::ostringstream e;
  3352. e << "directory\n \"" << parentDir << "\"\ncreation failed ";
  3353. e << "(check permissions).";
  3354. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3355. cmSystemTools::SetFatalErrorOccured();
  3356. return false;
  3357. }
  3358. FILE *file = cmsys::SystemTools::Fopen(path, "w");
  3359. if (!file)
  3360. {
  3361. std::ostringstream e;
  3362. e << "file\n \"" << path << "\"\ncreation failed (check permissions).";
  3363. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3364. cmSystemTools::SetFatalErrorOccured();
  3365. return false;
  3366. }
  3367. fclose(file);
  3368. // Actual lock/unlock
  3369. cmFileLockPool& lockPool = this->Makefile->GetLocalGenerator()->
  3370. GetGlobalGenerator()->GetFileLockPool();
  3371. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  3372. if (release)
  3373. {
  3374. fileLockResult = lockPool.Release(path);
  3375. }
  3376. else
  3377. {
  3378. switch (guard)
  3379. {
  3380. case GUARD_FUNCTION:
  3381. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  3382. break;
  3383. case GUARD_FILE:
  3384. fileLockResult = lockPool.LockFileScope(path, timeout);
  3385. break;
  3386. case GUARD_PROCESS:
  3387. fileLockResult = lockPool.LockProcessScope(path, timeout);
  3388. break;
  3389. default:
  3390. cmSystemTools::SetFatalErrorOccured();
  3391. return false;
  3392. }
  3393. }
  3394. const std::string result = fileLockResult.GetOutputMessage();
  3395. if (resultVariable.empty() && !fileLockResult.IsOk())
  3396. {
  3397. std::ostringstream e;
  3398. e << "error locking file\n \"" << path << "\"\n" << result << ".";
  3399. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3400. cmSystemTools::SetFatalErrorOccured();
  3401. return false;
  3402. }
  3403. if (!resultVariable.empty())
  3404. {
  3405. this->Makefile->AddDefinition(resultVariable, result.c_str());
  3406. }
  3407. return true;
  3408. #else
  3409. static_cast<void>(args);
  3410. this->SetError("sub-command LOCK not implemented in bootstrap cmake");
  3411. return false;
  3412. #endif
  3413. }
  3414. //----------------------------------------------------------------------------
  3415. bool cmFileCommand::HandleTimestampCommand(
  3416. std::vector<std::string> const& args)
  3417. {
  3418. if(args.size() < 3)
  3419. {
  3420. this->SetError("sub-command TIMESTAMP requires at least two arguments.");
  3421. return false;
  3422. }
  3423. else if(args.size() > 5)
  3424. {
  3425. this->SetError("sub-command TIMESTAMP takes at most four arguments.");
  3426. return false;
  3427. }
  3428. unsigned int argsIndex = 1;
  3429. const std::string& filename = args[argsIndex++];
  3430. const std::string& outputVariable = args[argsIndex++];
  3431. std::string formatString;
  3432. if(args.size() > argsIndex && args[argsIndex] != "UTC")
  3433. {
  3434. formatString = args[argsIndex++];
  3435. }
  3436. bool utcFlag = false;
  3437. if(args.size() > argsIndex)
  3438. {
  3439. if(args[argsIndex] == "UTC")
  3440. {
  3441. utcFlag = true;
  3442. }
  3443. else
  3444. {
  3445. std::string e = " TIMESTAMP sub-command does not recognize option " +
  3446. args[argsIndex] + ".";
  3447. this->SetError(e);
  3448. return false;
  3449. }
  3450. }
  3451. cmTimestamp timestamp;
  3452. std::string result = timestamp.FileModificationTime(
  3453. filename.c_str(), formatString, utcFlag);
  3454. this->Makefile->AddDefinition(outputVariable, result.c_str());
  3455. return true;
  3456. }