cmFileCommand.cxx 98 KB

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