1
0

cmFileCommand.cxx 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883
  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. cmPolicies::GetPolicyWarning(cmPolicies::CMP0009));
  991. }
  992. break;
  993. case cmPolicies::REQUIRED_IF_USED:
  994. case cmPolicies::REQUIRED_ALWAYS:
  995. this->SetError("policy CMP0009 error");
  996. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  997. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0009));
  998. return false;
  999. }
  1000. }
  1001. this->Makefile->AddDefinition(variable, output.c_str());
  1002. return true;
  1003. }
  1004. //----------------------------------------------------------------------------
  1005. bool cmFileCommand::HandleMakeDirectoryCommand(
  1006. std::vector<std::string> const& args)
  1007. {
  1008. // File command has at least one argument
  1009. assert(args.size() > 1);
  1010. std::vector<std::string>::const_iterator i = args.begin();
  1011. i++; // Get rid of subcommand
  1012. std::string expr;
  1013. for ( ; i != args.end(); ++i )
  1014. {
  1015. const std::string* cdir = &(*i);
  1016. if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
  1017. {
  1018. expr = this->Makefile->GetCurrentSourceDirectory();
  1019. expr += "/" + *i;
  1020. cdir = &expr;
  1021. }
  1022. if ( !this->Makefile->CanIWriteThisFile(cdir->c_str()) )
  1023. {
  1024. std::string e = "attempted to create a directory: " + *cdir
  1025. + " into a source directory.";
  1026. this->SetError(e);
  1027. cmSystemTools::SetFatalErrorOccured();
  1028. return false;
  1029. }
  1030. if ( !cmSystemTools::MakeDirectory(cdir->c_str()) )
  1031. {
  1032. std::string error = "problem creating directory: " + *cdir;
  1033. this->SetError(error);
  1034. return false;
  1035. }
  1036. }
  1037. return true;
  1038. }
  1039. //----------------------------------------------------------------------------
  1040. bool
  1041. cmFileCommand::HandleDifferentCommand(std::vector<std::string> const& args)
  1042. {
  1043. /*
  1044. FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
  1045. */
  1046. // Evaluate arguments.
  1047. const char* file_lhs = 0;
  1048. const char* file_rhs = 0;
  1049. const char* var = 0;
  1050. enum Doing { DoingNone, DoingVar, DoingFileLHS, DoingFileRHS };
  1051. Doing doing = DoingVar;
  1052. for(unsigned int i=1; i < args.size(); ++i)
  1053. {
  1054. if(args[i] == "FILES")
  1055. {
  1056. doing = DoingFileLHS;
  1057. }
  1058. else if(doing == DoingVar)
  1059. {
  1060. var = args[i].c_str();
  1061. doing = DoingNone;
  1062. }
  1063. else if(doing == DoingFileLHS)
  1064. {
  1065. file_lhs = args[i].c_str();
  1066. doing = DoingFileRHS;
  1067. }
  1068. else if(doing == DoingFileRHS)
  1069. {
  1070. file_rhs = args[i].c_str();
  1071. doing = DoingNone;
  1072. }
  1073. else
  1074. {
  1075. std::ostringstream e;
  1076. e << "DIFFERENT given unknown argument " << args[i];
  1077. this->SetError(e.str());
  1078. return false;
  1079. }
  1080. }
  1081. if(!var)
  1082. {
  1083. this->SetError("DIFFERENT not given result variable name.");
  1084. return false;
  1085. }
  1086. if(!file_lhs || !file_rhs)
  1087. {
  1088. this->SetError("DIFFERENT not given FILES option with two file names.");
  1089. return false;
  1090. }
  1091. // Compare the files.
  1092. const char* result =
  1093. cmSystemTools::FilesDiffer(file_lhs, file_rhs)? "1" : "0";
  1094. this->Makefile->AddDefinition(var, result);
  1095. return true;
  1096. }
  1097. //----------------------------------------------------------------------------
  1098. // File installation helper class.
  1099. struct cmFileCopier
  1100. {
  1101. cmFileCopier(cmFileCommand* command, const char* name = "COPY"):
  1102. FileCommand(command),
  1103. Makefile(command->GetMakefile()),
  1104. Name(name),
  1105. Always(false),
  1106. MatchlessFiles(true),
  1107. FilePermissions(0),
  1108. DirPermissions(0),
  1109. CurrentMatchRule(0),
  1110. UseGivenPermissionsFile(false),
  1111. UseGivenPermissionsDir(false),
  1112. UseSourcePermissions(true),
  1113. Doing(DoingNone)
  1114. {
  1115. }
  1116. virtual ~cmFileCopier() {}
  1117. bool Run(std::vector<std::string> const& args);
  1118. protected:
  1119. cmFileCommand* FileCommand;
  1120. cmMakefile* Makefile;
  1121. const char* Name;
  1122. bool Always;
  1123. cmFileTimeComparison FileTimes;
  1124. // Whether to install a file not matching any expression.
  1125. bool MatchlessFiles;
  1126. // Permissions for files and directories installed by this object.
  1127. mode_t FilePermissions;
  1128. mode_t DirPermissions;
  1129. // Properties set by pattern and regex match rules.
  1130. struct MatchProperties
  1131. {
  1132. bool Exclude;
  1133. mode_t Permissions;
  1134. MatchProperties(): Exclude(false), Permissions(0) {}
  1135. };
  1136. struct MatchRule;
  1137. friend struct MatchRule;
  1138. struct MatchRule
  1139. {
  1140. cmsys::RegularExpression Regex;
  1141. MatchProperties Properties;
  1142. std::string RegexString;
  1143. MatchRule(std::string const& regex):
  1144. Regex(regex.c_str()), RegexString(regex) {}
  1145. };
  1146. std::vector<MatchRule> MatchRules;
  1147. // Get the properties from rules matching this input file.
  1148. MatchProperties CollectMatchProperties(const char* file)
  1149. {
  1150. // Match rules are case-insensitive on some platforms.
  1151. #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
  1152. std::string lower = cmSystemTools::LowerCase(file);
  1153. const char* file_to_match = lower.c_str();
  1154. #else
  1155. const char* file_to_match = file;
  1156. #endif
  1157. // Collect properties from all matching rules.
  1158. bool matched = false;
  1159. MatchProperties result;
  1160. for(std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
  1161. mr != this->MatchRules.end(); ++mr)
  1162. {
  1163. if(mr->Regex.find(file_to_match))
  1164. {
  1165. matched = true;
  1166. result.Exclude |= mr->Properties.Exclude;
  1167. result.Permissions |= mr->Properties.Permissions;
  1168. }
  1169. }
  1170. if(!matched && !this->MatchlessFiles)
  1171. {
  1172. result.Exclude = !cmSystemTools::FileIsDirectory(file);
  1173. }
  1174. return result;
  1175. }
  1176. bool SetPermissions(const char* toFile, mode_t permissions)
  1177. {
  1178. if(permissions && !cmSystemTools::SetPermissions(toFile, permissions))
  1179. {
  1180. std::ostringstream e;
  1181. e << this->Name << " cannot set permissions on \"" << toFile << "\"";
  1182. this->FileCommand->SetError(e.str());
  1183. return false;
  1184. }
  1185. return true;
  1186. }
  1187. // Translate an argument to a permissions bit.
  1188. bool CheckPermissions(std::string const& arg, mode_t& permissions)
  1189. {
  1190. if(arg == "OWNER_READ") { permissions |= mode_owner_read; }
  1191. else if(arg == "OWNER_WRITE") { permissions |= mode_owner_write; }
  1192. else if(arg == "OWNER_EXECUTE") { permissions |= mode_owner_execute; }
  1193. else if(arg == "GROUP_READ") { permissions |= mode_group_read; }
  1194. else if(arg == "GROUP_WRITE") { permissions |= mode_group_write; }
  1195. else if(arg == "GROUP_EXECUTE") { permissions |= mode_group_execute; }
  1196. else if(arg == "WORLD_READ") { permissions |= mode_world_read; }
  1197. else if(arg == "WORLD_WRITE") { permissions |= mode_world_write; }
  1198. else if(arg == "WORLD_EXECUTE") { permissions |= mode_world_execute; }
  1199. else if(arg == "SETUID") { permissions |= mode_setuid; }
  1200. else if(arg == "SETGID") { permissions |= mode_setgid; }
  1201. else
  1202. {
  1203. std::ostringstream e;
  1204. e << this->Name << " given invalid permission \"" << arg << "\".";
  1205. this->FileCommand->SetError(e.str());
  1206. return false;
  1207. }
  1208. return true;
  1209. }
  1210. bool InstallSymlink(const char* fromFile, const char* toFile);
  1211. bool InstallFile(const char* fromFile, const char* toFile,
  1212. MatchProperties const& match_properties);
  1213. bool InstallDirectory(const char* source, const char* destination,
  1214. MatchProperties const& match_properties);
  1215. virtual bool Install(const char* fromFile, const char* toFile);
  1216. virtual std::string const& ToName(std::string const& fromName)
  1217. { return fromName; }
  1218. enum Type
  1219. {
  1220. TypeFile,
  1221. TypeDir,
  1222. TypeLink
  1223. };
  1224. virtual void ReportCopy(const char*, Type, bool) {}
  1225. virtual bool ReportMissing(const char* fromFile)
  1226. {
  1227. // The input file does not exist and installation is not optional.
  1228. std::ostringstream e;
  1229. e << this->Name << " cannot find \"" << fromFile << "\".";
  1230. this->FileCommand->SetError(e.str());
  1231. return false;
  1232. }
  1233. MatchRule* CurrentMatchRule;
  1234. bool UseGivenPermissionsFile;
  1235. bool UseGivenPermissionsDir;
  1236. bool UseSourcePermissions;
  1237. std::string Destination;
  1238. std::vector<std::string> Files;
  1239. int Doing;
  1240. virtual bool Parse(std::vector<std::string> const& args);
  1241. enum
  1242. {
  1243. DoingNone,
  1244. DoingError,
  1245. DoingDestination,
  1246. DoingFiles,
  1247. DoingPattern,
  1248. DoingRegex,
  1249. DoingPermissionsFile,
  1250. DoingPermissionsDir,
  1251. DoingPermissionsMatch,
  1252. DoingLast1
  1253. };
  1254. virtual bool CheckKeyword(std::string const& arg);
  1255. virtual bool CheckValue(std::string const& arg);
  1256. void NotBeforeMatch(std::string const& arg)
  1257. {
  1258. std::ostringstream e;
  1259. e << "option " << arg << " may not appear before PATTERN or REGEX.";
  1260. this->FileCommand->SetError(e.str());
  1261. this->Doing = DoingError;
  1262. }
  1263. void NotAfterMatch(std::string const& arg)
  1264. {
  1265. std::ostringstream e;
  1266. e << "option " << arg << " may not appear after PATTERN or REGEX.";
  1267. this->FileCommand->SetError(e.str());
  1268. this->Doing = DoingError;
  1269. }
  1270. virtual void DefaultFilePermissions()
  1271. {
  1272. // Use read/write permissions.
  1273. this->FilePermissions = 0;
  1274. this->FilePermissions |= mode_owner_read;
  1275. this->FilePermissions |= mode_owner_write;
  1276. this->FilePermissions |= mode_group_read;
  1277. this->FilePermissions |= mode_world_read;
  1278. }
  1279. virtual void DefaultDirectoryPermissions()
  1280. {
  1281. // Use read/write/executable permissions.
  1282. this->DirPermissions = 0;
  1283. this->DirPermissions |= mode_owner_read;
  1284. this->DirPermissions |= mode_owner_write;
  1285. this->DirPermissions |= mode_owner_execute;
  1286. this->DirPermissions |= mode_group_read;
  1287. this->DirPermissions |= mode_group_execute;
  1288. this->DirPermissions |= mode_world_read;
  1289. this->DirPermissions |= mode_world_execute;
  1290. }
  1291. };
  1292. //----------------------------------------------------------------------------
  1293. bool cmFileCopier::Parse(std::vector<std::string> const& args)
  1294. {
  1295. this->Doing = DoingFiles;
  1296. for(unsigned int i=1; i < args.size(); ++i)
  1297. {
  1298. // Check this argument.
  1299. if(!this->CheckKeyword(args[i]) &&
  1300. !this->CheckValue(args[i]))
  1301. {
  1302. std::ostringstream e;
  1303. e << "called with unknown argument \"" << args[i] << "\".";
  1304. this->FileCommand->SetError(e.str());
  1305. return false;
  1306. }
  1307. // Quit if an argument is invalid.
  1308. if(this->Doing == DoingError)
  1309. {
  1310. return false;
  1311. }
  1312. }
  1313. // Require a destination.
  1314. if(this->Destination.empty())
  1315. {
  1316. std::ostringstream e;
  1317. e << this->Name << " given no DESTINATION";
  1318. this->FileCommand->SetError(e.str());
  1319. return false;
  1320. }
  1321. // If file permissions were not specified set default permissions.
  1322. if(!this->UseGivenPermissionsFile && !this->UseSourcePermissions)
  1323. {
  1324. this->DefaultFilePermissions();
  1325. }
  1326. // If directory permissions were not specified set default permissions.
  1327. if(!this->UseGivenPermissionsDir && !this->UseSourcePermissions)
  1328. {
  1329. this->DefaultDirectoryPermissions();
  1330. }
  1331. return true;
  1332. }
  1333. //----------------------------------------------------------------------------
  1334. bool cmFileCopier::CheckKeyword(std::string const& arg)
  1335. {
  1336. if(arg == "DESTINATION")
  1337. {
  1338. if(this->CurrentMatchRule)
  1339. {
  1340. this->NotAfterMatch(arg);
  1341. }
  1342. else
  1343. {
  1344. this->Doing = DoingDestination;
  1345. }
  1346. }
  1347. else if(arg == "PATTERN")
  1348. {
  1349. this->Doing = DoingPattern;
  1350. }
  1351. else if(arg == "REGEX")
  1352. {
  1353. this->Doing = DoingRegex;
  1354. }
  1355. else if(arg == "EXCLUDE")
  1356. {
  1357. // Add this property to the current match rule.
  1358. if(this->CurrentMatchRule)
  1359. {
  1360. this->CurrentMatchRule->Properties.Exclude = true;
  1361. this->Doing = DoingNone;
  1362. }
  1363. else
  1364. {
  1365. this->NotBeforeMatch(arg);
  1366. }
  1367. }
  1368. else if(arg == "PERMISSIONS")
  1369. {
  1370. if(this->CurrentMatchRule)
  1371. {
  1372. this->Doing = DoingPermissionsMatch;
  1373. }
  1374. else
  1375. {
  1376. this->NotBeforeMatch(arg);
  1377. }
  1378. }
  1379. else if(arg == "FILE_PERMISSIONS")
  1380. {
  1381. if(this->CurrentMatchRule)
  1382. {
  1383. this->NotAfterMatch(arg);
  1384. }
  1385. else
  1386. {
  1387. this->Doing = DoingPermissionsFile;
  1388. this->UseGivenPermissionsFile = true;
  1389. }
  1390. }
  1391. else if(arg == "DIRECTORY_PERMISSIONS")
  1392. {
  1393. if(this->CurrentMatchRule)
  1394. {
  1395. this->NotAfterMatch(arg);
  1396. }
  1397. else
  1398. {
  1399. this->Doing = DoingPermissionsDir;
  1400. this->UseGivenPermissionsDir = true;
  1401. }
  1402. }
  1403. else if(arg == "USE_SOURCE_PERMISSIONS")
  1404. {
  1405. if(this->CurrentMatchRule)
  1406. {
  1407. this->NotAfterMatch(arg);
  1408. }
  1409. else
  1410. {
  1411. this->Doing = DoingNone;
  1412. this->UseSourcePermissions = true;
  1413. }
  1414. }
  1415. else if(arg == "NO_SOURCE_PERMISSIONS")
  1416. {
  1417. if(this->CurrentMatchRule)
  1418. {
  1419. this->NotAfterMatch(arg);
  1420. }
  1421. else
  1422. {
  1423. this->Doing = DoingNone;
  1424. this->UseSourcePermissions = false;
  1425. }
  1426. }
  1427. else if(arg == "FILES_MATCHING")
  1428. {
  1429. if(this->CurrentMatchRule)
  1430. {
  1431. this->NotAfterMatch(arg);
  1432. }
  1433. else
  1434. {
  1435. this->Doing = DoingNone;
  1436. this->MatchlessFiles = false;
  1437. }
  1438. }
  1439. else
  1440. {
  1441. return false;
  1442. }
  1443. return true;
  1444. }
  1445. //----------------------------------------------------------------------------
  1446. bool cmFileCopier::CheckValue(std::string const& arg)
  1447. {
  1448. switch(this->Doing)
  1449. {
  1450. case DoingFiles:
  1451. if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
  1452. {
  1453. this->Files.push_back(arg);
  1454. }
  1455. else
  1456. {
  1457. std::string file = this->Makefile->GetCurrentSourceDirectory();
  1458. file += "/" + arg;
  1459. this->Files.push_back(file);
  1460. }
  1461. break;
  1462. case DoingDestination:
  1463. if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
  1464. {
  1465. this->Destination = arg;
  1466. }
  1467. else
  1468. {
  1469. this->Destination = this->Makefile->GetCurrentBinaryDirectory();
  1470. this->Destination += "/" + arg;
  1471. }
  1472. this->Doing = DoingNone;
  1473. break;
  1474. case DoingPattern:
  1475. {
  1476. // Convert the pattern to a regular expression. Require a
  1477. // leading slash and trailing end-of-string in the matched
  1478. // string to make sure the pattern matches only whole file
  1479. // names.
  1480. std::string regex = "/";
  1481. regex += cmsys::Glob::PatternToRegex(arg, false);
  1482. regex += "$";
  1483. this->MatchRules.push_back(MatchRule(regex));
  1484. this->CurrentMatchRule = &*(this->MatchRules.end()-1);
  1485. if(this->CurrentMatchRule->Regex.is_valid())
  1486. {
  1487. this->Doing = DoingNone;
  1488. }
  1489. else
  1490. {
  1491. std::ostringstream e;
  1492. e << "could not compile PATTERN \"" << arg << "\".";
  1493. this->FileCommand->SetError(e.str());
  1494. this->Doing = DoingError;
  1495. }
  1496. }
  1497. break;
  1498. case DoingRegex:
  1499. this->MatchRules.push_back(MatchRule(arg));
  1500. this->CurrentMatchRule = &*(this->MatchRules.end()-1);
  1501. if(this->CurrentMatchRule->Regex.is_valid())
  1502. {
  1503. this->Doing = DoingNone;
  1504. }
  1505. else
  1506. {
  1507. std::ostringstream e;
  1508. e << "could not compile REGEX \"" << arg << "\".";
  1509. this->FileCommand->SetError(e.str());
  1510. this->Doing = DoingError;
  1511. }
  1512. break;
  1513. case DoingPermissionsFile:
  1514. if(!this->CheckPermissions(arg, this->FilePermissions))
  1515. {
  1516. this->Doing = DoingError;
  1517. }
  1518. break;
  1519. case DoingPermissionsDir:
  1520. if(!this->CheckPermissions(arg, this->DirPermissions))
  1521. {
  1522. this->Doing = DoingError;
  1523. }
  1524. break;
  1525. case DoingPermissionsMatch:
  1526. if(!this->CheckPermissions(
  1527. arg, this->CurrentMatchRule->Properties.Permissions))
  1528. {
  1529. this->Doing = DoingError;
  1530. }
  1531. break;
  1532. default:
  1533. return false;
  1534. }
  1535. return true;
  1536. }
  1537. //----------------------------------------------------------------------------
  1538. bool cmFileCopier::Run(std::vector<std::string> const& args)
  1539. {
  1540. if(!this->Parse(args))
  1541. {
  1542. return false;
  1543. }
  1544. std::vector<std::string> const& files = this->Files;
  1545. for(std::vector<std::string>::size_type i = 0; i < files.size(); ++i)
  1546. {
  1547. // Split the input file into its directory and name components.
  1548. std::vector<std::string> fromPathComponents;
  1549. cmSystemTools::SplitPath(files[i], fromPathComponents);
  1550. std::string fromName = *(fromPathComponents.end()-1);
  1551. std::string fromDir = cmSystemTools::JoinPath(fromPathComponents.begin(),
  1552. fromPathComponents.end()-1);
  1553. // Compute the full path to the destination file.
  1554. std::string toFile = this->Destination;
  1555. std::string const& toName = this->ToName(fromName);
  1556. if(!toName.empty())
  1557. {
  1558. toFile += "/";
  1559. toFile += toName;
  1560. }
  1561. // Construct the full path to the source file. The file name may
  1562. // have been changed above.
  1563. std::string fromFile = fromDir;
  1564. if(!fromName.empty())
  1565. {
  1566. fromFile += "/";
  1567. fromFile += fromName;
  1568. }
  1569. if(!this->Install(fromFile.c_str(), toFile.c_str()))
  1570. {
  1571. return false;
  1572. }
  1573. }
  1574. return true;
  1575. }
  1576. //----------------------------------------------------------------------------
  1577. bool cmFileCopier::Install(const char* fromFile, const char* toFile)
  1578. {
  1579. if(!*fromFile)
  1580. {
  1581. std::ostringstream e;
  1582. e << "INSTALL encountered an empty string input file name.";
  1583. this->FileCommand->SetError(e.str());
  1584. return false;
  1585. }
  1586. // Collect any properties matching this file name.
  1587. MatchProperties match_properties = this->CollectMatchProperties(fromFile);
  1588. // Skip the file if it is excluded.
  1589. if(match_properties.Exclude)
  1590. {
  1591. return true;
  1592. }
  1593. if(cmSystemTools::SameFile(fromFile, toFile))
  1594. {
  1595. return true;
  1596. }
  1597. else if(cmSystemTools::FileIsSymlink(fromFile))
  1598. {
  1599. return this->InstallSymlink(fromFile, toFile);
  1600. }
  1601. else if(cmSystemTools::FileIsDirectory(fromFile))
  1602. {
  1603. return this->InstallDirectory(fromFile, toFile, match_properties);
  1604. }
  1605. else if(cmSystemTools::FileExists(fromFile))
  1606. {
  1607. return this->InstallFile(fromFile, toFile, match_properties);
  1608. }
  1609. return this->ReportMissing(fromFile);
  1610. }
  1611. //----------------------------------------------------------------------------
  1612. bool cmFileCopier::InstallSymlink(const char* fromFile, const char* toFile)
  1613. {
  1614. // Read the original symlink.
  1615. std::string symlinkTarget;
  1616. if(!cmSystemTools::ReadSymlink(fromFile, symlinkTarget))
  1617. {
  1618. std::ostringstream e;
  1619. e << this->Name << " cannot read symlink \"" << fromFile
  1620. << "\" to duplicate at \"" << toFile << "\".";
  1621. this->FileCommand->SetError(e.str());
  1622. return false;
  1623. }
  1624. // Compare the symlink value to that at the destination if not
  1625. // always installing.
  1626. bool copy = true;
  1627. if(!this->Always)
  1628. {
  1629. std::string oldSymlinkTarget;
  1630. if(cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget))
  1631. {
  1632. if(symlinkTarget == oldSymlinkTarget)
  1633. {
  1634. copy = false;
  1635. }
  1636. }
  1637. }
  1638. // Inform the user about this file installation.
  1639. this->ReportCopy(toFile, TypeLink, copy);
  1640. if(copy)
  1641. {
  1642. // Remove the destination file so we can always create the symlink.
  1643. cmSystemTools::RemoveFile(toFile);
  1644. // Create the symlink.
  1645. if(!cmSystemTools::CreateSymlink(symlinkTarget, toFile))
  1646. {
  1647. std::ostringstream e;
  1648. e << this->Name << " cannot duplicate symlink \"" << fromFile
  1649. << "\" at \"" << toFile << "\".";
  1650. this->FileCommand->SetError(e.str());
  1651. return false;
  1652. }
  1653. }
  1654. return true;
  1655. }
  1656. //----------------------------------------------------------------------------
  1657. bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile,
  1658. MatchProperties const& match_properties)
  1659. {
  1660. // Determine whether we will copy the file.
  1661. bool copy = true;
  1662. if(!this->Always)
  1663. {
  1664. // If both files exist with the same time do not copy.
  1665. if(!this->FileTimes.FileTimesDiffer(fromFile, toFile))
  1666. {
  1667. copy = false;
  1668. }
  1669. }
  1670. // Inform the user about this file installation.
  1671. this->ReportCopy(toFile, TypeFile, copy);
  1672. // Copy the file.
  1673. if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true))
  1674. {
  1675. std::ostringstream e;
  1676. e << this->Name << " cannot copy file \"" << fromFile
  1677. << "\" to \"" << toFile << "\".";
  1678. this->FileCommand->SetError(e.str());
  1679. return false;
  1680. }
  1681. // Set the file modification time of the destination file.
  1682. if(copy && !this->Always)
  1683. {
  1684. // Add write permission so we can set the file time.
  1685. // Permissions are set unconditionally below anyway.
  1686. mode_t perm = 0;
  1687. if(cmSystemTools::GetPermissions(toFile, perm))
  1688. {
  1689. cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
  1690. }
  1691. if (!cmSystemTools::CopyFileTime(fromFile, toFile))
  1692. {
  1693. std::ostringstream e;
  1694. e << this->Name << " cannot set modification time on \""
  1695. << toFile << "\"";
  1696. this->FileCommand->SetError(e.str());
  1697. return false;
  1698. }
  1699. }
  1700. // Set permissions of the destination file.
  1701. mode_t permissions = (match_properties.Permissions?
  1702. match_properties.Permissions : this->FilePermissions);
  1703. if(!permissions)
  1704. {
  1705. // No permissions were explicitly provided but the user requested
  1706. // that the source file permissions be used.
  1707. cmSystemTools::GetPermissions(fromFile, permissions);
  1708. }
  1709. return this->SetPermissions(toFile, permissions);
  1710. }
  1711. //----------------------------------------------------------------------------
  1712. bool cmFileCopier::InstallDirectory(const char* source,
  1713. const char* destination,
  1714. MatchProperties const& match_properties)
  1715. {
  1716. // Inform the user about this directory installation.
  1717. this->ReportCopy(destination, TypeDir,
  1718. !cmSystemTools::FileIsDirectory(destination));
  1719. // Make sure the destination directory exists.
  1720. if(!cmSystemTools::MakeDirectory(destination))
  1721. {
  1722. std::ostringstream e;
  1723. e << this->Name << " cannot make directory \"" << destination << "\": "
  1724. << cmSystemTools::GetLastSystemError();
  1725. this->FileCommand->SetError(e.str());
  1726. return false;
  1727. }
  1728. // Compute the requested permissions for the destination directory.
  1729. mode_t permissions = (match_properties.Permissions?
  1730. match_properties.Permissions : this->DirPermissions);
  1731. if(!permissions)
  1732. {
  1733. // No permissions were explicitly provided but the user requested
  1734. // that the source directory permissions be used.
  1735. cmSystemTools::GetPermissions(source, permissions);
  1736. }
  1737. // Compute the set of permissions required on this directory to
  1738. // recursively install files and subdirectories safely.
  1739. mode_t required_permissions =
  1740. mode_owner_read | mode_owner_write | mode_owner_execute;
  1741. // If the required permissions are specified it is safe to set the
  1742. // final permissions now. Otherwise we must add the required
  1743. // permissions temporarily during file installation.
  1744. mode_t permissions_before = 0;
  1745. mode_t permissions_after = 0;
  1746. if((permissions & required_permissions) == required_permissions)
  1747. {
  1748. permissions_before = permissions;
  1749. }
  1750. else
  1751. {
  1752. permissions_before = permissions | required_permissions;
  1753. permissions_after = permissions;
  1754. }
  1755. // Set the required permissions of the destination directory.
  1756. if(!this->SetPermissions(destination, permissions_before))
  1757. {
  1758. return false;
  1759. }
  1760. // Load the directory contents to traverse it recursively.
  1761. cmsys::Directory dir;
  1762. if(source && *source)
  1763. {
  1764. dir.Load(source);
  1765. }
  1766. unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
  1767. for(unsigned long fileNum = 0; fileNum < numFiles; ++fileNum)
  1768. {
  1769. if(!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
  1770. strcmp(dir.GetFile(fileNum), "..") == 0))
  1771. {
  1772. std::string fromPath = source;
  1773. fromPath += "/";
  1774. fromPath += dir.GetFile(fileNum);
  1775. std::string toPath = destination;
  1776. toPath += "/";
  1777. toPath += dir.GetFile(fileNum);
  1778. if(!this->Install(fromPath.c_str(), toPath.c_str()))
  1779. {
  1780. return false;
  1781. }
  1782. }
  1783. }
  1784. // Set the requested permissions of the destination directory.
  1785. return this->SetPermissions(destination, permissions_after);
  1786. }
  1787. //----------------------------------------------------------------------------
  1788. bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
  1789. {
  1790. cmFileCopier copier(this);
  1791. return copier.Run(args);
  1792. }
  1793. //----------------------------------------------------------------------------
  1794. struct cmFileInstaller: public cmFileCopier
  1795. {
  1796. cmFileInstaller(cmFileCommand* command):
  1797. cmFileCopier(command, "INSTALL"),
  1798. InstallType(cmInstallType_FILES),
  1799. Optional(false),
  1800. MessageAlways(false),
  1801. MessageLazy(false),
  1802. MessageNever(false),
  1803. DestDirLength(0)
  1804. {
  1805. // Installation does not use source permissions by default.
  1806. this->UseSourcePermissions = false;
  1807. // Check whether to copy files always or only if they have changed.
  1808. this->Always =
  1809. cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS"));
  1810. // Get the current manifest.
  1811. this->Manifest =
  1812. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
  1813. }
  1814. ~cmFileInstaller()
  1815. {
  1816. // Save the updated install manifest.
  1817. this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
  1818. this->Manifest.c_str());
  1819. }
  1820. protected:
  1821. cmInstallType InstallType;
  1822. bool Optional;
  1823. bool MessageAlways;
  1824. bool MessageLazy;
  1825. bool MessageNever;
  1826. int DestDirLength;
  1827. std::string Rename;
  1828. std::string Manifest;
  1829. void ManifestAppend(std::string const& file)
  1830. {
  1831. if (!this->Manifest.empty())
  1832. {
  1833. this->Manifest += ";";
  1834. }
  1835. this->Manifest += file.substr(this->DestDirLength);
  1836. }
  1837. virtual std::string const& ToName(std::string const& fromName)
  1838. { return this->Rename.empty()? fromName : this->Rename; }
  1839. virtual void ReportCopy(const char* toFile, Type type, bool copy)
  1840. {
  1841. if(!this->MessageNever && (copy || !this->MessageLazy))
  1842. {
  1843. std::string message = (copy? "Installing: " : "Up-to-date: ");
  1844. message += toFile;
  1845. this->Makefile->DisplayStatus(message.c_str(), -1);
  1846. }
  1847. if(type != TypeDir)
  1848. {
  1849. // Add the file to the manifest.
  1850. this->ManifestAppend(toFile);
  1851. }
  1852. }
  1853. virtual bool ReportMissing(const char* fromFile)
  1854. {
  1855. return (this->Optional ||
  1856. this->cmFileCopier::ReportMissing(fromFile));
  1857. }
  1858. virtual bool Install(const char* fromFile, const char* toFile)
  1859. {
  1860. // Support installing from empty source to make a directory.
  1861. if(this->InstallType == cmInstallType_DIRECTORY && !*fromFile)
  1862. {
  1863. return this->InstallDirectory(fromFile, toFile, MatchProperties());
  1864. }
  1865. return this->cmFileCopier::Install(fromFile, toFile);
  1866. }
  1867. virtual bool Parse(std::vector<std::string> const& args);
  1868. enum
  1869. {
  1870. DoingType = DoingLast1,
  1871. DoingRename,
  1872. DoingLast2
  1873. };
  1874. virtual bool CheckKeyword(std::string const& arg);
  1875. virtual bool CheckValue(std::string const& arg);
  1876. virtual void DefaultFilePermissions()
  1877. {
  1878. this->cmFileCopier::DefaultFilePermissions();
  1879. // Add execute permissions based on the target type.
  1880. switch(this->InstallType)
  1881. {
  1882. case cmInstallType_SHARED_LIBRARY:
  1883. case cmInstallType_MODULE_LIBRARY:
  1884. if(this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE"))
  1885. {
  1886. break;
  1887. }
  1888. case cmInstallType_EXECUTABLE:
  1889. case cmInstallType_PROGRAMS:
  1890. this->FilePermissions |= mode_owner_execute;
  1891. this->FilePermissions |= mode_group_execute;
  1892. this->FilePermissions |= mode_world_execute;
  1893. break;
  1894. default: break;
  1895. }
  1896. }
  1897. bool GetTargetTypeFromString(const std::string& stype);
  1898. bool HandleInstallDestination();
  1899. };
  1900. //----------------------------------------------------------------------------
  1901. bool cmFileInstaller::Parse(std::vector<std::string> const& args)
  1902. {
  1903. if(!this->cmFileCopier::Parse(args))
  1904. {
  1905. return false;
  1906. }
  1907. if(!this->Rename.empty())
  1908. {
  1909. if(this->InstallType != cmInstallType_FILES &&
  1910. this->InstallType != cmInstallType_PROGRAMS)
  1911. {
  1912. this->FileCommand->SetError("INSTALL option RENAME may be used "
  1913. "only with FILES or PROGRAMS.");
  1914. return false;
  1915. }
  1916. if(this->Files.size() > 1)
  1917. {
  1918. this->FileCommand->SetError("INSTALL option RENAME may be used "
  1919. "only with one file.");
  1920. return false;
  1921. }
  1922. }
  1923. if(!this->HandleInstallDestination())
  1924. {
  1925. return false;
  1926. }
  1927. if(((this->MessageAlways?1:0) +
  1928. (this->MessageLazy?1:0) +
  1929. (this->MessageNever?1:0)) > 1)
  1930. {
  1931. this->FileCommand->SetError("INSTALL options MESSAGE_ALWAYS, "
  1932. "MESSAGE_LAZY, and MESSAGE_NEVER "
  1933. "are mutually exclusive.");
  1934. return false;
  1935. }
  1936. return true;
  1937. }
  1938. //----------------------------------------------------------------------------
  1939. bool cmFileInstaller::CheckKeyword(std::string const& arg)
  1940. {
  1941. if(arg == "TYPE")
  1942. {
  1943. if(this->CurrentMatchRule)
  1944. {
  1945. this->NotAfterMatch(arg);
  1946. }
  1947. else
  1948. {
  1949. this->Doing = DoingType;
  1950. }
  1951. }
  1952. else if(arg == "FILES")
  1953. {
  1954. if(this->CurrentMatchRule)
  1955. {
  1956. this->NotAfterMatch(arg);
  1957. }
  1958. else
  1959. {
  1960. this->Doing = DoingFiles;
  1961. }
  1962. }
  1963. else if(arg == "RENAME")
  1964. {
  1965. if(this->CurrentMatchRule)
  1966. {
  1967. this->NotAfterMatch(arg);
  1968. }
  1969. else
  1970. {
  1971. this->Doing = DoingRename;
  1972. }
  1973. }
  1974. else if(arg == "OPTIONAL")
  1975. {
  1976. if(this->CurrentMatchRule)
  1977. {
  1978. this->NotAfterMatch(arg);
  1979. }
  1980. else
  1981. {
  1982. this->Doing = DoingNone;
  1983. this->Optional = true;
  1984. }
  1985. }
  1986. else if(arg == "MESSAGE_ALWAYS")
  1987. {
  1988. if(this->CurrentMatchRule)
  1989. {
  1990. this->NotAfterMatch(arg);
  1991. }
  1992. else
  1993. {
  1994. this->Doing = DoingNone;
  1995. this->MessageAlways = true;
  1996. }
  1997. }
  1998. else if(arg == "MESSAGE_LAZY")
  1999. {
  2000. if(this->CurrentMatchRule)
  2001. {
  2002. this->NotAfterMatch(arg);
  2003. }
  2004. else
  2005. {
  2006. this->Doing = DoingNone;
  2007. this->MessageLazy = true;
  2008. }
  2009. }
  2010. else if(arg == "MESSAGE_NEVER")
  2011. {
  2012. if(this->CurrentMatchRule)
  2013. {
  2014. this->NotAfterMatch(arg);
  2015. }
  2016. else
  2017. {
  2018. this->Doing = DoingNone;
  2019. this->MessageNever = true;
  2020. }
  2021. }
  2022. else if(arg == "PERMISSIONS")
  2023. {
  2024. if(this->CurrentMatchRule)
  2025. {
  2026. this->Doing = DoingPermissionsMatch;
  2027. }
  2028. else
  2029. {
  2030. // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
  2031. this->Doing = DoingPermissionsFile;
  2032. this->UseGivenPermissionsFile = true;
  2033. }
  2034. }
  2035. else if(arg == "DIR_PERMISSIONS")
  2036. {
  2037. if(this->CurrentMatchRule)
  2038. {
  2039. this->NotAfterMatch(arg);
  2040. }
  2041. else
  2042. {
  2043. // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
  2044. this->Doing = DoingPermissionsDir;
  2045. this->UseGivenPermissionsDir = true;
  2046. }
  2047. }
  2048. else if(arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
  2049. arg == "PROPERTIES")
  2050. {
  2051. std::ostringstream e;
  2052. e << "INSTALL called with old-style " << arg << " argument. "
  2053. << "This script was generated with an older version of CMake. "
  2054. << "Re-run this cmake version on your build tree.";
  2055. this->FileCommand->SetError(e.str());
  2056. this->Doing = DoingError;
  2057. }
  2058. else
  2059. {
  2060. return this->cmFileCopier::CheckKeyword(arg);
  2061. }
  2062. return true;
  2063. }
  2064. //----------------------------------------------------------------------------
  2065. bool cmFileInstaller::CheckValue(std::string const& arg)
  2066. {
  2067. switch(this->Doing)
  2068. {
  2069. case DoingType:
  2070. if(!this->GetTargetTypeFromString(arg))
  2071. {
  2072. this->Doing = DoingError;
  2073. }
  2074. break;
  2075. case DoingRename:
  2076. this->Rename = arg;
  2077. break;
  2078. default:
  2079. return this->cmFileCopier::CheckValue(arg);
  2080. }
  2081. return true;
  2082. }
  2083. //----------------------------------------------------------------------------
  2084. bool cmFileInstaller
  2085. ::GetTargetTypeFromString(const std::string& stype)
  2086. {
  2087. if ( stype == "EXECUTABLE" )
  2088. {
  2089. this->InstallType = cmInstallType_EXECUTABLE;
  2090. }
  2091. else if ( stype == "FILE" )
  2092. {
  2093. this->InstallType = cmInstallType_FILES;
  2094. }
  2095. else if ( stype == "PROGRAM" )
  2096. {
  2097. this->InstallType = cmInstallType_PROGRAMS;
  2098. }
  2099. else if ( stype == "STATIC_LIBRARY" )
  2100. {
  2101. this->InstallType = cmInstallType_STATIC_LIBRARY;
  2102. }
  2103. else if ( stype == "SHARED_LIBRARY" )
  2104. {
  2105. this->InstallType = cmInstallType_SHARED_LIBRARY;
  2106. }
  2107. else if ( stype == "MODULE" )
  2108. {
  2109. this->InstallType = cmInstallType_MODULE_LIBRARY;
  2110. }
  2111. else if ( stype == "DIRECTORY" )
  2112. {
  2113. this->InstallType = cmInstallType_DIRECTORY;
  2114. }
  2115. else
  2116. {
  2117. std::ostringstream e;
  2118. e << "Option TYPE given unknown value \"" << stype << "\".";
  2119. this->FileCommand->SetError(e.str());
  2120. return false;
  2121. }
  2122. return true;
  2123. }
  2124. //----------------------------------------------------------------------------
  2125. bool cmFileInstaller::HandleInstallDestination()
  2126. {
  2127. std::string& destination = this->Destination;
  2128. // allow for / to be a valid destination
  2129. if ( destination.size() < 2 && destination != "/" )
  2130. {
  2131. this->FileCommand->SetError("called with inappropriate arguments. "
  2132. "No DESTINATION provided or .");
  2133. return false;
  2134. }
  2135. const char* destdir = cmSystemTools::GetEnv("DESTDIR");
  2136. if ( destdir && *destdir )
  2137. {
  2138. std::string sdestdir = destdir;
  2139. cmSystemTools::ConvertToUnixSlashes(sdestdir);
  2140. char ch1 = destination[0];
  2141. char ch2 = destination[1];
  2142. char ch3 = 0;
  2143. if ( destination.size() > 2 )
  2144. {
  2145. ch3 = destination[2];
  2146. }
  2147. int skip = 0;
  2148. if ( ch1 != '/' )
  2149. {
  2150. int relative = 0;
  2151. if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
  2152. ch2 == ':' )
  2153. {
  2154. // Assume windows
  2155. // let's do some destdir magic:
  2156. skip = 2;
  2157. if ( ch3 != '/' )
  2158. {
  2159. relative = 1;
  2160. }
  2161. }
  2162. else
  2163. {
  2164. relative = 1;
  2165. }
  2166. if ( relative )
  2167. {
  2168. // This is relative path on unix or windows. Since we are doing
  2169. // destdir, this case does not make sense.
  2170. this->FileCommand->SetError(
  2171. "called with relative DESTINATION. This "
  2172. "does not make sense when using DESTDIR. Specify "
  2173. "absolute path or remove DESTDIR environment variable.");
  2174. return false;
  2175. }
  2176. }
  2177. else
  2178. {
  2179. if ( ch2 == '/' )
  2180. {
  2181. // looks like a network path.
  2182. std::string message = "called with network path DESTINATION. This "
  2183. "does not make sense when using DESTDIR. Specify local "
  2184. "absolute path or remove DESTDIR environment variable."
  2185. "\nDESTINATION=\n";
  2186. message += destination;
  2187. this->FileCommand->SetError(message);
  2188. return false;
  2189. }
  2190. }
  2191. destination = sdestdir + (destination.c_str() + skip);
  2192. this->DestDirLength = int(sdestdir.size());
  2193. }
  2194. if(this->InstallType != cmInstallType_DIRECTORY)
  2195. {
  2196. if ( !cmSystemTools::FileExists(destination.c_str()) )
  2197. {
  2198. if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
  2199. {
  2200. std::string errstring = "cannot create directory: " + destination +
  2201. ". Maybe need administrative privileges.";
  2202. this->FileCommand->SetError(errstring);
  2203. return false;
  2204. }
  2205. }
  2206. if ( !cmSystemTools::FileIsDirectory(destination) )
  2207. {
  2208. std::string errstring = "INSTALL destination: " + destination +
  2209. " is not a directory.";
  2210. this->FileCommand->SetError(errstring);
  2211. return false;
  2212. }
  2213. }
  2214. return true;
  2215. }
  2216. //----------------------------------------------------------------------------
  2217. bool
  2218. cmFileCommand::HandleRPathChangeCommand(std::vector<std::string> const& args)
  2219. {
  2220. // Evaluate arguments.
  2221. const char* file = 0;
  2222. const char* oldRPath = 0;
  2223. const char* newRPath = 0;
  2224. enum Doing { DoingNone, DoingFile, DoingOld, DoingNew };
  2225. Doing doing = DoingNone;
  2226. for(unsigned int i=1; i < args.size(); ++i)
  2227. {
  2228. if(args[i] == "OLD_RPATH")
  2229. {
  2230. doing = DoingOld;
  2231. }
  2232. else if(args[i] == "NEW_RPATH")
  2233. {
  2234. doing = DoingNew;
  2235. }
  2236. else if(args[i] == "FILE")
  2237. {
  2238. doing = DoingFile;
  2239. }
  2240. else if(doing == DoingFile)
  2241. {
  2242. file = args[i].c_str();
  2243. doing = DoingNone;
  2244. }
  2245. else if(doing == DoingOld)
  2246. {
  2247. oldRPath = args[i].c_str();
  2248. doing = DoingNone;
  2249. }
  2250. else if(doing == DoingNew)
  2251. {
  2252. newRPath = args[i].c_str();
  2253. doing = DoingNone;
  2254. }
  2255. else
  2256. {
  2257. std::ostringstream e;
  2258. e << "RPATH_CHANGE given unknown argument " << args[i];
  2259. this->SetError(e.str());
  2260. return false;
  2261. }
  2262. }
  2263. if(!file)
  2264. {
  2265. this->SetError("RPATH_CHANGE not given FILE option.");
  2266. return false;
  2267. }
  2268. if(!oldRPath)
  2269. {
  2270. this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
  2271. return false;
  2272. }
  2273. if(!newRPath)
  2274. {
  2275. this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
  2276. return false;
  2277. }
  2278. if(!cmSystemTools::FileExists(file, true))
  2279. {
  2280. std::ostringstream e;
  2281. e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
  2282. this->SetError(e.str());
  2283. return false;
  2284. }
  2285. bool success = true;
  2286. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  2287. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  2288. std::string emsg;
  2289. bool changed;
  2290. if(!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed))
  2291. {
  2292. std::ostringstream e;
  2293. e << "RPATH_CHANGE could not write new RPATH:\n"
  2294. << " " << newRPath << "\n"
  2295. << "to the file:\n"
  2296. << " " << file << "\n"
  2297. << emsg;
  2298. this->SetError(e.str());
  2299. success = false;
  2300. }
  2301. if(success)
  2302. {
  2303. if(changed)
  2304. {
  2305. std::string message = "Set runtime path of \"";
  2306. message += file;
  2307. message += "\" to \"";
  2308. message += newRPath;
  2309. message += "\"";
  2310. this->Makefile->DisplayStatus(message.c_str(), -1);
  2311. }
  2312. if(have_ft)
  2313. {
  2314. cmSystemTools::FileTimeSet(file, ft);
  2315. }
  2316. }
  2317. cmSystemTools::FileTimeDelete(ft);
  2318. return success;
  2319. }
  2320. //----------------------------------------------------------------------------
  2321. bool
  2322. cmFileCommand::HandleRPathRemoveCommand(std::vector<std::string> const& args)
  2323. {
  2324. // Evaluate arguments.
  2325. const char* file = 0;
  2326. enum Doing { DoingNone, DoingFile };
  2327. Doing doing = DoingNone;
  2328. for(unsigned int i=1; i < args.size(); ++i)
  2329. {
  2330. if(args[i] == "FILE")
  2331. {
  2332. doing = DoingFile;
  2333. }
  2334. else if(doing == DoingFile)
  2335. {
  2336. file = args[i].c_str();
  2337. doing = DoingNone;
  2338. }
  2339. else
  2340. {
  2341. std::ostringstream e;
  2342. e << "RPATH_REMOVE given unknown argument " << args[i];
  2343. this->SetError(e.str());
  2344. return false;
  2345. }
  2346. }
  2347. if(!file)
  2348. {
  2349. this->SetError("RPATH_REMOVE not given FILE option.");
  2350. return false;
  2351. }
  2352. if(!cmSystemTools::FileExists(file, true))
  2353. {
  2354. std::ostringstream e;
  2355. e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
  2356. this->SetError(e.str());
  2357. return false;
  2358. }
  2359. bool success = true;
  2360. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  2361. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  2362. std::string emsg;
  2363. bool removed;
  2364. if(!cmSystemTools::RemoveRPath(file, &emsg, &removed))
  2365. {
  2366. std::ostringstream e;
  2367. e << "RPATH_REMOVE could not remove RPATH from file:\n"
  2368. << " " << file << "\n"
  2369. << emsg;
  2370. this->SetError(e.str());
  2371. success = false;
  2372. }
  2373. if(success)
  2374. {
  2375. if(removed)
  2376. {
  2377. std::string message = "Removed runtime path from \"";
  2378. message += file;
  2379. message += "\"";
  2380. this->Makefile->DisplayStatus(message.c_str(), -1);
  2381. }
  2382. if(have_ft)
  2383. {
  2384. cmSystemTools::FileTimeSet(file, ft);
  2385. }
  2386. }
  2387. cmSystemTools::FileTimeDelete(ft);
  2388. return success;
  2389. }
  2390. //----------------------------------------------------------------------------
  2391. bool
  2392. cmFileCommand::HandleRPathCheckCommand(std::vector<std::string> const& args)
  2393. {
  2394. // Evaluate arguments.
  2395. const char* file = 0;
  2396. const char* rpath = 0;
  2397. enum Doing { DoingNone, DoingFile, DoingRPath };
  2398. Doing doing = DoingNone;
  2399. for(unsigned int i=1; i < args.size(); ++i)
  2400. {
  2401. if(args[i] == "RPATH")
  2402. {
  2403. doing = DoingRPath;
  2404. }
  2405. else if(args[i] == "FILE")
  2406. {
  2407. doing = DoingFile;
  2408. }
  2409. else if(doing == DoingFile)
  2410. {
  2411. file = args[i].c_str();
  2412. doing = DoingNone;
  2413. }
  2414. else if(doing == DoingRPath)
  2415. {
  2416. rpath = args[i].c_str();
  2417. doing = DoingNone;
  2418. }
  2419. else
  2420. {
  2421. std::ostringstream e;
  2422. e << "RPATH_CHECK given unknown argument " << args[i];
  2423. this->SetError(e.str());
  2424. return false;
  2425. }
  2426. }
  2427. if(!file)
  2428. {
  2429. this->SetError("RPATH_CHECK not given FILE option.");
  2430. return false;
  2431. }
  2432. if(!rpath)
  2433. {
  2434. this->SetError("RPATH_CHECK not given RPATH option.");
  2435. return false;
  2436. }
  2437. // If the file exists but does not have the desired RPath then
  2438. // delete it. This is used during installation to re-install a file
  2439. // if its RPath will change.
  2440. if(cmSystemTools::FileExists(file, true) &&
  2441. !cmSystemTools::CheckRPath(file, rpath))
  2442. {
  2443. cmSystemTools::RemoveFile(file);
  2444. }
  2445. return true;
  2446. }
  2447. //----------------------------------------------------------------------------
  2448. bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
  2449. {
  2450. cmFileInstaller installer(this);
  2451. return installer.Run(args);
  2452. }
  2453. //----------------------------------------------------------------------------
  2454. bool cmFileCommand::HandleRelativePathCommand(
  2455. std::vector<std::string> const& args)
  2456. {
  2457. if(args.size() != 4 )
  2458. {
  2459. this->SetError("RELATIVE_PATH called with incorrect number of arguments");
  2460. return false;
  2461. }
  2462. const std::string& outVar = args[1];
  2463. const std::string& directoryName = args[2];
  2464. const std::string& fileName = args[3];
  2465. if(!cmSystemTools::FileIsFullPath(directoryName.c_str()))
  2466. {
  2467. std::string errstring =
  2468. "RELATIVE_PATH must be passed a full path to the directory: "
  2469. + directoryName;
  2470. this->SetError(errstring);
  2471. return false;
  2472. }
  2473. if(!cmSystemTools::FileIsFullPath(fileName.c_str()))
  2474. {
  2475. std::string errstring =
  2476. "RELATIVE_PATH must be passed a full path to the file: "
  2477. + fileName;
  2478. this->SetError(errstring);
  2479. return false;
  2480. }
  2481. std::string res = cmSystemTools::RelativePath(directoryName.c_str(),
  2482. fileName.c_str());
  2483. this->Makefile->AddDefinition(outVar,
  2484. res.c_str());
  2485. return true;
  2486. }
  2487. //----------------------------------------------------------------------------
  2488. bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
  2489. {
  2490. if(args.size() != 3)
  2491. {
  2492. this->SetError("RENAME given incorrect number of arguments.");
  2493. return false;
  2494. }
  2495. // Compute full path for old and new names.
  2496. std::string oldname = args[1];
  2497. if(!cmsys::SystemTools::FileIsFullPath(oldname.c_str()))
  2498. {
  2499. oldname = this->Makefile->GetCurrentSourceDirectory();
  2500. oldname += "/" + args[1];
  2501. }
  2502. std::string newname = args[2];
  2503. if(!cmsys::SystemTools::FileIsFullPath(newname.c_str()))
  2504. {
  2505. newname = this->Makefile->GetCurrentSourceDirectory();
  2506. newname += "/" + args[2];
  2507. }
  2508. if(!cmSystemTools::RenameFile(oldname.c_str(), newname.c_str()))
  2509. {
  2510. std::string err = cmSystemTools::GetLastSystemError();
  2511. std::ostringstream e;
  2512. e << "RENAME failed to rename\n"
  2513. << " " << oldname << "\n"
  2514. << "to\n"
  2515. << " " << newname << "\n"
  2516. << "because: " << err << "\n";
  2517. this->SetError(e.str());
  2518. return false;
  2519. }
  2520. return true;
  2521. }
  2522. //----------------------------------------------------------------------------
  2523. bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
  2524. bool recurse)
  2525. {
  2526. std::string message;
  2527. std::vector<std::string>::const_iterator i = args.begin();
  2528. i++; // Get rid of subcommand
  2529. for(;i != args.end(); ++i)
  2530. {
  2531. std::string fileName = *i;
  2532. if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
  2533. {
  2534. fileName = this->Makefile->GetCurrentSourceDirectory();
  2535. fileName += "/" + *i;
  2536. }
  2537. if(cmSystemTools::FileIsDirectory(fileName) &&
  2538. !cmSystemTools::FileIsSymlink(fileName) && recurse)
  2539. {
  2540. cmSystemTools::RemoveADirectory(fileName);
  2541. }
  2542. else
  2543. {
  2544. cmSystemTools::RemoveFile(fileName);
  2545. }
  2546. }
  2547. return true;
  2548. }
  2549. //----------------------------------------------------------------------------
  2550. bool cmFileCommand::HandleCMakePathCommand(std::vector<std::string>
  2551. const& args,
  2552. bool nativePath)
  2553. {
  2554. std::vector<std::string>::const_iterator i = args.begin();
  2555. if(args.size() != 3)
  2556. {
  2557. this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  2558. "called with exactly three arguments.");
  2559. return false;
  2560. }
  2561. i++; // Get rid of subcommand
  2562. #if defined(_WIN32) && !defined(__CYGWIN__)
  2563. char pathSep = ';';
  2564. #else
  2565. char pathSep = ':';
  2566. #endif
  2567. std::vector<cmsys::String> path = cmSystemTools::SplitString(*i,
  2568. pathSep);
  2569. i++;
  2570. const char* var = i->c_str();
  2571. std::string value;
  2572. for(std::vector<cmsys::String>::iterator j = path.begin();
  2573. j != path.end(); ++j)
  2574. {
  2575. if(j != path.begin())
  2576. {
  2577. value += ";";
  2578. }
  2579. if(!nativePath)
  2580. {
  2581. cmSystemTools::ConvertToUnixSlashes(*j);
  2582. }
  2583. else
  2584. {
  2585. *j = cmSystemTools::ConvertToOutputPath(j->c_str());
  2586. // remove double quotes in the path
  2587. cmsys::String& s = *j;
  2588. if(s.size() > 1 && s[0] == '\"' && s[s.size()-1] == '\"')
  2589. {
  2590. s = s.substr(1,s.size()-2);
  2591. }
  2592. }
  2593. value += *j;
  2594. }
  2595. this->Makefile->AddDefinition(var, value.c_str());
  2596. return true;
  2597. }
  2598. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2599. // Stuff for curl download/upload
  2600. typedef std::vector<char> cmFileCommandVectorOfChar;
  2601. namespace {
  2602. size_t
  2603. cmWriteToFileCallback(void *ptr, size_t size, size_t nmemb,
  2604. void *data)
  2605. {
  2606. int realsize = (int)(size * nmemb);
  2607. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  2608. const char* chPtr = static_cast<char*>(ptr);
  2609. fout->write(chPtr, realsize);
  2610. return realsize;
  2611. }
  2612. size_t
  2613. cmWriteToMemoryCallback(void *ptr, size_t size, size_t nmemb,
  2614. void *data)
  2615. {
  2616. int realsize = (int)(size * nmemb);
  2617. cmFileCommandVectorOfChar *vec
  2618. = static_cast<cmFileCommandVectorOfChar*>(data);
  2619. const char* chPtr = static_cast<char*>(ptr);
  2620. vec->insert(vec->end(), chPtr, chPtr + realsize);
  2621. return realsize;
  2622. }
  2623. static size_t
  2624. cmFileCommandCurlDebugCallback(CURL *, curl_infotype type, char *chPtr,
  2625. size_t size, void *data)
  2626. {
  2627. cmFileCommandVectorOfChar *vec
  2628. = static_cast<cmFileCommandVectorOfChar*>(data);
  2629. switch(type)
  2630. {
  2631. case CURLINFO_TEXT:
  2632. case CURLINFO_HEADER_IN:
  2633. case CURLINFO_HEADER_OUT:
  2634. vec->insert(vec->end(), chPtr, chPtr + size);
  2635. break;
  2636. case CURLINFO_DATA_IN:
  2637. case CURLINFO_DATA_OUT:
  2638. case CURLINFO_SSL_DATA_IN:
  2639. case CURLINFO_SSL_DATA_OUT:
  2640. {
  2641. char buf[128];
  2642. int n = sprintf(buf, "[%" cmIML_INT_PRIu64 " bytes data]\n",
  2643. static_cast<cmIML_INT_uint64_t>(size));
  2644. if (n > 0)
  2645. {
  2646. vec->insert(vec->end(), buf, buf + n);
  2647. }
  2648. }
  2649. break;
  2650. default:
  2651. break;
  2652. }
  2653. return 0;
  2654. }
  2655. class cURLProgressHelper
  2656. {
  2657. public:
  2658. cURLProgressHelper(cmFileCommand *fc, const char *text)
  2659. {
  2660. this->CurrentPercentage = -1;
  2661. this->FileCommand = fc;
  2662. this->Text = text;
  2663. }
  2664. bool UpdatePercentage(double value, double total, std::string &status)
  2665. {
  2666. int OldPercentage = this->CurrentPercentage;
  2667. if (total > 0.0)
  2668. {
  2669. this->CurrentPercentage = static_cast<int>(value/total*100.0 + 0.5);
  2670. if(this->CurrentPercentage > 100)
  2671. {
  2672. // Avoid extra progress reports for unexpected data beyond total.
  2673. this->CurrentPercentage = 100;
  2674. }
  2675. }
  2676. bool updated = (OldPercentage != this->CurrentPercentage);
  2677. if (updated)
  2678. {
  2679. std::ostringstream oss;
  2680. oss << "[" << this->Text << " " << this->CurrentPercentage
  2681. << "% complete]";
  2682. status = oss.str();
  2683. }
  2684. return updated;
  2685. }
  2686. cmFileCommand *GetFileCommand()
  2687. {
  2688. return this->FileCommand;
  2689. }
  2690. private:
  2691. int CurrentPercentage;
  2692. cmFileCommand *FileCommand;
  2693. std::string Text;
  2694. };
  2695. static int
  2696. cmFileDownloadProgressCallback(void *clientp,
  2697. double dltotal, double dlnow,
  2698. double ultotal, double ulnow)
  2699. {
  2700. cURLProgressHelper *helper =
  2701. reinterpret_cast<cURLProgressHelper *>(clientp);
  2702. static_cast<void>(ultotal);
  2703. static_cast<void>(ulnow);
  2704. std::string status;
  2705. if (helper->UpdatePercentage(dlnow, dltotal, status))
  2706. {
  2707. cmFileCommand *fc = helper->GetFileCommand();
  2708. cmMakefile *mf = fc->GetMakefile();
  2709. mf->DisplayStatus(status.c_str(), -1);
  2710. }
  2711. return 0;
  2712. }
  2713. static int
  2714. cmFileUploadProgressCallback(void *clientp,
  2715. double dltotal, double dlnow,
  2716. double ultotal, double ulnow)
  2717. {
  2718. cURLProgressHelper *helper =
  2719. reinterpret_cast<cURLProgressHelper *>(clientp);
  2720. static_cast<void>(dltotal);
  2721. static_cast<void>(dlnow);
  2722. std::string status;
  2723. if (helper->UpdatePercentage(ulnow, ultotal, status))
  2724. {
  2725. cmFileCommand *fc = helper->GetFileCommand();
  2726. cmMakefile *mf = fc->GetMakefile();
  2727. mf->DisplayStatus(status.c_str(), -1);
  2728. }
  2729. return 0;
  2730. }
  2731. }
  2732. namespace {
  2733. class cURLEasyGuard
  2734. {
  2735. public:
  2736. cURLEasyGuard(CURL * easy)
  2737. : Easy(easy)
  2738. {}
  2739. ~cURLEasyGuard(void)
  2740. {
  2741. if (this->Easy)
  2742. {
  2743. ::curl_easy_cleanup(this->Easy);
  2744. }
  2745. }
  2746. inline void release(void)
  2747. {
  2748. this->Easy = 0;
  2749. return;
  2750. }
  2751. private:
  2752. ::CURL * Easy;
  2753. };
  2754. }
  2755. #endif
  2756. #define check_curl_result(result, errstr) \
  2757. if (result != CURLE_OK) \
  2758. { \
  2759. std::string e(errstr); \
  2760. e += ::curl_easy_strerror(result); \
  2761. this->SetError(e); \
  2762. return false; \
  2763. }
  2764. bool
  2765. cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
  2766. {
  2767. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2768. std::vector<std::string>::const_iterator i = args.begin();
  2769. if(args.size() < 3)
  2770. {
  2771. this->SetError("DOWNLOAD must be called with at least three arguments.");
  2772. return false;
  2773. }
  2774. ++i; // Get rid of subcommand
  2775. std::string url = *i;
  2776. ++i;
  2777. std::string file = *i;
  2778. ++i;
  2779. long timeout = 0;
  2780. long inactivity_timeout = 0;
  2781. std::string logVar;
  2782. std::string statusVar;
  2783. bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
  2784. const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
  2785. std::string expectedHash;
  2786. std::string hashMatchMSG;
  2787. cmsys::auto_ptr<cmCryptoHash> hash;
  2788. bool showProgress = false;
  2789. while(i != args.end())
  2790. {
  2791. if(*i == "TIMEOUT")
  2792. {
  2793. ++i;
  2794. if(i != args.end())
  2795. {
  2796. timeout = atol(i->c_str());
  2797. }
  2798. else
  2799. {
  2800. this->SetError("DOWNLOAD missing time for TIMEOUT.");
  2801. return false;
  2802. }
  2803. }
  2804. else if(*i == "INACTIVITY_TIMEOUT")
  2805. {
  2806. ++i;
  2807. if(i != args.end())
  2808. {
  2809. inactivity_timeout = atol(i->c_str());
  2810. }
  2811. else
  2812. {
  2813. this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  2814. return false;
  2815. }
  2816. }
  2817. else if(*i == "LOG")
  2818. {
  2819. ++i;
  2820. if( i == args.end())
  2821. {
  2822. this->SetError("DOWNLOAD missing VAR for LOG.");
  2823. return false;
  2824. }
  2825. logVar = *i;
  2826. }
  2827. else if(*i == "STATUS")
  2828. {
  2829. ++i;
  2830. if( i == args.end())
  2831. {
  2832. this->SetError("DOWNLOAD missing VAR for STATUS.");
  2833. return false;
  2834. }
  2835. statusVar = *i;
  2836. }
  2837. else if(*i == "TLS_VERIFY")
  2838. {
  2839. ++i;
  2840. if(i != args.end())
  2841. {
  2842. tls_verify = cmSystemTools::IsOn(i->c_str());
  2843. }
  2844. else
  2845. {
  2846. this->SetError("TLS_VERIFY missing bool value.");
  2847. return false;
  2848. }
  2849. }
  2850. else if(*i == "TLS_CAINFO")
  2851. {
  2852. ++i;
  2853. if(i != args.end())
  2854. {
  2855. cainfo = i->c_str();
  2856. }
  2857. else
  2858. {
  2859. this->SetError("TLS_CAFILE missing file value.");
  2860. return false;
  2861. }
  2862. }
  2863. else if(*i == "EXPECTED_MD5")
  2864. {
  2865. ++i;
  2866. if( i == args.end())
  2867. {
  2868. this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  2869. return false;
  2870. }
  2871. hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New("MD5"));
  2872. hashMatchMSG = "MD5 sum";
  2873. expectedHash = cmSystemTools::LowerCase(*i);
  2874. }
  2875. else if(*i == "SHOW_PROGRESS")
  2876. {
  2877. showProgress = true;
  2878. }
  2879. else if(*i == "EXPECTED_HASH")
  2880. {
  2881. ++i;
  2882. if(i == args.end())
  2883. {
  2884. this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  2885. return false;
  2886. }
  2887. std::string::size_type pos = i->find("=");
  2888. if(pos == std::string::npos)
  2889. {
  2890. std::string err =
  2891. "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
  2892. err += *i;
  2893. this->SetError(err);
  2894. return false;
  2895. }
  2896. std::string algo = i->substr(0, pos);
  2897. expectedHash = cmSystemTools::LowerCase(i->substr(pos+1));
  2898. hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
  2899. if(!hash.get())
  2900. {
  2901. std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
  2902. err += algo;
  2903. this->SetError(err);
  2904. return false;
  2905. }
  2906. hashMatchMSG = algo + " hash";
  2907. }
  2908. ++i;
  2909. }
  2910. // If file exists already, and caller specified an expected md5 or sha,
  2911. // and the existing file already has the expected hash, then simply
  2912. // return.
  2913. //
  2914. if(cmSystemTools::FileExists(file.c_str()) && hash.get())
  2915. {
  2916. std::string msg;
  2917. std::string actualHash = hash->HashFile(file);
  2918. if(actualHash == expectedHash)
  2919. {
  2920. msg = "returning early; file already exists with expected ";
  2921. msg += hashMatchMSG;
  2922. msg += "\"";
  2923. if(!statusVar.empty())
  2924. {
  2925. std::ostringstream result;
  2926. result << (int)0 << ";\"" << msg;
  2927. this->Makefile->AddDefinition(statusVar,
  2928. result.str().c_str());
  2929. }
  2930. return true;
  2931. }
  2932. }
  2933. // Make sure parent directory exists so we can write to the file
  2934. // as we receive downloaded bits from curl...
  2935. //
  2936. std::string dir = cmSystemTools::GetFilenamePath(file);
  2937. if(!cmSystemTools::FileExists(dir.c_str()) &&
  2938. !cmSystemTools::MakeDirectory(dir.c_str()))
  2939. {
  2940. std::string errstring = "DOWNLOAD error: cannot create directory '"
  2941. + dir + "' - Specify file by full path name and verify that you "
  2942. "have directory creation and file write privileges.";
  2943. this->SetError(errstring);
  2944. return false;
  2945. }
  2946. cmsys::ofstream fout(file.c_str(), std::ios::binary);
  2947. if(!fout)
  2948. {
  2949. this->SetError("DOWNLOAD cannot open file for write.");
  2950. return false;
  2951. }
  2952. #if defined(WIN32) && defined(CMAKE_ENCODING_UTF8)
  2953. url = fix_file_url_windows(url);
  2954. #endif
  2955. ::CURL *curl;
  2956. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2957. curl = ::curl_easy_init();
  2958. if(!curl)
  2959. {
  2960. this->SetError("DOWNLOAD error initializing curl.");
  2961. return false;
  2962. }
  2963. cURLEasyGuard g_curl(curl);
  2964. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2965. check_curl_result(res, "DOWNLOAD cannot set url: ");
  2966. // enable HTTP ERROR parsing
  2967. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2968. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  2969. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  2970. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  2971. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  2972. cmWriteToFileCallback);
  2973. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  2974. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2975. cmFileCommandCurlDebugCallback);
  2976. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  2977. // check to see if TLS verification is requested
  2978. if(tls_verify)
  2979. {
  2980. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2981. check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
  2982. }
  2983. else
  2984. {
  2985. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2986. check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
  2987. }
  2988. // check to see if a CAINFO file has been specified
  2989. // command arg comes first
  2990. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2991. if (!cainfo_err.empty())
  2992. {
  2993. this->SetError(cainfo_err);
  2994. return false;
  2995. }
  2996. cmFileCommandVectorOfChar chunkDebug;
  2997. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&fout);
  2998. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  2999. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
  3000. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  3001. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  3002. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  3003. if(!logVar.empty())
  3004. {
  3005. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  3006. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  3007. }
  3008. if(timeout > 0)
  3009. {
  3010. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
  3011. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  3012. }
  3013. if(inactivity_timeout > 0)
  3014. {
  3015. // Give up if there is no progress for a long time.
  3016. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  3017. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  3018. }
  3019. // Need the progress helper's scope to last through the duration of
  3020. // the curl_easy_perform call... so this object is declared at function
  3021. // scope intentionally, rather than inside the "if(showProgress)"
  3022. // block...
  3023. //
  3024. cURLProgressHelper helper(this, "download");
  3025. if(showProgress)
  3026. {
  3027. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  3028. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  3029. res = ::curl_easy_setopt(curl,
  3030. CURLOPT_PROGRESSFUNCTION, cmFileDownloadProgressCallback);
  3031. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  3032. res = ::curl_easy_setopt(curl,
  3033. CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
  3034. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  3035. }
  3036. res = ::curl_easy_perform(curl);
  3037. /* always cleanup */
  3038. g_curl.release();
  3039. ::curl_easy_cleanup(curl);
  3040. if(!statusVar.empty())
  3041. {
  3042. std::ostringstream result;
  3043. result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
  3044. this->Makefile->AddDefinition(statusVar,
  3045. result.str().c_str());
  3046. }
  3047. ::curl_global_cleanup();
  3048. // Explicitly flush/close so we can measure the md5 accurately.
  3049. //
  3050. fout.flush();
  3051. fout.close();
  3052. // Verify MD5 sum if requested:
  3053. //
  3054. if (hash.get())
  3055. {
  3056. std::string actualHash = hash->HashFile(file);
  3057. if (actualHash.empty())
  3058. {
  3059. this->SetError("DOWNLOAD cannot compute hash on downloaded file");
  3060. return false;
  3061. }
  3062. if (expectedHash != actualHash)
  3063. {
  3064. std::ostringstream oss;
  3065. oss << "DOWNLOAD HASH mismatch" << std::endl
  3066. << " for file: [" << file << "]" << std::endl
  3067. << " expected hash: [" << expectedHash << "]" << std::endl
  3068. << " actual hash: [" << actualHash << "]" << std::endl
  3069. << " status: [" << (int)res << ";\""
  3070. << ::curl_easy_strerror(res) << "\"]" << std::endl
  3071. ;
  3072. this->SetError(oss.str());
  3073. return false;
  3074. }
  3075. }
  3076. if (!logVar.empty())
  3077. {
  3078. chunkDebug.push_back(0);
  3079. this->Makefile->AddDefinition(logVar, &*chunkDebug.begin());
  3080. }
  3081. return true;
  3082. #else
  3083. this->SetError("DOWNLOAD not supported by bootstrap cmake.");
  3084. return false;
  3085. #endif
  3086. }
  3087. bool
  3088. cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
  3089. {
  3090. #if defined(CMAKE_BUILD_WITH_CMAKE)
  3091. if(args.size() < 3)
  3092. {
  3093. this->SetError("UPLOAD must be called with at least three arguments.");
  3094. return false;
  3095. }
  3096. std::vector<std::string>::const_iterator i = args.begin();
  3097. ++i;
  3098. std::string filename = *i;
  3099. ++i;
  3100. std::string url = *i;
  3101. ++i;
  3102. long timeout = 0;
  3103. long inactivity_timeout = 0;
  3104. std::string logVar;
  3105. std::string statusVar;
  3106. bool showProgress = false;
  3107. while(i != args.end())
  3108. {
  3109. if(*i == "TIMEOUT")
  3110. {
  3111. ++i;
  3112. if(i != args.end())
  3113. {
  3114. timeout = atol(i->c_str());
  3115. }
  3116. else
  3117. {
  3118. this->SetError("UPLOAD missing time for TIMEOUT.");
  3119. return false;
  3120. }
  3121. }
  3122. else if(*i == "INACTIVITY_TIMEOUT")
  3123. {
  3124. ++i;
  3125. if(i != args.end())
  3126. {
  3127. inactivity_timeout = atol(i->c_str());
  3128. }
  3129. else
  3130. {
  3131. this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  3132. return false;
  3133. }
  3134. }
  3135. else if(*i == "LOG")
  3136. {
  3137. ++i;
  3138. if( i == args.end())
  3139. {
  3140. this->SetError("UPLOAD missing VAR for LOG.");
  3141. return false;
  3142. }
  3143. logVar = *i;
  3144. }
  3145. else if(*i == "STATUS")
  3146. {
  3147. ++i;
  3148. if( i == args.end())
  3149. {
  3150. this->SetError("UPLOAD missing VAR for STATUS.");
  3151. return false;
  3152. }
  3153. statusVar = *i;
  3154. }
  3155. else if(*i == "SHOW_PROGRESS")
  3156. {
  3157. showProgress = true;
  3158. }
  3159. ++i;
  3160. }
  3161. // Open file for reading:
  3162. //
  3163. FILE *fin = cmsys::SystemTools::Fopen(filename, "rb");
  3164. if(!fin)
  3165. {
  3166. std::string errStr = "UPLOAD cannot open file '";
  3167. errStr += filename + "' for reading.";
  3168. this->SetError(errStr);
  3169. return false;
  3170. }
  3171. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  3172. #if defined(WIN32) && defined(CMAKE_ENCODING_UTF8)
  3173. url = fix_file_url_windows(url);
  3174. #endif
  3175. ::CURL *curl;
  3176. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  3177. curl = ::curl_easy_init();
  3178. if(!curl)
  3179. {
  3180. this->SetError("UPLOAD error initializing curl.");
  3181. fclose(fin);
  3182. return false;
  3183. }
  3184. cURLEasyGuard g_curl(curl);
  3185. // enable HTTP ERROR parsing
  3186. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  3187. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  3188. // enable uploading
  3189. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  3190. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  3191. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  3192. check_curl_result(res, "UPLOAD cannot set url: ");
  3193. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  3194. cmWriteToMemoryCallback);
  3195. check_curl_result(res, "UPLOAD cannot set write function: ");
  3196. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  3197. cmFileCommandCurlDebugCallback);
  3198. check_curl_result(res, "UPLOAD cannot set debug function: ");
  3199. cmFileCommandVectorOfChar chunkResponse;
  3200. cmFileCommandVectorOfChar chunkDebug;
  3201. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunkResponse);
  3202. check_curl_result(res, "UPLOAD cannot set write data: ");
  3203. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
  3204. check_curl_result(res, "UPLOAD cannot set debug data: ");
  3205. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  3206. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  3207. if(!logVar.empty())
  3208. {
  3209. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  3210. check_curl_result(res, "UPLOAD cannot set verbose: ");
  3211. }
  3212. if(timeout > 0)
  3213. {
  3214. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
  3215. check_curl_result(res, "UPLOAD cannot set timeout: ");
  3216. }
  3217. if(inactivity_timeout > 0)
  3218. {
  3219. // Give up if there is no progress for a long time.
  3220. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  3221. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  3222. }
  3223. // Need the progress helper's scope to last through the duration of
  3224. // the curl_easy_perform call... so this object is declared at function
  3225. // scope intentionally, rather than inside the "if(showProgress)"
  3226. // block...
  3227. //
  3228. cURLProgressHelper helper(this, "upload");
  3229. if(showProgress)
  3230. {
  3231. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  3232. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  3233. res = ::curl_easy_setopt(curl,
  3234. CURLOPT_PROGRESSFUNCTION, cmFileUploadProgressCallback);
  3235. check_curl_result(res, "UPLOAD cannot set progress function: ");
  3236. res = ::curl_easy_setopt(curl,
  3237. CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
  3238. check_curl_result(res, "UPLOAD cannot set progress data: ");
  3239. }
  3240. // now specify which file to upload
  3241. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  3242. check_curl_result(res, "UPLOAD cannot set input file: ");
  3243. // and give the size of the upload (optional)
  3244. res = ::curl_easy_setopt(curl,
  3245. CURLOPT_INFILESIZE, static_cast<long>(file_size));
  3246. check_curl_result(res, "UPLOAD cannot set input file size: ");
  3247. res = ::curl_easy_perform(curl);
  3248. /* always cleanup */
  3249. g_curl.release();
  3250. ::curl_easy_cleanup(curl);
  3251. if(!statusVar.empty())
  3252. {
  3253. std::ostringstream result;
  3254. result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
  3255. this->Makefile->AddDefinition(statusVar,
  3256. result.str().c_str());
  3257. }
  3258. ::curl_global_cleanup();
  3259. fclose(fin);
  3260. fin = NULL;
  3261. if(!logVar.empty())
  3262. {
  3263. std::string log;
  3264. if(!chunkResponse.empty())
  3265. {
  3266. chunkResponse.push_back(0);
  3267. log += "Response:\n";
  3268. log += &*chunkResponse.begin();
  3269. log += "\n";
  3270. }
  3271. if(!chunkDebug.empty())
  3272. {
  3273. chunkDebug.push_back(0);
  3274. log += "Debug:\n";
  3275. log += &*chunkDebug.begin();
  3276. log += "\n";
  3277. }
  3278. this->Makefile->AddDefinition(logVar, log.c_str());
  3279. }
  3280. return true;
  3281. #else
  3282. this->SetError("UPLOAD not supported by bootstrap cmake.");
  3283. return false;
  3284. #endif
  3285. }
  3286. //----------------------------------------------------------------------------
  3287. void cmFileCommand::AddEvaluationFile(const std::string &inputName,
  3288. const std::string &outputExpr,
  3289. const std::string &condition,
  3290. bool inputIsContent
  3291. )
  3292. {
  3293. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  3294. cmGeneratorExpression outputGe(&lfbt);
  3295. cmsys::auto_ptr<cmCompiledGeneratorExpression> outputCge
  3296. = outputGe.Parse(outputExpr);
  3297. cmGeneratorExpression conditionGe(&lfbt);
  3298. cmsys::auto_ptr<cmCompiledGeneratorExpression> conditionCge
  3299. = conditionGe.Parse(condition);
  3300. this->Makefile->GetGlobalGenerator()->AddEvaluationFile(inputName,
  3301. outputCge,
  3302. this->Makefile,
  3303. conditionCge,
  3304. inputIsContent);
  3305. }
  3306. //----------------------------------------------------------------------------
  3307. bool cmFileCommand::HandleGenerateCommand(
  3308. std::vector<std::string> const& args)
  3309. {
  3310. if (args.size() < 5)
  3311. {
  3312. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3313. return false;
  3314. }
  3315. if (args[1] != "OUTPUT")
  3316. {
  3317. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3318. return false;
  3319. }
  3320. std::string condition;
  3321. if (args.size() > 5)
  3322. {
  3323. if (args[5] != "CONDITION")
  3324. {
  3325. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3326. return false;
  3327. }
  3328. if (args.size() != 7)
  3329. {
  3330. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3331. return false;
  3332. }
  3333. condition = args[6];
  3334. if (condition.empty())
  3335. {
  3336. this->SetError("CONDITION of sub-command GENERATE must not be empty if "
  3337. "specified.");
  3338. return false;
  3339. }
  3340. }
  3341. std::string output = args[2];
  3342. const bool inputIsContent = args[3] != "INPUT";
  3343. if (inputIsContent && args[3] != "CONTENT")
  3344. {
  3345. this->SetError("Incorrect arguments to GENERATE subcommand.");
  3346. return false;
  3347. }
  3348. std::string input = args[4];
  3349. this->AddEvaluationFile(input, output, condition, inputIsContent);
  3350. return true;
  3351. }
  3352. //----------------------------------------------------------------------------
  3353. bool cmFileCommand::HandleLockCommand(
  3354. std::vector<std::string> const& args)
  3355. {
  3356. #if defined(CMAKE_BUILD_WITH_CMAKE)
  3357. // Default values
  3358. bool directory = false;
  3359. bool release = false;
  3360. enum Guard {
  3361. GUARD_FUNCTION,
  3362. GUARD_FILE,
  3363. GUARD_PROCESS
  3364. };
  3365. Guard guard = GUARD_PROCESS;
  3366. std::string resultVariable;
  3367. unsigned long timeout = static_cast<unsigned long>(-1);
  3368. // Parse arguments
  3369. if(args.size() < 2)
  3370. {
  3371. this->Makefile->IssueMessage(
  3372. cmake::FATAL_ERROR,
  3373. "sub-command LOCK requires at least two arguments.");
  3374. return false;
  3375. }
  3376. std::string path = args[1];
  3377. for (unsigned i = 2; i < args.size(); ++i)
  3378. {
  3379. if (args[i] == "DIRECTORY")
  3380. {
  3381. directory = true;
  3382. }
  3383. else if (args[i] == "RELEASE")
  3384. {
  3385. release = true;
  3386. }
  3387. else if (args[i] == "GUARD")
  3388. {
  3389. ++i;
  3390. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  3391. if (i >= args.size())
  3392. {
  3393. this->Makefile->IssueMessage(cmake::FATAL_ERROR, merr);
  3394. return false;
  3395. }
  3396. else
  3397. {
  3398. if (args[i] == "FUNCTION")
  3399. {
  3400. guard = GUARD_FUNCTION;
  3401. }
  3402. else if (args[i] == "FILE")
  3403. {
  3404. guard = GUARD_FILE;
  3405. }
  3406. else if (args[i] == "PROCESS")
  3407. {
  3408. guard = GUARD_PROCESS;
  3409. }
  3410. else
  3411. {
  3412. std::ostringstream e;
  3413. e << merr << ", but got:\n \"" << args[i] << "\".";
  3414. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3415. return false;
  3416. }
  3417. }
  3418. }
  3419. else if (args[i] == "RESULT_VARIABLE")
  3420. {
  3421. ++i;
  3422. if (i >= args.size())
  3423. {
  3424. this->Makefile->IssueMessage(
  3425. cmake::FATAL_ERROR,
  3426. "expected variable name after RESULT_VARIABLE");
  3427. return false;
  3428. }
  3429. resultVariable = args[i];
  3430. }
  3431. else if (args[i] == "TIMEOUT")
  3432. {
  3433. ++i;
  3434. if (i >= args.size())
  3435. {
  3436. this->Makefile->IssueMessage(
  3437. cmake::FATAL_ERROR,
  3438. "expected timeout value after TIMEOUT");
  3439. return false;
  3440. }
  3441. long scanned;
  3442. if(!cmSystemTools::StringToLong(args[i].c_str(), &scanned)
  3443. || scanned < 0)
  3444. {
  3445. std::ostringstream e;
  3446. e << "TIMEOUT value \"" << args[i] << "\" is not an unsigned integer.";
  3447. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3448. return false;
  3449. }
  3450. timeout = static_cast<unsigned long>(scanned);
  3451. }
  3452. else
  3453. {
  3454. std::ostringstream e;
  3455. e << "expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or TIMEOUT\n";
  3456. e << "but got: \"" << args[i] << "\".";
  3457. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3458. return false;
  3459. }
  3460. }
  3461. if (directory)
  3462. {
  3463. path += "/cmake.lock";
  3464. }
  3465. if (!cmsys::SystemTools::FileIsFullPath(path))
  3466. {
  3467. path = this->Makefile->GetCurrentSourceDirectory() + ("/" + path);
  3468. }
  3469. // Unify path (remove '//', '/../', ...)
  3470. path = cmSystemTools::CollapseFullPath(path);
  3471. // Create file and directories if needed
  3472. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  3473. if (!cmSystemTools::MakeDirectory(parentDir))
  3474. {
  3475. std::ostringstream e;
  3476. e << "directory\n \"" << parentDir << "\"\ncreation failed ";
  3477. e << "(check permissions).";
  3478. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3479. cmSystemTools::SetFatalErrorOccured();
  3480. return false;
  3481. }
  3482. FILE *file = cmsys::SystemTools::Fopen(path, "w");
  3483. if (!file)
  3484. {
  3485. std::ostringstream e;
  3486. e << "file\n \"" << path << "\"\ncreation failed (check permissions).";
  3487. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3488. cmSystemTools::SetFatalErrorOccured();
  3489. return false;
  3490. }
  3491. fclose(file);
  3492. // Actual lock/unlock
  3493. cmFileLockPool& lockPool = this->Makefile->GetGlobalGenerator()
  3494. ->GetFileLockPool();
  3495. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  3496. if (release)
  3497. {
  3498. fileLockResult = lockPool.Release(path);
  3499. }
  3500. else
  3501. {
  3502. switch (guard)
  3503. {
  3504. case GUARD_FUNCTION:
  3505. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  3506. break;
  3507. case GUARD_FILE:
  3508. fileLockResult = lockPool.LockFileScope(path, timeout);
  3509. break;
  3510. case GUARD_PROCESS:
  3511. fileLockResult = lockPool.LockProcessScope(path, timeout);
  3512. break;
  3513. default:
  3514. cmSystemTools::SetFatalErrorOccured();
  3515. return false;
  3516. }
  3517. }
  3518. const std::string result = fileLockResult.GetOutputMessage();
  3519. if (resultVariable.empty() && !fileLockResult.IsOk())
  3520. {
  3521. std::ostringstream e;
  3522. e << "error locking file\n \"" << path << "\"\n" << result << ".";
  3523. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3524. cmSystemTools::SetFatalErrorOccured();
  3525. return false;
  3526. }
  3527. if (!resultVariable.empty())
  3528. {
  3529. this->Makefile->AddDefinition(resultVariable, result.c_str());
  3530. }
  3531. return true;
  3532. #else
  3533. static_cast<void>(args);
  3534. this->SetError("sub-command LOCK not implemented in bootstrap cmake");
  3535. return false;
  3536. #endif
  3537. }
  3538. //----------------------------------------------------------------------------
  3539. bool cmFileCommand::HandleTimestampCommand(
  3540. std::vector<std::string> const& args)
  3541. {
  3542. if(args.size() < 3)
  3543. {
  3544. this->SetError("sub-command TIMESTAMP requires at least two arguments.");
  3545. return false;
  3546. }
  3547. else if(args.size() > 5)
  3548. {
  3549. this->SetError("sub-command TIMESTAMP takes at most four arguments.");
  3550. return false;
  3551. }
  3552. unsigned int argsIndex = 1;
  3553. const std::string& filename = args[argsIndex++];
  3554. const std::string& outputVariable = args[argsIndex++];
  3555. std::string formatString;
  3556. if(args.size() > argsIndex && args[argsIndex] != "UTC")
  3557. {
  3558. formatString = args[argsIndex++];
  3559. }
  3560. bool utcFlag = false;
  3561. if(args.size() > argsIndex)
  3562. {
  3563. if(args[argsIndex] == "UTC")
  3564. {
  3565. utcFlag = true;
  3566. }
  3567. else
  3568. {
  3569. std::string e = " TIMESTAMP sub-command does not recognize option " +
  3570. args[argsIndex] + ".";
  3571. this->SetError(e);
  3572. return false;
  3573. }
  3574. }
  3575. cmTimestamp timestamp;
  3576. std::string result = timestamp.FileModificationTime(
  3577. filename.c_str(), formatString, utcFlag);
  3578. this->Makefile->AddDefinition(outputVariable, result.c_str());
  3579. return true;
  3580. }