cmFileCommand.cxx 97 KB

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