cmFileCommand.cxx 95 KB

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