cmFileCommand.cxx 97 KB

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