cmFileCommand.cxx 97 KB

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