cmFileCommand.cxx 102 KB

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