cmFileCommand.cxx 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmFileCommand.h"
  4. #include "cm_kwiml.h"
  5. #include "cm_static_string_view.hxx"
  6. #include "cmsys/FStream.hxx"
  7. #include "cmsys/Glob.hxx"
  8. #include "cmsys/RegularExpression.hxx"
  9. #include <algorithm>
  10. #include <assert.h>
  11. #include <cmath>
  12. #include <ctype.h>
  13. #include <memory> // IWYU pragma: keep
  14. #include <sstream>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <utility>
  18. #include <vector>
  19. #include "cmAlgorithms.h"
  20. #include "cmArgumentParser.h"
  21. #include "cmCryptoHash.h"
  22. #include "cmFileCopier.h"
  23. #include "cmFileInstaller.h"
  24. #include "cmFileLockPool.h"
  25. #include "cmGeneratorExpression.h"
  26. #include "cmGlobalGenerator.h"
  27. #include "cmHexFileConverter.h"
  28. #include "cmListFileCache.h"
  29. #include "cmMakefile.h"
  30. #include "cmMessageType.h"
  31. #include "cmPolicies.h"
  32. #include "cmRange.h"
  33. #include "cmSystemTools.h"
  34. #include "cmTimestamp.h"
  35. #include "cm_sys_stat.h"
  36. #include "cmake.h"
  37. #if defined(CMAKE_BUILD_WITH_CMAKE)
  38. # include "cmCurl.h"
  39. # include "cmFileLockResult.h"
  40. # include "cm_curl.h"
  41. #endif
  42. #if defined(CMAKE_USE_ELF_PARSER)
  43. # include "cmELF.h"
  44. #endif
  45. #if defined(_WIN32)
  46. # include <windows.h>
  47. #endif
  48. class cmSystemToolsFileTime;
  49. #if defined(_WIN32)
  50. // libcurl doesn't support file:// urls for unicode filenames on Windows.
  51. // Convert string from UTF-8 to ACP if this is a file:// URL.
  52. static std::string fix_file_url_windows(const std::string& url)
  53. {
  54. std::string ret = url;
  55. if (strncmp(url.c_str(), "file://", 7) == 0) {
  56. std::wstring wurl = cmsys::Encoding::ToWide(url);
  57. if (!wurl.empty()) {
  58. int mblen =
  59. WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1, NULL, 0, NULL, NULL);
  60. if (mblen > 0) {
  61. std::vector<char> chars(mblen);
  62. mblen = WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1, &chars[0],
  63. mblen, NULL, NULL);
  64. if (mblen > 0) {
  65. ret = &chars[0];
  66. }
  67. }
  68. }
  69. }
  70. return ret;
  71. }
  72. #endif
  73. // cmLibraryCommand
  74. bool cmFileCommand::InitialPass(std::vector<std::string> const& args,
  75. cmExecutionStatus&)
  76. {
  77. if (args.size() < 2) {
  78. this->SetError("must be called with at least two arguments.");
  79. return false;
  80. }
  81. std::string const& subCommand = args[0];
  82. if (subCommand == "WRITE") {
  83. return this->HandleWriteCommand(args, false);
  84. }
  85. if (subCommand == "APPEND") {
  86. return this->HandleWriteCommand(args, true);
  87. }
  88. if (subCommand == "DOWNLOAD") {
  89. return this->HandleDownloadCommand(args);
  90. }
  91. if (subCommand == "UPLOAD") {
  92. return this->HandleUploadCommand(args);
  93. }
  94. if (subCommand == "READ") {
  95. return this->HandleReadCommand(args);
  96. }
  97. if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
  98. subCommand == "SHA256" || subCommand == "SHA384" ||
  99. subCommand == "SHA512" || subCommand == "SHA3_224" ||
  100. subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
  101. subCommand == "SHA3_512") {
  102. return this->HandleHashCommand(args);
  103. }
  104. if (subCommand == "STRINGS") {
  105. return this->HandleStringsCommand(args);
  106. }
  107. if (subCommand == "GLOB") {
  108. return this->HandleGlobCommand(args, false);
  109. }
  110. if (subCommand == "GLOB_RECURSE") {
  111. return this->HandleGlobCommand(args, true);
  112. }
  113. if (subCommand == "MAKE_DIRECTORY") {
  114. return this->HandleMakeDirectoryCommand(args);
  115. }
  116. if (subCommand == "RENAME") {
  117. return this->HandleRename(args);
  118. }
  119. if (subCommand == "REMOVE") {
  120. return this->HandleRemove(args, false);
  121. }
  122. if (subCommand == "REMOVE_RECURSE") {
  123. return this->HandleRemove(args, true);
  124. }
  125. if (subCommand == "COPY") {
  126. return this->HandleCopyCommand(args);
  127. }
  128. if (subCommand == "INSTALL") {
  129. return this->HandleInstallCommand(args);
  130. }
  131. if (subCommand == "DIFFERENT") {
  132. return this->HandleDifferentCommand(args);
  133. }
  134. if (subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH") {
  135. return this->HandleRPathChangeCommand(args);
  136. }
  137. if (subCommand == "RPATH_CHECK") {
  138. return this->HandleRPathCheckCommand(args);
  139. }
  140. if (subCommand == "RPATH_REMOVE") {
  141. return this->HandleRPathRemoveCommand(args);
  142. }
  143. if (subCommand == "READ_ELF") {
  144. return this->HandleReadElfCommand(args);
  145. }
  146. if (subCommand == "RELATIVE_PATH") {
  147. return this->HandleRelativePathCommand(args);
  148. }
  149. if (subCommand == "TO_CMAKE_PATH") {
  150. return this->HandleCMakePathCommand(args, false);
  151. }
  152. if (subCommand == "TO_NATIVE_PATH") {
  153. return this->HandleCMakePathCommand(args, true);
  154. }
  155. if (subCommand == "TOUCH") {
  156. return this->HandleTouchCommand(args, true);
  157. }
  158. if (subCommand == "TOUCH_NOCREATE") {
  159. return this->HandleTouchCommand(args, false);
  160. }
  161. if (subCommand == "TIMESTAMP") {
  162. return this->HandleTimestampCommand(args);
  163. }
  164. if (subCommand == "GENERATE") {
  165. return this->HandleGenerateCommand(args);
  166. }
  167. if (subCommand == "LOCK") {
  168. return this->HandleLockCommand(args);
  169. }
  170. if (subCommand == "SIZE") {
  171. return this->HandleSizeCommand(args);
  172. }
  173. if (subCommand == "READ_SYMLINK") {
  174. return this->HandleReadSymlinkCommand(args);
  175. }
  176. if (subCommand == "CREATE_LINK") {
  177. return this->HandleCreateLinkCommand(args);
  178. }
  179. std::string e = "does not recognize sub-command " + subCommand;
  180. this->SetError(e);
  181. return false;
  182. }
  183. bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args,
  184. bool append)
  185. {
  186. std::vector<std::string>::const_iterator i = args.begin();
  187. i++; // Get rid of subcommand
  188. std::string fileName = *i;
  189. if (!cmsys::SystemTools::FileIsFullPath(*i)) {
  190. fileName = this->Makefile->GetCurrentSourceDirectory();
  191. fileName += "/" + *i;
  192. }
  193. i++;
  194. if (!this->Makefile->CanIWriteThisFile(fileName)) {
  195. std::string e =
  196. "attempted to write a file: " + fileName + " into a source directory.";
  197. this->SetError(e);
  198. cmSystemTools::SetFatalErrorOccured();
  199. return false;
  200. }
  201. std::string dir = cmSystemTools::GetFilenamePath(fileName);
  202. cmSystemTools::MakeDirectory(dir);
  203. mode_t mode = 0;
  204. bool writable = false;
  205. // Set permissions to writable
  206. if (cmSystemTools::GetPermissions(fileName, mode)) {
  207. #if defined(_MSC_VER) || defined(__MINGW32__)
  208. writable = (mode & S_IWRITE) != 0;
  209. mode_t newMode = mode | S_IWRITE;
  210. #else
  211. writable = mode & S_IWUSR;
  212. mode_t newMode = mode | S_IWUSR | S_IWGRP;
  213. #endif
  214. if (!writable) {
  215. cmSystemTools::SetPermissions(fileName, newMode);
  216. }
  217. }
  218. // If GetPermissions fails, pretend like it is ok. File open will fail if
  219. // the file is not writable
  220. cmsys::ofstream file(fileName.c_str(),
  221. append ? std::ios::app : std::ios::out);
  222. if (!file) {
  223. std::string error = "failed to open for writing (";
  224. error += cmSystemTools::GetLastSystemError();
  225. error += "):\n ";
  226. error += fileName;
  227. this->SetError(error);
  228. return false;
  229. }
  230. std::string message = cmJoin(cmMakeRange(i, args.end()), std::string());
  231. file << message;
  232. if (!file) {
  233. std::string error = "write failed (";
  234. error += cmSystemTools::GetLastSystemError();
  235. error += "):\n ";
  236. error += fileName;
  237. this->SetError(error);
  238. return false;
  239. }
  240. file.close();
  241. if (mode && !writable) {
  242. cmSystemTools::SetPermissions(fileName, mode);
  243. }
  244. return true;
  245. }
  246. bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
  247. {
  248. if (args.size() < 3) {
  249. this->SetError("READ must be called with at least two additional "
  250. "arguments");
  251. return false;
  252. }
  253. std::string const& fileNameArg = args[1];
  254. std::string const& variable = args[2];
  255. struct Arguments
  256. {
  257. std::string Offset;
  258. std::string Limit;
  259. bool Hex = false;
  260. };
  261. static auto const parser = cmArgumentParser<Arguments>{}
  262. .Bind("OFFSET"_s, &Arguments::Offset)
  263. .Bind("LIMIT"_s, &Arguments::Limit)
  264. .Bind("HEX"_s, &Arguments::Hex);
  265. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(3));
  266. std::string fileName = fileNameArg;
  267. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  268. fileName = this->Makefile->GetCurrentSourceDirectory();
  269. fileName += "/" + fileNameArg;
  270. }
  271. // Open the specified file.
  272. #if defined(_WIN32) || defined(__CYGWIN__)
  273. cmsys::ifstream file(fileName.c_str(),
  274. arguments.Hex ? (std::ios::binary | std::ios::in)
  275. : std::ios::in);
  276. #else
  277. cmsys::ifstream file(fileName.c_str());
  278. #endif
  279. if (!file) {
  280. std::string error = "failed to open for reading (";
  281. error += cmSystemTools::GetLastSystemError();
  282. error += "):\n ";
  283. error += fileName;
  284. this->SetError(error);
  285. return false;
  286. }
  287. // is there a limit?
  288. long sizeLimit = -1;
  289. if (!arguments.Limit.empty()) {
  290. sizeLimit = atoi(arguments.Limit.c_str());
  291. }
  292. // is there an offset?
  293. long offset = 0;
  294. if (!arguments.Offset.empty()) {
  295. offset = atoi(arguments.Offset.c_str());
  296. }
  297. file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
  298. std::string output;
  299. if (arguments.Hex) {
  300. // Convert part of the file into hex code
  301. char c;
  302. while ((sizeLimit != 0) && (file.get(c))) {
  303. char hex[4];
  304. sprintf(hex, "%.2x", c & 0xff);
  305. output += hex;
  306. if (sizeLimit > 0) {
  307. sizeLimit--;
  308. }
  309. }
  310. } else {
  311. std::string line;
  312. bool has_newline = false;
  313. while (
  314. sizeLimit != 0 &&
  315. cmSystemTools::GetLineFromStream(file, line, &has_newline, sizeLimit)) {
  316. if (sizeLimit > 0) {
  317. sizeLimit = sizeLimit - static_cast<long>(line.size());
  318. if (has_newline) {
  319. sizeLimit--;
  320. }
  321. if (sizeLimit < 0) {
  322. sizeLimit = 0;
  323. }
  324. }
  325. output += line;
  326. if (has_newline) {
  327. output += "\n";
  328. }
  329. }
  330. }
  331. this->Makefile->AddDefinition(variable, output.c_str());
  332. return true;
  333. }
  334. bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
  335. {
  336. #if defined(CMAKE_BUILD_WITH_CMAKE)
  337. if (args.size() != 3) {
  338. std::ostringstream e;
  339. e << args[0] << " requires a file name and output variable";
  340. this->SetError(e.str());
  341. return false;
  342. }
  343. std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
  344. if (hash) {
  345. std::string out = hash->HashFile(args[1]);
  346. if (!out.empty()) {
  347. this->Makefile->AddDefinition(args[2], out.c_str());
  348. return true;
  349. }
  350. std::ostringstream e;
  351. e << args[0] << " failed to read file \"" << args[1]
  352. << "\": " << cmSystemTools::GetLastSystemError();
  353. this->SetError(e.str());
  354. }
  355. return false;
  356. #else
  357. std::ostringstream e;
  358. e << args[0] << " not available during bootstrap";
  359. this->SetError(e.str());
  360. return false;
  361. #endif
  362. }
  363. bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
  364. {
  365. if (args.size() < 3) {
  366. this->SetError("STRINGS requires a file name and output variable");
  367. return false;
  368. }
  369. // Get the file to read.
  370. std::string fileName = args[1];
  371. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  372. fileName = this->Makefile->GetCurrentSourceDirectory();
  373. fileName += "/" + args[1];
  374. }
  375. // Get the variable in which to store the results.
  376. std::string outVar = args[2];
  377. // Parse the options.
  378. enum
  379. {
  380. arg_none,
  381. arg_limit_input,
  382. arg_limit_output,
  383. arg_limit_count,
  384. arg_length_minimum,
  385. arg_length_maximum,
  386. arg__maximum,
  387. arg_regex,
  388. arg_encoding
  389. };
  390. unsigned int minlen = 0;
  391. unsigned int maxlen = 0;
  392. int limit_input = -1;
  393. int limit_output = -1;
  394. unsigned int limit_count = 0;
  395. cmsys::RegularExpression regex;
  396. bool have_regex = false;
  397. bool newline_consume = false;
  398. bool hex_conversion_enabled = true;
  399. enum
  400. {
  401. encoding_none = cmsys::FStream::BOM_None,
  402. encoding_utf8 = cmsys::FStream::BOM_UTF8,
  403. encoding_utf16le = cmsys::FStream::BOM_UTF16LE,
  404. encoding_utf16be = cmsys::FStream::BOM_UTF16BE,
  405. encoding_utf32le = cmsys::FStream::BOM_UTF32LE,
  406. encoding_utf32be = cmsys::FStream::BOM_UTF32BE
  407. };
  408. int encoding = encoding_none;
  409. int arg_mode = arg_none;
  410. for (unsigned int i = 3; i < args.size(); ++i) {
  411. if (args[i] == "LIMIT_INPUT") {
  412. arg_mode = arg_limit_input;
  413. } else if (args[i] == "LIMIT_OUTPUT") {
  414. arg_mode = arg_limit_output;
  415. } else if (args[i] == "LIMIT_COUNT") {
  416. arg_mode = arg_limit_count;
  417. } else if (args[i] == "LENGTH_MINIMUM") {
  418. arg_mode = arg_length_minimum;
  419. } else if (args[i] == "LENGTH_MAXIMUM") {
  420. arg_mode = arg_length_maximum;
  421. } else if (args[i] == "REGEX") {
  422. arg_mode = arg_regex;
  423. } else if (args[i] == "NEWLINE_CONSUME") {
  424. newline_consume = true;
  425. arg_mode = arg_none;
  426. } else if (args[i] == "NO_HEX_CONVERSION") {
  427. hex_conversion_enabled = false;
  428. arg_mode = arg_none;
  429. } else if (args[i] == "ENCODING") {
  430. arg_mode = arg_encoding;
  431. } else if (arg_mode == arg_limit_input) {
  432. if (sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
  433. limit_input < 0) {
  434. std::ostringstream e;
  435. e << "STRINGS option LIMIT_INPUT value \"" << args[i]
  436. << "\" is not an unsigned integer.";
  437. this->SetError(e.str());
  438. return false;
  439. }
  440. arg_mode = arg_none;
  441. } else if (arg_mode == arg_limit_output) {
  442. if (sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
  443. limit_output < 0) {
  444. std::ostringstream e;
  445. e << "STRINGS option LIMIT_OUTPUT value \"" << args[i]
  446. << "\" is not an unsigned integer.";
  447. this->SetError(e.str());
  448. return false;
  449. }
  450. arg_mode = arg_none;
  451. } else if (arg_mode == arg_limit_count) {
  452. int count;
  453. if (sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0) {
  454. std::ostringstream e;
  455. e << "STRINGS option LIMIT_COUNT value \"" << args[i]
  456. << "\" is not an unsigned integer.";
  457. this->SetError(e.str());
  458. return false;
  459. }
  460. limit_count = count;
  461. arg_mode = arg_none;
  462. } else if (arg_mode == arg_length_minimum) {
  463. int len;
  464. if (sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0) {
  465. std::ostringstream e;
  466. e << "STRINGS option LENGTH_MINIMUM value \"" << args[i]
  467. << "\" is not an unsigned integer.";
  468. this->SetError(e.str());
  469. return false;
  470. }
  471. minlen = len;
  472. arg_mode = arg_none;
  473. } else if (arg_mode == arg_length_maximum) {
  474. int len;
  475. if (sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0) {
  476. std::ostringstream e;
  477. e << "STRINGS option LENGTH_MAXIMUM value \"" << args[i]
  478. << "\" is not an unsigned integer.";
  479. this->SetError(e.str());
  480. return false;
  481. }
  482. maxlen = len;
  483. arg_mode = arg_none;
  484. } else if (arg_mode == arg_regex) {
  485. if (!regex.compile(args[i])) {
  486. std::ostringstream e;
  487. e << "STRINGS option REGEX value \"" << args[i]
  488. << "\" could not be compiled.";
  489. this->SetError(e.str());
  490. return false;
  491. }
  492. have_regex = true;
  493. arg_mode = arg_none;
  494. } else if (arg_mode == arg_encoding) {
  495. if (args[i] == "UTF-8") {
  496. encoding = encoding_utf8;
  497. } else if (args[i] == "UTF-16LE") {
  498. encoding = encoding_utf16le;
  499. } else if (args[i] == "UTF-16BE") {
  500. encoding = encoding_utf16be;
  501. } else if (args[i] == "UTF-32LE") {
  502. encoding = encoding_utf32le;
  503. } else if (args[i] == "UTF-32BE") {
  504. encoding = encoding_utf32be;
  505. } else {
  506. std::ostringstream e;
  507. e << "STRINGS option ENCODING \"" << args[i] << "\" not recognized.";
  508. this->SetError(e.str());
  509. return false;
  510. }
  511. arg_mode = arg_none;
  512. } else {
  513. std::ostringstream e;
  514. e << "STRINGS given unknown argument \"" << args[i] << "\"";
  515. this->SetError(e.str());
  516. return false;
  517. }
  518. }
  519. if (hex_conversion_enabled) {
  520. // TODO: should work without temp file, but just on a memory buffer
  521. std::string binaryFileName = this->Makefile->GetCurrentBinaryDirectory();
  522. binaryFileName += "/CMakeFiles";
  523. binaryFileName += "/FileCommandStringsBinaryFile";
  524. if (cmHexFileConverter::TryConvert(fileName, binaryFileName)) {
  525. fileName = binaryFileName;
  526. }
  527. }
  528. // Open the specified file.
  529. #if defined(_WIN32) || defined(__CYGWIN__)
  530. cmsys::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
  531. #else
  532. cmsys::ifstream fin(fileName.c_str());
  533. #endif
  534. if (!fin) {
  535. std::ostringstream e;
  536. e << "STRINGS file \"" << fileName << "\" cannot be read.";
  537. this->SetError(e.str());
  538. return false;
  539. }
  540. // If BOM is found and encoding was not specified, use the BOM
  541. int bom_found = cmsys::FStream::ReadBOM(fin);
  542. if (encoding == encoding_none && bom_found != cmsys::FStream::BOM_None) {
  543. encoding = bom_found;
  544. }
  545. unsigned int bytes_rem = 0;
  546. if (encoding == encoding_utf16le || encoding == encoding_utf16be) {
  547. bytes_rem = 1;
  548. }
  549. if (encoding == encoding_utf32le || encoding == encoding_utf32be) {
  550. bytes_rem = 3;
  551. }
  552. // Parse strings out of the file.
  553. int output_size = 0;
  554. std::vector<std::string> strings;
  555. std::string s;
  556. while ((!limit_count || strings.size() < limit_count) &&
  557. (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
  558. fin) {
  559. std::string current_str;
  560. int c = fin.get();
  561. for (unsigned int i = 0; i < bytes_rem; ++i) {
  562. int c1 = fin.get();
  563. if (!fin) {
  564. fin.putback(static_cast<char>(c1));
  565. break;
  566. }
  567. c = (c << 8) | c1;
  568. }
  569. if (encoding == encoding_utf16le) {
  570. c = ((c & 0xFF) << 8) | ((c & 0xFF00) >> 8);
  571. } else if (encoding == encoding_utf32le) {
  572. c = (((c & 0xFF) << 24) | ((c & 0xFF00) << 8) | ((c & 0xFF0000) >> 8) |
  573. ((c & 0xFF000000) >> 24));
  574. }
  575. if (c == '\r') {
  576. // Ignore CR character to make output always have UNIX newlines.
  577. continue;
  578. }
  579. if (c >= 0 && c <= 0xFF &&
  580. (isprint(c) || c == '\t' || (c == '\n' && newline_consume))) {
  581. // This is an ASCII character that may be part of a string.
  582. // Cast added to avoid compiler warning. Cast is ok because
  583. // c is guaranteed to fit in char by the above if...
  584. current_str += static_cast<char>(c);
  585. } else if (encoding == encoding_utf8) {
  586. // Check for UTF-8 encoded string (up to 4 octets)
  587. static const unsigned char utf8_check_table[3][2] = {
  588. { 0xE0, 0xC0 },
  589. { 0xF0, 0xE0 },
  590. { 0xF8, 0xF0 },
  591. };
  592. // how many octets are there?
  593. unsigned int num_utf8_bytes = 0;
  594. for (unsigned int j = 0; num_utf8_bytes == 0 && j < 3; j++) {
  595. if ((c & utf8_check_table[j][0]) == utf8_check_table[j][1]) {
  596. num_utf8_bytes = j + 2;
  597. }
  598. }
  599. // get subsequent octets and check that they are valid
  600. for (unsigned int j = 0; j < num_utf8_bytes; j++) {
  601. if (j != 0) {
  602. c = fin.get();
  603. if (!fin || (c & 0xC0) != 0x80) {
  604. fin.putback(static_cast<char>(c));
  605. break;
  606. }
  607. }
  608. current_str += static_cast<char>(c);
  609. }
  610. // if this was an invalid utf8 sequence, discard the data, and put
  611. // back subsequent characters
  612. if ((current_str.length() != num_utf8_bytes)) {
  613. for (unsigned int j = 0; j < current_str.size() - 1; j++) {
  614. c = current_str[current_str.size() - 1 - j];
  615. fin.putback(static_cast<char>(c));
  616. }
  617. current_str.clear();
  618. }
  619. }
  620. if (c == '\n' && !newline_consume) {
  621. // The current line has been terminated. Check if the current
  622. // string matches the requirements. The length may now be as
  623. // low as zero since blank lines are allowed.
  624. if (s.length() >= minlen && (!have_regex || regex.find(s))) {
  625. output_size += static_cast<int>(s.size()) + 1;
  626. if (limit_output >= 0 && output_size >= limit_output) {
  627. s.clear();
  628. break;
  629. }
  630. strings.push_back(s);
  631. }
  632. // Reset the string to empty.
  633. s.clear();
  634. } else if (current_str.empty()) {
  635. // A non-string character has been found. Check if the current
  636. // string matches the requirements. We require that the length
  637. // be at least one no matter what the user specified.
  638. if (s.length() >= minlen && !s.empty() &&
  639. (!have_regex || regex.find(s))) {
  640. output_size += static_cast<int>(s.size()) + 1;
  641. if (limit_output >= 0 && output_size >= limit_output) {
  642. s.clear();
  643. break;
  644. }
  645. strings.push_back(s);
  646. }
  647. // Reset the string to empty.
  648. s.clear();
  649. } else {
  650. s += current_str;
  651. }
  652. if (maxlen > 0 && s.size() == maxlen) {
  653. // Terminate a string if the maximum length is reached.
  654. if (s.length() >= minlen && (!have_regex || regex.find(s))) {
  655. output_size += static_cast<int>(s.size()) + 1;
  656. if (limit_output >= 0 && output_size >= limit_output) {
  657. s.clear();
  658. break;
  659. }
  660. strings.push_back(s);
  661. }
  662. s.clear();
  663. }
  664. }
  665. // If there is a non-empty current string we have hit the end of the
  666. // input file or the input size limit. Check if the current string
  667. // matches the requirements.
  668. if ((!limit_count || strings.size() < limit_count) && !s.empty() &&
  669. s.length() >= minlen && (!have_regex || regex.find(s))) {
  670. output_size += static_cast<int>(s.size()) + 1;
  671. if (limit_output < 0 || output_size < limit_output) {
  672. strings.push_back(s);
  673. }
  674. }
  675. // Encode the result in a CMake list.
  676. const char* sep = "";
  677. std::string output;
  678. for (std::string const& sr : strings) {
  679. // Separate the strings in the output to make it a list.
  680. output += sep;
  681. sep = ";";
  682. // Store the string in the output, but escape semicolons to
  683. // make sure it is a list.
  684. for (char i : sr) {
  685. if (i == ';') {
  686. output += '\\';
  687. }
  688. output += i;
  689. }
  690. }
  691. // Save the output in a makefile variable.
  692. this->Makefile->AddDefinition(outVar, output.c_str());
  693. return true;
  694. }
  695. bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
  696. bool recurse)
  697. {
  698. // File commands has at least one argument
  699. assert(args.size() > 1);
  700. std::vector<std::string>::const_iterator i = args.begin();
  701. i++; // Get rid of subcommand
  702. std::string variable = *i;
  703. i++;
  704. cmsys::Glob g;
  705. g.SetRecurse(recurse);
  706. bool explicitFollowSymlinks = false;
  707. cmPolicies::PolicyStatus status =
  708. this->Makefile->GetPolicyStatus(cmPolicies::CMP0009);
  709. if (recurse) {
  710. switch (status) {
  711. case cmPolicies::REQUIRED_IF_USED:
  712. case cmPolicies::REQUIRED_ALWAYS:
  713. case cmPolicies::NEW:
  714. g.RecurseThroughSymlinksOff();
  715. break;
  716. case cmPolicies::OLD:
  717. case cmPolicies::WARN:
  718. g.RecurseThroughSymlinksOn();
  719. break;
  720. }
  721. }
  722. std::vector<std::string> files;
  723. bool configureDepends = false;
  724. bool warnConfigureLate = false;
  725. bool warnFollowedSymlinks = false;
  726. const cmake::WorkingMode workingMode =
  727. this->Makefile->GetCMakeInstance()->GetWorkingMode();
  728. while (i != args.end()) {
  729. if (*i == "LIST_DIRECTORIES") {
  730. ++i; // skip LIST_DIRECTORIES
  731. if (i != args.end()) {
  732. if (cmSystemTools::IsOn(*i)) {
  733. g.SetListDirs(true);
  734. g.SetRecurseListDirs(true);
  735. } else if (cmSystemTools::IsOff(*i)) {
  736. g.SetListDirs(false);
  737. g.SetRecurseListDirs(false);
  738. } else {
  739. this->SetError("LIST_DIRECTORIES missing bool value.");
  740. return false;
  741. }
  742. ++i;
  743. } else {
  744. this->SetError("LIST_DIRECTORIES missing bool value.");
  745. return false;
  746. }
  747. } else if (*i == "FOLLOW_SYMLINKS") {
  748. ++i; // skip FOLLOW_SYMLINKS
  749. if (recurse) {
  750. explicitFollowSymlinks = true;
  751. g.RecurseThroughSymlinksOn();
  752. if (i == args.end()) {
  753. this->SetError(
  754. "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS.");
  755. return false;
  756. }
  757. }
  758. } else if (*i == "RELATIVE") {
  759. ++i; // skip RELATIVE
  760. if (i == args.end()) {
  761. this->SetError("GLOB requires a directory after the RELATIVE tag.");
  762. return false;
  763. }
  764. g.SetRelative(i->c_str());
  765. ++i;
  766. if (i == args.end()) {
  767. this->SetError("GLOB requires a glob expression after the directory.");
  768. return false;
  769. }
  770. } else if (*i == "CONFIGURE_DEPENDS") {
  771. // Generated build system depends on glob results
  772. if (!configureDepends && warnConfigureLate) {
  773. this->Makefile->IssueMessage(
  774. MessageType::AUTHOR_WARNING,
  775. "CONFIGURE_DEPENDS flag was given after a glob expression was "
  776. "already evaluated.");
  777. }
  778. if (workingMode != cmake::NORMAL_MODE) {
  779. this->Makefile->IssueMessage(
  780. MessageType::FATAL_ERROR,
  781. "CONFIGURE_DEPENDS is invalid for script and find package modes.");
  782. return false;
  783. }
  784. configureDepends = true;
  785. ++i;
  786. if (i == args.end()) {
  787. this->SetError(
  788. "GLOB requires a glob expression after CONFIGURE_DEPENDS.");
  789. return false;
  790. }
  791. } else {
  792. std::string expr = *i;
  793. if (!cmsys::SystemTools::FileIsFullPath(*i)) {
  794. expr = this->Makefile->GetCurrentSourceDirectory();
  795. // Handle script mode
  796. if (!expr.empty()) {
  797. expr += "/" + *i;
  798. } else {
  799. expr = *i;
  800. }
  801. }
  802. cmsys::Glob::GlobMessages globMessages;
  803. g.FindFiles(expr, &globMessages);
  804. if (!globMessages.empty()) {
  805. bool shouldExit = false;
  806. for (cmsys::Glob::Message const& globMessage : globMessages) {
  807. if (globMessage.type == cmsys::Glob::cyclicRecursion) {
  808. this->Makefile->IssueMessage(
  809. MessageType::AUTHOR_WARNING,
  810. "Cyclic recursion detected while globbing for '" + *i + "':\n" +
  811. globMessage.content);
  812. } else {
  813. this->Makefile->IssueMessage(
  814. MessageType::FATAL_ERROR,
  815. "Error has occurred while globbing for '" + *i + "' - " +
  816. globMessage.content);
  817. shouldExit = true;
  818. }
  819. }
  820. if (shouldExit) {
  821. return false;
  822. }
  823. }
  824. if (recurse && !explicitFollowSymlinks &&
  825. g.GetFollowedSymlinkCount() != 0) {
  826. warnFollowedSymlinks = true;
  827. }
  828. std::vector<std::string>& foundFiles = g.GetFiles();
  829. files.insert(files.end(), foundFiles.begin(), foundFiles.end());
  830. if (configureDepends) {
  831. std::sort(foundFiles.begin(), foundFiles.end());
  832. foundFiles.erase(std::unique(foundFiles.begin(), foundFiles.end()),
  833. foundFiles.end());
  834. this->Makefile->GetCMakeInstance()->AddGlobCacheEntry(
  835. recurse, (recurse ? g.GetRecurseListDirs() : g.GetListDirs()),
  836. (recurse ? g.GetRecurseThroughSymlinks() : false),
  837. (g.GetRelative() ? g.GetRelative() : ""), expr, foundFiles, variable,
  838. this->Makefile->GetBacktrace());
  839. } else {
  840. warnConfigureLate = true;
  841. }
  842. ++i;
  843. }
  844. }
  845. switch (status) {
  846. case cmPolicies::REQUIRED_IF_USED:
  847. case cmPolicies::REQUIRED_ALWAYS:
  848. case cmPolicies::NEW:
  849. // Correct behavior, yay!
  850. break;
  851. case cmPolicies::OLD:
  852. // Probably not really the expected behavior, but the author explicitly
  853. // asked for the old behavior... no warning.
  854. case cmPolicies::WARN:
  855. // Possibly unexpected old behavior *and* we actually traversed
  856. // symlinks without being explicitly asked to: warn the author.
  857. if (warnFollowedSymlinks) {
  858. this->Makefile->IssueMessage(
  859. MessageType::AUTHOR_WARNING,
  860. cmPolicies::GetPolicyWarning(cmPolicies::CMP0009));
  861. }
  862. break;
  863. }
  864. std::sort(files.begin(), files.end());
  865. files.erase(std::unique(files.begin(), files.end()), files.end());
  866. this->Makefile->AddDefinition(variable, cmJoin(files, ";").c_str());
  867. return true;
  868. }
  869. bool cmFileCommand::HandleMakeDirectoryCommand(
  870. std::vector<std::string> const& args)
  871. {
  872. // File command has at least one argument
  873. assert(args.size() > 1);
  874. std::string expr;
  875. for (std::string const& arg :
  876. cmMakeRange(args).advance(1)) // Get rid of subcommand
  877. {
  878. const std::string* cdir = &arg;
  879. if (!cmsys::SystemTools::FileIsFullPath(arg)) {
  880. expr = this->Makefile->GetCurrentSourceDirectory();
  881. expr += "/" + arg;
  882. cdir = &expr;
  883. }
  884. if (!this->Makefile->CanIWriteThisFile(*cdir)) {
  885. std::string e = "attempted to create a directory: " + *cdir +
  886. " into a source directory.";
  887. this->SetError(e);
  888. cmSystemTools::SetFatalErrorOccured();
  889. return false;
  890. }
  891. if (!cmSystemTools::MakeDirectory(*cdir)) {
  892. std::string error = "problem creating directory: " + *cdir;
  893. this->SetError(error);
  894. return false;
  895. }
  896. }
  897. return true;
  898. }
  899. bool cmFileCommand::HandleTouchCommand(std::vector<std::string> const& args,
  900. bool create)
  901. {
  902. // File command has at least one argument
  903. assert(args.size() > 1);
  904. for (std::string const& arg :
  905. cmMakeRange(args).advance(1)) // Get rid of subcommand
  906. {
  907. std::string tfile = arg;
  908. if (!cmsys::SystemTools::FileIsFullPath(tfile)) {
  909. tfile = this->Makefile->GetCurrentSourceDirectory();
  910. tfile += "/" + arg;
  911. }
  912. if (!this->Makefile->CanIWriteThisFile(tfile)) {
  913. std::string e =
  914. "attempted to touch a file: " + tfile + " in a source directory.";
  915. this->SetError(e);
  916. cmSystemTools::SetFatalErrorOccured();
  917. return false;
  918. }
  919. if (!cmSystemTools::Touch(tfile, create)) {
  920. std::string error = "problem touching file: " + tfile;
  921. this->SetError(error);
  922. return false;
  923. }
  924. }
  925. return true;
  926. }
  927. bool cmFileCommand::HandleDifferentCommand(
  928. std::vector<std::string> const& args)
  929. {
  930. /*
  931. FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
  932. */
  933. // Evaluate arguments.
  934. const char* file_lhs = nullptr;
  935. const char* file_rhs = nullptr;
  936. const char* var = nullptr;
  937. enum Doing
  938. {
  939. DoingNone,
  940. DoingVar,
  941. DoingFileLHS,
  942. DoingFileRHS
  943. };
  944. Doing doing = DoingVar;
  945. for (unsigned int i = 1; i < args.size(); ++i) {
  946. if (args[i] == "FILES") {
  947. doing = DoingFileLHS;
  948. } else if (doing == DoingVar) {
  949. var = args[i].c_str();
  950. doing = DoingNone;
  951. } else if (doing == DoingFileLHS) {
  952. file_lhs = args[i].c_str();
  953. doing = DoingFileRHS;
  954. } else if (doing == DoingFileRHS) {
  955. file_rhs = args[i].c_str();
  956. doing = DoingNone;
  957. } else {
  958. std::ostringstream e;
  959. e << "DIFFERENT given unknown argument " << args[i];
  960. this->SetError(e.str());
  961. return false;
  962. }
  963. }
  964. if (!var) {
  965. this->SetError("DIFFERENT not given result variable name.");
  966. return false;
  967. }
  968. if (!file_lhs || !file_rhs) {
  969. this->SetError("DIFFERENT not given FILES option with two file names.");
  970. return false;
  971. }
  972. // Compare the files.
  973. const char* result =
  974. cmSystemTools::FilesDiffer(file_lhs, file_rhs) ? "1" : "0";
  975. this->Makefile->AddDefinition(var, result);
  976. return true;
  977. }
  978. bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
  979. {
  980. cmFileCopier copier(this);
  981. return copier.Run(args);
  982. }
  983. bool cmFileCommand::HandleRPathChangeCommand(
  984. std::vector<std::string> const& args)
  985. {
  986. // Evaluate arguments.
  987. std::string file;
  988. const char* oldRPath = nullptr;
  989. const char* newRPath = nullptr;
  990. enum Doing
  991. {
  992. DoingNone,
  993. DoingFile,
  994. DoingOld,
  995. DoingNew
  996. };
  997. Doing doing = DoingNone;
  998. for (unsigned int i = 1; i < args.size(); ++i) {
  999. if (args[i] == "OLD_RPATH") {
  1000. doing = DoingOld;
  1001. } else if (args[i] == "NEW_RPATH") {
  1002. doing = DoingNew;
  1003. } else if (args[i] == "FILE") {
  1004. doing = DoingFile;
  1005. } else if (doing == DoingFile) {
  1006. file = args[i];
  1007. doing = DoingNone;
  1008. } else if (doing == DoingOld) {
  1009. oldRPath = args[i].c_str();
  1010. doing = DoingNone;
  1011. } else if (doing == DoingNew) {
  1012. newRPath = args[i].c_str();
  1013. doing = DoingNone;
  1014. } else {
  1015. std::ostringstream e;
  1016. e << "RPATH_CHANGE given unknown argument " << args[i];
  1017. this->SetError(e.str());
  1018. return false;
  1019. }
  1020. }
  1021. if (file.empty()) {
  1022. this->SetError("RPATH_CHANGE not given FILE option.");
  1023. return false;
  1024. }
  1025. if (!oldRPath) {
  1026. this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
  1027. return false;
  1028. }
  1029. if (!newRPath) {
  1030. this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
  1031. return false;
  1032. }
  1033. if (!cmSystemTools::FileExists(file, true)) {
  1034. std::ostringstream e;
  1035. e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
  1036. this->SetError(e.str());
  1037. return false;
  1038. }
  1039. bool success = true;
  1040. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  1041. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  1042. std::string emsg;
  1043. bool changed;
  1044. if (!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed)) {
  1045. std::ostringstream e;
  1046. /* clang-format off */
  1047. e << "RPATH_CHANGE could not write new RPATH:\n"
  1048. << " " << newRPath << "\n"
  1049. << "to the file:\n"
  1050. << " " << file << "\n"
  1051. << emsg;
  1052. /* clang-format on */
  1053. this->SetError(e.str());
  1054. success = false;
  1055. }
  1056. if (success) {
  1057. if (changed) {
  1058. std::string message = "Set runtime path of \"";
  1059. message += file;
  1060. message += "\" to \"";
  1061. message += newRPath;
  1062. message += "\"";
  1063. this->Makefile->DisplayStatus(message, -1);
  1064. }
  1065. if (have_ft) {
  1066. cmSystemTools::FileTimeSet(file, ft);
  1067. }
  1068. }
  1069. cmSystemTools::FileTimeDelete(ft);
  1070. return success;
  1071. }
  1072. bool cmFileCommand::HandleRPathRemoveCommand(
  1073. std::vector<std::string> const& args)
  1074. {
  1075. // Evaluate arguments.
  1076. std::string file;
  1077. enum Doing
  1078. {
  1079. DoingNone,
  1080. DoingFile
  1081. };
  1082. Doing doing = DoingNone;
  1083. for (unsigned int i = 1; i < args.size(); ++i) {
  1084. if (args[i] == "FILE") {
  1085. doing = DoingFile;
  1086. } else if (doing == DoingFile) {
  1087. file = args[i];
  1088. doing = DoingNone;
  1089. } else {
  1090. std::ostringstream e;
  1091. e << "RPATH_REMOVE given unknown argument " << args[i];
  1092. this->SetError(e.str());
  1093. return false;
  1094. }
  1095. }
  1096. if (file.empty()) {
  1097. this->SetError("RPATH_REMOVE not given FILE option.");
  1098. return false;
  1099. }
  1100. if (!cmSystemTools::FileExists(file, true)) {
  1101. std::ostringstream e;
  1102. e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
  1103. this->SetError(e.str());
  1104. return false;
  1105. }
  1106. bool success = true;
  1107. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  1108. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  1109. std::string emsg;
  1110. bool removed;
  1111. if (!cmSystemTools::RemoveRPath(file, &emsg, &removed)) {
  1112. std::ostringstream e;
  1113. /* clang-format off */
  1114. e << "RPATH_REMOVE could not remove RPATH from file:\n"
  1115. << " " << file << "\n"
  1116. << emsg;
  1117. /* clang-format on */
  1118. this->SetError(e.str());
  1119. success = false;
  1120. }
  1121. if (success) {
  1122. if (removed) {
  1123. std::string message = "Removed runtime path from \"";
  1124. message += file;
  1125. message += "\"";
  1126. this->Makefile->DisplayStatus(message, -1);
  1127. }
  1128. if (have_ft) {
  1129. cmSystemTools::FileTimeSet(file, ft);
  1130. }
  1131. }
  1132. cmSystemTools::FileTimeDelete(ft);
  1133. return success;
  1134. }
  1135. bool cmFileCommand::HandleRPathCheckCommand(
  1136. std::vector<std::string> const& args)
  1137. {
  1138. // Evaluate arguments.
  1139. std::string file;
  1140. const char* rpath = nullptr;
  1141. enum Doing
  1142. {
  1143. DoingNone,
  1144. DoingFile,
  1145. DoingRPath
  1146. };
  1147. Doing doing = DoingNone;
  1148. for (unsigned int i = 1; i < args.size(); ++i) {
  1149. if (args[i] == "RPATH") {
  1150. doing = DoingRPath;
  1151. } else if (args[i] == "FILE") {
  1152. doing = DoingFile;
  1153. } else if (doing == DoingFile) {
  1154. file = args[i];
  1155. doing = DoingNone;
  1156. } else if (doing == DoingRPath) {
  1157. rpath = args[i].c_str();
  1158. doing = DoingNone;
  1159. } else {
  1160. std::ostringstream e;
  1161. e << "RPATH_CHECK given unknown argument " << args[i];
  1162. this->SetError(e.str());
  1163. return false;
  1164. }
  1165. }
  1166. if (file.empty()) {
  1167. this->SetError("RPATH_CHECK not given FILE option.");
  1168. return false;
  1169. }
  1170. if (!rpath) {
  1171. this->SetError("RPATH_CHECK not given RPATH option.");
  1172. return false;
  1173. }
  1174. // If the file exists but does not have the desired RPath then
  1175. // delete it. This is used during installation to re-install a file
  1176. // if its RPath will change.
  1177. if (cmSystemTools::FileExists(file, true) &&
  1178. !cmSystemTools::CheckRPath(file, rpath)) {
  1179. cmSystemTools::RemoveFile(file);
  1180. }
  1181. return true;
  1182. }
  1183. bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args)
  1184. {
  1185. if (args.size() < 4) {
  1186. this->SetError("READ_ELF must be called with at least three additional "
  1187. "arguments.");
  1188. return false;
  1189. }
  1190. std::string const& fileNameArg = args[1];
  1191. struct Arguments
  1192. {
  1193. std::string RPath;
  1194. std::string RunPath;
  1195. std::string Error;
  1196. };
  1197. static auto const parser = cmArgumentParser<Arguments>{}
  1198. .Bind("RPATH"_s, &Arguments::RPath)
  1199. .Bind("RUNPATH"_s, &Arguments::RunPath)
  1200. .Bind("CAPTURE_ERROR"_s, &Arguments::Error);
  1201. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(2));
  1202. if (!cmSystemTools::FileExists(fileNameArg, true)) {
  1203. std::ostringstream e;
  1204. e << "READ_ELF given FILE \"" << fileNameArg << "\" that does not exist.";
  1205. this->SetError(e.str());
  1206. return false;
  1207. }
  1208. #if defined(CMAKE_USE_ELF_PARSER)
  1209. cmELF elf(fileNameArg.c_str());
  1210. if (!arguments.RPath.empty()) {
  1211. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  1212. std::string rpath(se_rpath->Value);
  1213. std::replace(rpath.begin(), rpath.end(), ':', ';');
  1214. this->Makefile->AddDefinition(arguments.RPath, rpath.c_str());
  1215. }
  1216. }
  1217. if (!arguments.RunPath.empty()) {
  1218. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  1219. std::string runpath(se_runpath->Value);
  1220. std::replace(runpath.begin(), runpath.end(), ':', ';');
  1221. this->Makefile->AddDefinition(arguments.RunPath, runpath.c_str());
  1222. }
  1223. }
  1224. return true;
  1225. #else
  1226. std::string error = "ELF parser not available on this platform.";
  1227. if (arguments.Error.empty()) {
  1228. this->SetError(error);
  1229. return false;
  1230. }
  1231. this->Makefile->AddDefinition(arguments.Error, error.c_str());
  1232. return true;
  1233. #endif
  1234. }
  1235. bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
  1236. {
  1237. cmFileInstaller installer(this);
  1238. return installer.Run(args);
  1239. }
  1240. bool cmFileCommand::HandleRelativePathCommand(
  1241. std::vector<std::string> const& args)
  1242. {
  1243. if (args.size() != 4) {
  1244. this->SetError("RELATIVE_PATH called with incorrect number of arguments");
  1245. return false;
  1246. }
  1247. const std::string& outVar = args[1];
  1248. const std::string& directoryName = args[2];
  1249. const std::string& fileName = args[3];
  1250. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1251. std::string errstring =
  1252. "RELATIVE_PATH must be passed a full path to the directory: " +
  1253. directoryName;
  1254. this->SetError(errstring);
  1255. return false;
  1256. }
  1257. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1258. std::string errstring =
  1259. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1260. this->SetError(errstring);
  1261. return false;
  1262. }
  1263. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1264. this->Makefile->AddDefinition(outVar, res.c_str());
  1265. return true;
  1266. }
  1267. bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
  1268. {
  1269. if (args.size() != 3) {
  1270. this->SetError("RENAME given incorrect number of arguments.");
  1271. return false;
  1272. }
  1273. // Compute full path for old and new names.
  1274. std::string oldname = args[1];
  1275. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1276. oldname = this->Makefile->GetCurrentSourceDirectory();
  1277. oldname += "/" + args[1];
  1278. }
  1279. std::string newname = args[2];
  1280. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1281. newname = this->Makefile->GetCurrentSourceDirectory();
  1282. newname += "/" + args[2];
  1283. }
  1284. if (!cmSystemTools::RenameFile(oldname, newname)) {
  1285. std::string err = cmSystemTools::GetLastSystemError();
  1286. std::ostringstream e;
  1287. /* clang-format off */
  1288. e << "RENAME failed to rename\n"
  1289. << " " << oldname << "\n"
  1290. << "to\n"
  1291. << " " << newname << "\n"
  1292. << "because: " << err << "\n";
  1293. /* clang-format on */
  1294. this->SetError(e.str());
  1295. return false;
  1296. }
  1297. return true;
  1298. }
  1299. bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
  1300. bool recurse)
  1301. {
  1302. std::string message;
  1303. for (std::string const& arg :
  1304. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1305. {
  1306. std::string fileName = arg;
  1307. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1308. fileName = this->Makefile->GetCurrentSourceDirectory();
  1309. fileName += "/" + arg;
  1310. }
  1311. if (cmSystemTools::FileIsDirectory(fileName) &&
  1312. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1313. cmSystemTools::RemoveADirectory(fileName);
  1314. } else {
  1315. cmSystemTools::RemoveFile(fileName);
  1316. }
  1317. }
  1318. return true;
  1319. }
  1320. namespace {
  1321. std::string ToNativePath(const std::string& path)
  1322. {
  1323. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1324. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1325. outPath.back() == '\"') {
  1326. return outPath.substr(1, outPath.size() - 2);
  1327. }
  1328. return outPath;
  1329. }
  1330. std::string ToCMakePath(const std::string& path)
  1331. {
  1332. auto temp = path;
  1333. cmSystemTools::ConvertToUnixSlashes(temp);
  1334. return temp;
  1335. }
  1336. }
  1337. bool cmFileCommand::HandleCMakePathCommand(
  1338. std::vector<std::string> const& args, bool nativePath)
  1339. {
  1340. if (args.size() != 3) {
  1341. this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1342. "called with exactly three arguments.");
  1343. return false;
  1344. }
  1345. #if defined(_WIN32) && !defined(__CYGWIN__)
  1346. char pathSep = ';';
  1347. #else
  1348. char pathSep = ':';
  1349. #endif
  1350. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1351. std::string value = cmJoin(
  1352. cmMakeRange(path).transform(nativePath ? ToNativePath : ToCMakePath), ";");
  1353. this->Makefile->AddDefinition(args[2], value.c_str());
  1354. return true;
  1355. }
  1356. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1357. // Stuff for curl download/upload
  1358. typedef std::vector<char> cmFileCommandVectorOfChar;
  1359. namespace {
  1360. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1361. {
  1362. int realsize = static_cast<int>(size * nmemb);
  1363. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1364. const char* chPtr = static_cast<char*>(ptr);
  1365. fout->write(chPtr, realsize);
  1366. return realsize;
  1367. }
  1368. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1369. void* data)
  1370. {
  1371. int realsize = static_cast<int>(size * nmemb);
  1372. cmFileCommandVectorOfChar* vec =
  1373. static_cast<cmFileCommandVectorOfChar*>(data);
  1374. const char* chPtr = static_cast<char*>(ptr);
  1375. vec->insert(vec->end(), chPtr, chPtr + realsize);
  1376. return realsize;
  1377. }
  1378. size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1379. size_t size, void* data)
  1380. {
  1381. cmFileCommandVectorOfChar* vec =
  1382. static_cast<cmFileCommandVectorOfChar*>(data);
  1383. switch (type) {
  1384. case CURLINFO_TEXT:
  1385. case CURLINFO_HEADER_IN:
  1386. case CURLINFO_HEADER_OUT:
  1387. vec->insert(vec->end(), chPtr, chPtr + size);
  1388. break;
  1389. case CURLINFO_DATA_IN:
  1390. case CURLINFO_DATA_OUT:
  1391. case CURLINFO_SSL_DATA_IN:
  1392. case CURLINFO_SSL_DATA_OUT: {
  1393. char buf[128];
  1394. int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1395. static_cast<KWIML_INT_uint64_t>(size));
  1396. if (n > 0) {
  1397. vec->insert(vec->end(), buf, buf + n);
  1398. }
  1399. } break;
  1400. default:
  1401. break;
  1402. }
  1403. return 0;
  1404. }
  1405. class cURLProgressHelper
  1406. {
  1407. public:
  1408. cURLProgressHelper(cmFileCommand* fc, const char* text)
  1409. {
  1410. this->CurrentPercentage = -1;
  1411. this->FileCommand = fc;
  1412. this->Text = text;
  1413. }
  1414. bool UpdatePercentage(double value, double total, std::string& status)
  1415. {
  1416. long OldPercentage = this->CurrentPercentage;
  1417. if (total > 0.0) {
  1418. this->CurrentPercentage = std::lround(value / total * 100.0);
  1419. if (this->CurrentPercentage > 100) {
  1420. // Avoid extra progress reports for unexpected data beyond total.
  1421. this->CurrentPercentage = 100;
  1422. }
  1423. }
  1424. bool updated = (OldPercentage != this->CurrentPercentage);
  1425. if (updated) {
  1426. std::ostringstream oss;
  1427. oss << "[" << this->Text << " " << this->CurrentPercentage
  1428. << "% complete]";
  1429. status = oss.str();
  1430. }
  1431. return updated;
  1432. }
  1433. cmFileCommand* GetFileCommand() { return this->FileCommand; }
  1434. private:
  1435. long CurrentPercentage;
  1436. cmFileCommand* FileCommand;
  1437. std::string Text;
  1438. };
  1439. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1440. double ultotal, double ulnow)
  1441. {
  1442. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1443. static_cast<void>(ultotal);
  1444. static_cast<void>(ulnow);
  1445. std::string status;
  1446. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1447. cmFileCommand* fc = helper->GetFileCommand();
  1448. cmMakefile* mf = fc->GetMakefile();
  1449. mf->DisplayStatus(status, -1);
  1450. }
  1451. return 0;
  1452. }
  1453. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1454. double ultotal, double ulnow)
  1455. {
  1456. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1457. static_cast<void>(dltotal);
  1458. static_cast<void>(dlnow);
  1459. std::string status;
  1460. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1461. cmFileCommand* fc = helper->GetFileCommand();
  1462. cmMakefile* mf = fc->GetMakefile();
  1463. mf->DisplayStatus(status, -1);
  1464. }
  1465. return 0;
  1466. }
  1467. }
  1468. namespace {
  1469. class cURLEasyGuard
  1470. {
  1471. public:
  1472. cURLEasyGuard(CURL* easy)
  1473. : Easy(easy)
  1474. {
  1475. }
  1476. ~cURLEasyGuard()
  1477. {
  1478. if (this->Easy) {
  1479. ::curl_easy_cleanup(this->Easy);
  1480. }
  1481. }
  1482. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1483. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1484. void release() { this->Easy = nullptr; }
  1485. private:
  1486. ::CURL* Easy;
  1487. };
  1488. }
  1489. #endif
  1490. #define check_curl_result(result, errstr) \
  1491. do { \
  1492. if (result != CURLE_OK) { \
  1493. std::string e(errstr); \
  1494. e += ::curl_easy_strerror(result); \
  1495. this->SetError(e); \
  1496. return false; \
  1497. } \
  1498. } while (false)
  1499. bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
  1500. {
  1501. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1502. std::vector<std::string>::const_iterator i = args.begin();
  1503. if (args.size() < 3) {
  1504. this->SetError("DOWNLOAD must be called with at least three arguments.");
  1505. return false;
  1506. }
  1507. ++i; // Get rid of subcommand
  1508. std::string url = *i;
  1509. ++i;
  1510. std::string file = *i;
  1511. ++i;
  1512. long timeout = 0;
  1513. long inactivity_timeout = 0;
  1514. std::string logVar;
  1515. std::string statusVar;
  1516. bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
  1517. const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
  1518. std::string netrc_level = this->Makefile->GetSafeDefinition("CMAKE_NETRC");
  1519. std::string netrc_file =
  1520. this->Makefile->GetSafeDefinition("CMAKE_NETRC_FILE");
  1521. std::string expectedHash;
  1522. std::string hashMatchMSG;
  1523. std::unique_ptr<cmCryptoHash> hash;
  1524. bool showProgress = false;
  1525. std::string userpwd;
  1526. std::vector<std::string> curl_headers;
  1527. while (i != args.end()) {
  1528. if (*i == "TIMEOUT") {
  1529. ++i;
  1530. if (i != args.end()) {
  1531. timeout = atol(i->c_str());
  1532. } else {
  1533. this->SetError("DOWNLOAD missing time for TIMEOUT.");
  1534. return false;
  1535. }
  1536. } else if (*i == "INACTIVITY_TIMEOUT") {
  1537. ++i;
  1538. if (i != args.end()) {
  1539. inactivity_timeout = atol(i->c_str());
  1540. } else {
  1541. this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1542. return false;
  1543. }
  1544. } else if (*i == "LOG") {
  1545. ++i;
  1546. if (i == args.end()) {
  1547. this->SetError("DOWNLOAD missing VAR for LOG.");
  1548. return false;
  1549. }
  1550. logVar = *i;
  1551. } else if (*i == "STATUS") {
  1552. ++i;
  1553. if (i == args.end()) {
  1554. this->SetError("DOWNLOAD missing VAR for STATUS.");
  1555. return false;
  1556. }
  1557. statusVar = *i;
  1558. } else if (*i == "TLS_VERIFY") {
  1559. ++i;
  1560. if (i != args.end()) {
  1561. tls_verify = cmSystemTools::IsOn(*i);
  1562. } else {
  1563. this->SetError("TLS_VERIFY missing bool value.");
  1564. return false;
  1565. }
  1566. } else if (*i == "TLS_CAINFO") {
  1567. ++i;
  1568. if (i != args.end()) {
  1569. cainfo = i->c_str();
  1570. } else {
  1571. this->SetError("TLS_CAFILE missing file value.");
  1572. return false;
  1573. }
  1574. } else if (*i == "NETRC_FILE") {
  1575. ++i;
  1576. if (i != args.end()) {
  1577. netrc_file = *i;
  1578. } else {
  1579. this->SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1580. return false;
  1581. }
  1582. } else if (*i == "NETRC") {
  1583. ++i;
  1584. if (i != args.end()) {
  1585. netrc_level = *i;
  1586. } else {
  1587. this->SetError("DOWNLOAD missing level value for NETRC.");
  1588. return false;
  1589. }
  1590. } else if (*i == "EXPECTED_MD5") {
  1591. ++i;
  1592. if (i == args.end()) {
  1593. this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1594. return false;
  1595. }
  1596. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1597. hashMatchMSG = "MD5 sum";
  1598. expectedHash = cmSystemTools::LowerCase(*i);
  1599. } else if (*i == "SHOW_PROGRESS") {
  1600. showProgress = true;
  1601. } else if (*i == "EXPECTED_HASH") {
  1602. ++i;
  1603. if (i == args.end()) {
  1604. this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1605. return false;
  1606. }
  1607. std::string::size_type pos = i->find("=");
  1608. if (pos == std::string::npos) {
  1609. std::string err =
  1610. "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
  1611. err += *i;
  1612. this->SetError(err);
  1613. return false;
  1614. }
  1615. std::string algo = i->substr(0, pos);
  1616. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1617. hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
  1618. if (!hash) {
  1619. std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
  1620. err += algo;
  1621. this->SetError(err);
  1622. return false;
  1623. }
  1624. hashMatchMSG = algo + " hash";
  1625. } else if (*i == "USERPWD") {
  1626. ++i;
  1627. if (i == args.end()) {
  1628. this->SetError("DOWNLOAD missing string for USERPWD.");
  1629. return false;
  1630. }
  1631. userpwd = *i;
  1632. } else if (*i == "HTTPHEADER") {
  1633. ++i;
  1634. if (i == args.end()) {
  1635. this->SetError("DOWNLOAD missing string for HTTPHEADER.");
  1636. return false;
  1637. }
  1638. curl_headers.push_back(*i);
  1639. } else {
  1640. // Do not return error for compatibility reason.
  1641. std::string err = "Unexpected argument: ";
  1642. err += *i;
  1643. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, err);
  1644. }
  1645. ++i;
  1646. }
  1647. // If file exists already, and caller specified an expected md5 or sha,
  1648. // and the existing file already has the expected hash, then simply
  1649. // return.
  1650. //
  1651. if (cmSystemTools::FileExists(file) && hash.get()) {
  1652. std::string msg;
  1653. std::string actualHash = hash->HashFile(file);
  1654. if (actualHash == expectedHash) {
  1655. msg = "returning early; file already exists with expected ";
  1656. msg += hashMatchMSG;
  1657. msg += "\"";
  1658. if (!statusVar.empty()) {
  1659. std::ostringstream result;
  1660. result << 0 << ";\"" << msg;
  1661. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  1662. }
  1663. return true;
  1664. }
  1665. }
  1666. // Make sure parent directory exists so we can write to the file
  1667. // as we receive downloaded bits from curl...
  1668. //
  1669. std::string dir = cmSystemTools::GetFilenamePath(file);
  1670. if (!cmSystemTools::FileExists(dir) && !cmSystemTools::MakeDirectory(dir)) {
  1671. std::string errstring = "DOWNLOAD error: cannot create directory '" + dir +
  1672. "' - Specify file by full path name and verify that you "
  1673. "have directory creation and file write privileges.";
  1674. this->SetError(errstring);
  1675. return false;
  1676. }
  1677. cmsys::ofstream fout(file.c_str(), std::ios::binary);
  1678. if (!fout) {
  1679. this->SetError("DOWNLOAD cannot open file for write.");
  1680. return false;
  1681. }
  1682. # if defined(_WIN32)
  1683. url = fix_file_url_windows(url);
  1684. # endif
  1685. ::CURL* curl;
  1686. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1687. curl = ::curl_easy_init();
  1688. if (!curl) {
  1689. this->SetError("DOWNLOAD error initializing curl.");
  1690. return false;
  1691. }
  1692. cURLEasyGuard g_curl(curl);
  1693. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1694. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1695. // enable HTTP ERROR parsing
  1696. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1697. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1698. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1699. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1700. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1701. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1702. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1703. cmFileCommandCurlDebugCallback);
  1704. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1705. // check to see if TLS verification is requested
  1706. if (tls_verify) {
  1707. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1708. check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
  1709. } else {
  1710. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1711. check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
  1712. }
  1713. // check to see if a CAINFO file has been specified
  1714. // command arg comes first
  1715. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  1716. if (!cainfo_err.empty()) {
  1717. this->SetError(cainfo_err);
  1718. return false;
  1719. }
  1720. // check to see if netrc parameters have been specified
  1721. // local command args takes precedence over CMAKE_NETRC*
  1722. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1723. std::string const& netrc_option_err =
  1724. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1725. if (!netrc_option_err.empty()) {
  1726. this->SetError(netrc_option_err);
  1727. return false;
  1728. }
  1729. cmFileCommandVectorOfChar chunkDebug;
  1730. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fout);
  1731. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1732. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1733. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1734. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1735. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1736. if (!logVar.empty()) {
  1737. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1738. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1739. }
  1740. if (timeout > 0) {
  1741. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1742. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1743. }
  1744. if (inactivity_timeout > 0) {
  1745. // Give up if there is no progress for a long time.
  1746. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1747. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1748. }
  1749. // Need the progress helper's scope to last through the duration of
  1750. // the curl_easy_perform call... so this object is declared at function
  1751. // scope intentionally, rather than inside the "if(showProgress)"
  1752. // block...
  1753. //
  1754. cURLProgressHelper helper(this, "download");
  1755. if (showProgress) {
  1756. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1757. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1758. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1759. cmFileDownloadProgressCallback);
  1760. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1761. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1762. reinterpret_cast<void*>(&helper));
  1763. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1764. }
  1765. if (!userpwd.empty()) {
  1766. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1767. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1768. }
  1769. struct curl_slist* headers = nullptr;
  1770. for (std::string const& h : curl_headers) {
  1771. headers = ::curl_slist_append(headers, h.c_str());
  1772. }
  1773. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1774. res = ::curl_easy_perform(curl);
  1775. ::curl_slist_free_all(headers);
  1776. /* always cleanup */
  1777. g_curl.release();
  1778. ::curl_easy_cleanup(curl);
  1779. if (!statusVar.empty()) {
  1780. std::ostringstream result;
  1781. result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
  1782. << "\"";
  1783. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  1784. }
  1785. ::curl_global_cleanup();
  1786. // Explicitly flush/close so we can measure the md5 accurately.
  1787. //
  1788. fout.flush();
  1789. fout.close();
  1790. // Verify MD5 sum if requested:
  1791. //
  1792. if (hash) {
  1793. std::string actualHash = hash->HashFile(file);
  1794. if (actualHash.empty()) {
  1795. this->SetError("DOWNLOAD cannot compute hash on downloaded file");
  1796. return false;
  1797. }
  1798. if (expectedHash != actualHash) {
  1799. std::ostringstream oss;
  1800. oss << "DOWNLOAD HASH mismatch" << std::endl
  1801. << " for file: [" << file << "]" << std::endl
  1802. << " expected hash: [" << expectedHash << "]" << std::endl
  1803. << " actual hash: [" << actualHash << "]" << std::endl
  1804. << " status: [" << static_cast<int>(res) << ";\""
  1805. << ::curl_easy_strerror(res) << "\"]" << std::endl;
  1806. if (!statusVar.empty() && res == 0) {
  1807. std::string status = "1;HASH mismatch: "
  1808. "expected: " +
  1809. expectedHash + " actual: " + actualHash;
  1810. this->Makefile->AddDefinition(statusVar, status.c_str());
  1811. }
  1812. this->SetError(oss.str());
  1813. return false;
  1814. }
  1815. }
  1816. if (!logVar.empty()) {
  1817. chunkDebug.push_back(0);
  1818. this->Makefile->AddDefinition(logVar, chunkDebug.data());
  1819. }
  1820. return true;
  1821. #else
  1822. this->SetError("DOWNLOAD not supported by bootstrap cmake.");
  1823. return false;
  1824. #endif
  1825. }
  1826. bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
  1827. {
  1828. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1829. if (args.size() < 3) {
  1830. this->SetError("UPLOAD must be called with at least three arguments.");
  1831. return false;
  1832. }
  1833. std::vector<std::string>::const_iterator i = args.begin();
  1834. ++i;
  1835. std::string filename = *i;
  1836. ++i;
  1837. std::string url = *i;
  1838. ++i;
  1839. long timeout = 0;
  1840. long inactivity_timeout = 0;
  1841. std::string logVar;
  1842. std::string statusVar;
  1843. bool showProgress = false;
  1844. std::string userpwd;
  1845. std::string netrc_level = this->Makefile->GetSafeDefinition("CMAKE_NETRC");
  1846. std::string netrc_file =
  1847. this->Makefile->GetSafeDefinition("CMAKE_NETRC_FILE");
  1848. std::vector<std::string> curl_headers;
  1849. while (i != args.end()) {
  1850. if (*i == "TIMEOUT") {
  1851. ++i;
  1852. if (i != args.end()) {
  1853. timeout = atol(i->c_str());
  1854. } else {
  1855. this->SetError("UPLOAD missing time for TIMEOUT.");
  1856. return false;
  1857. }
  1858. } else if (*i == "INACTIVITY_TIMEOUT") {
  1859. ++i;
  1860. if (i != args.end()) {
  1861. inactivity_timeout = atol(i->c_str());
  1862. } else {
  1863. this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1864. return false;
  1865. }
  1866. } else if (*i == "LOG") {
  1867. ++i;
  1868. if (i == args.end()) {
  1869. this->SetError("UPLOAD missing VAR for LOG.");
  1870. return false;
  1871. }
  1872. logVar = *i;
  1873. } else if (*i == "STATUS") {
  1874. ++i;
  1875. if (i == args.end()) {
  1876. this->SetError("UPLOAD missing VAR for STATUS.");
  1877. return false;
  1878. }
  1879. statusVar = *i;
  1880. } else if (*i == "SHOW_PROGRESS") {
  1881. showProgress = true;
  1882. } else if (*i == "NETRC_FILE") {
  1883. ++i;
  1884. if (i != args.end()) {
  1885. netrc_file = *i;
  1886. } else {
  1887. this->SetError("UPLOAD missing file value for NETRC_FILE.");
  1888. return false;
  1889. }
  1890. } else if (*i == "NETRC") {
  1891. ++i;
  1892. if (i != args.end()) {
  1893. netrc_level = *i;
  1894. } else {
  1895. this->SetError("UPLOAD missing level value for NETRC.");
  1896. return false;
  1897. }
  1898. } else if (*i == "USERPWD") {
  1899. ++i;
  1900. if (i == args.end()) {
  1901. this->SetError("UPLOAD missing string for USERPWD.");
  1902. return false;
  1903. }
  1904. userpwd = *i;
  1905. } else if (*i == "HTTPHEADER") {
  1906. ++i;
  1907. if (i == args.end()) {
  1908. this->SetError("UPLOAD missing string for HTTPHEADER.");
  1909. return false;
  1910. }
  1911. curl_headers.push_back(*i);
  1912. } else {
  1913. // Do not return error for compatibility reason.
  1914. std::string err = "Unexpected argument: ";
  1915. err += *i;
  1916. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, err);
  1917. }
  1918. ++i;
  1919. }
  1920. // Open file for reading:
  1921. //
  1922. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  1923. if (!fin) {
  1924. std::string errStr = "UPLOAD cannot open file '";
  1925. errStr += filename + "' for reading.";
  1926. this->SetError(errStr);
  1927. return false;
  1928. }
  1929. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  1930. # if defined(_WIN32)
  1931. url = fix_file_url_windows(url);
  1932. # endif
  1933. ::CURL* curl;
  1934. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1935. curl = ::curl_easy_init();
  1936. if (!curl) {
  1937. this->SetError("UPLOAD error initializing curl.");
  1938. fclose(fin);
  1939. return false;
  1940. }
  1941. cURLEasyGuard g_curl(curl);
  1942. // enable HTTP ERROR parsing
  1943. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1944. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  1945. // enable uploading
  1946. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  1947. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  1948. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1949. check_curl_result(res, "UPLOAD cannot set url: ");
  1950. res =
  1951. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  1952. check_curl_result(res, "UPLOAD cannot set write function: ");
  1953. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1954. cmFileCommandCurlDebugCallback);
  1955. check_curl_result(res, "UPLOAD cannot set debug function: ");
  1956. cmFileCommandVectorOfChar chunkResponse;
  1957. cmFileCommandVectorOfChar chunkDebug;
  1958. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  1959. check_curl_result(res, "UPLOAD cannot set write data: ");
  1960. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1961. check_curl_result(res, "UPLOAD cannot set debug data: ");
  1962. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1963. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  1964. if (!logVar.empty()) {
  1965. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1966. check_curl_result(res, "UPLOAD cannot set verbose: ");
  1967. }
  1968. if (timeout > 0) {
  1969. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1970. check_curl_result(res, "UPLOAD cannot set timeout: ");
  1971. }
  1972. if (inactivity_timeout > 0) {
  1973. // Give up if there is no progress for a long time.
  1974. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1975. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1976. }
  1977. // Need the progress helper's scope to last through the duration of
  1978. // the curl_easy_perform call... so this object is declared at function
  1979. // scope intentionally, rather than inside the "if(showProgress)"
  1980. // block...
  1981. //
  1982. cURLProgressHelper helper(this, "upload");
  1983. if (showProgress) {
  1984. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1985. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  1986. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1987. cmFileUploadProgressCallback);
  1988. check_curl_result(res, "UPLOAD cannot set progress function: ");
  1989. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1990. reinterpret_cast<void*>(&helper));
  1991. check_curl_result(res, "UPLOAD cannot set progress data: ");
  1992. }
  1993. // now specify which file to upload
  1994. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  1995. check_curl_result(res, "UPLOAD cannot set input file: ");
  1996. // and give the size of the upload (optional)
  1997. res =
  1998. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  1999. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2000. if (!userpwd.empty()) {
  2001. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2002. check_curl_result(res, "UPLOAD cannot set user password: ");
  2003. }
  2004. // check to see if netrc parameters have been specified
  2005. // local command args takes precedence over CMAKE_NETRC*
  2006. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2007. std::string const& netrc_option_err =
  2008. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2009. if (!netrc_option_err.empty()) {
  2010. this->SetError(netrc_option_err);
  2011. return false;
  2012. }
  2013. struct curl_slist* headers = nullptr;
  2014. for (std::string const& h : curl_headers) {
  2015. headers = ::curl_slist_append(headers, h.c_str());
  2016. }
  2017. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2018. res = ::curl_easy_perform(curl);
  2019. ::curl_slist_free_all(headers);
  2020. /* always cleanup */
  2021. g_curl.release();
  2022. ::curl_easy_cleanup(curl);
  2023. if (!statusVar.empty()) {
  2024. std::ostringstream result;
  2025. result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
  2026. << "\"";
  2027. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  2028. }
  2029. ::curl_global_cleanup();
  2030. fclose(fin);
  2031. fin = nullptr;
  2032. if (!logVar.empty()) {
  2033. std::string log;
  2034. if (!chunkResponse.empty()) {
  2035. chunkResponse.push_back(0);
  2036. log += "Response:\n";
  2037. log += chunkResponse.data();
  2038. log += "\n";
  2039. }
  2040. if (!chunkDebug.empty()) {
  2041. chunkDebug.push_back(0);
  2042. log += "Debug:\n";
  2043. log += chunkDebug.data();
  2044. log += "\n";
  2045. }
  2046. this->Makefile->AddDefinition(logVar, log.c_str());
  2047. }
  2048. return true;
  2049. #else
  2050. this->SetError("UPLOAD not supported by bootstrap cmake.");
  2051. return false;
  2052. #endif
  2053. }
  2054. void cmFileCommand::AddEvaluationFile(const std::string& inputName,
  2055. const std::string& outputExpr,
  2056. const std::string& condition,
  2057. bool inputIsContent)
  2058. {
  2059. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2060. cmGeneratorExpression outputGe(lfbt);
  2061. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2062. outputGe.Parse(outputExpr);
  2063. cmGeneratorExpression conditionGe(lfbt);
  2064. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2065. conditionGe.Parse(condition);
  2066. this->Makefile->AddEvaluationFile(inputName, std::move(outputCge),
  2067. std::move(conditionCge), inputIsContent);
  2068. }
  2069. bool cmFileCommand::HandleGenerateCommand(std::vector<std::string> const& args)
  2070. {
  2071. if (args.size() < 5) {
  2072. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2073. return false;
  2074. }
  2075. if (args[1] != "OUTPUT") {
  2076. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2077. return false;
  2078. }
  2079. std::string condition;
  2080. if (args.size() > 5) {
  2081. if (args[5] != "CONDITION") {
  2082. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2083. return false;
  2084. }
  2085. if (args.size() != 7) {
  2086. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2087. return false;
  2088. }
  2089. condition = args[6];
  2090. if (condition.empty()) {
  2091. this->SetError("CONDITION of sub-command GENERATE must not be empty if "
  2092. "specified.");
  2093. return false;
  2094. }
  2095. }
  2096. std::string output = args[2];
  2097. const bool inputIsContent = args[3] != "INPUT";
  2098. if (inputIsContent && args[3] != "CONTENT") {
  2099. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2100. return false;
  2101. }
  2102. std::string input = args[4];
  2103. this->AddEvaluationFile(input, output, condition, inputIsContent);
  2104. return true;
  2105. }
  2106. bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args)
  2107. {
  2108. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2109. // Default values
  2110. bool directory = false;
  2111. bool release = false;
  2112. enum Guard
  2113. {
  2114. GUARD_FUNCTION,
  2115. GUARD_FILE,
  2116. GUARD_PROCESS
  2117. };
  2118. Guard guard = GUARD_PROCESS;
  2119. std::string resultVariable;
  2120. unsigned long timeout = static_cast<unsigned long>(-1);
  2121. // Parse arguments
  2122. if (args.size() < 2) {
  2123. this->Makefile->IssueMessage(
  2124. MessageType::FATAL_ERROR,
  2125. "sub-command LOCK requires at least two arguments.");
  2126. return false;
  2127. }
  2128. std::string path = args[1];
  2129. for (unsigned i = 2; i < args.size(); ++i) {
  2130. if (args[i] == "DIRECTORY") {
  2131. directory = true;
  2132. } else if (args[i] == "RELEASE") {
  2133. release = true;
  2134. } else if (args[i] == "GUARD") {
  2135. ++i;
  2136. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2137. if (i >= args.size()) {
  2138. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, merr);
  2139. return false;
  2140. }
  2141. if (args[i] == "FUNCTION") {
  2142. guard = GUARD_FUNCTION;
  2143. } else if (args[i] == "FILE") {
  2144. guard = GUARD_FILE;
  2145. } else if (args[i] == "PROCESS") {
  2146. guard = GUARD_PROCESS;
  2147. } else {
  2148. std::ostringstream e;
  2149. e << merr << ", but got:\n \"" << args[i] << "\".";
  2150. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2151. return false;
  2152. }
  2153. } else if (args[i] == "RESULT_VARIABLE") {
  2154. ++i;
  2155. if (i >= args.size()) {
  2156. this->Makefile->IssueMessage(
  2157. MessageType::FATAL_ERROR,
  2158. "expected variable name after RESULT_VARIABLE");
  2159. return false;
  2160. }
  2161. resultVariable = args[i];
  2162. } else if (args[i] == "TIMEOUT") {
  2163. ++i;
  2164. if (i >= args.size()) {
  2165. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  2166. "expected timeout value after TIMEOUT");
  2167. return false;
  2168. }
  2169. long scanned;
  2170. if (!cmSystemTools::StringToLong(args[i].c_str(), &scanned) ||
  2171. scanned < 0) {
  2172. std::ostringstream e;
  2173. e << "TIMEOUT value \"" << args[i] << "\" is not an unsigned integer.";
  2174. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2175. return false;
  2176. }
  2177. timeout = static_cast<unsigned long>(scanned);
  2178. } else {
  2179. std::ostringstream e;
  2180. e << "expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or TIMEOUT\n";
  2181. e << "but got: \"" << args[i] << "\".";
  2182. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2183. return false;
  2184. }
  2185. }
  2186. if (directory) {
  2187. path += "/cmake.lock";
  2188. }
  2189. if (!cmsys::SystemTools::FileIsFullPath(path)) {
  2190. path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
  2191. }
  2192. // Unify path (remove '//', '/../', ...)
  2193. path = cmSystemTools::CollapseFullPath(path);
  2194. // Create file and directories if needed
  2195. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2196. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2197. std::ostringstream e;
  2198. e << "directory\n \"" << parentDir << "\"\ncreation failed ";
  2199. e << "(check permissions).";
  2200. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2201. cmSystemTools::SetFatalErrorOccured();
  2202. return false;
  2203. }
  2204. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2205. if (!file) {
  2206. std::ostringstream e;
  2207. e << "file\n \"" << path << "\"\ncreation failed (check permissions).";
  2208. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2209. cmSystemTools::SetFatalErrorOccured();
  2210. return false;
  2211. }
  2212. fclose(file);
  2213. // Actual lock/unlock
  2214. cmFileLockPool& lockPool =
  2215. this->Makefile->GetGlobalGenerator()->GetFileLockPool();
  2216. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2217. if (release) {
  2218. fileLockResult = lockPool.Release(path);
  2219. } else {
  2220. switch (guard) {
  2221. case GUARD_FUNCTION:
  2222. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2223. break;
  2224. case GUARD_FILE:
  2225. fileLockResult = lockPool.LockFileScope(path, timeout);
  2226. break;
  2227. case GUARD_PROCESS:
  2228. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2229. break;
  2230. default:
  2231. cmSystemTools::SetFatalErrorOccured();
  2232. return false;
  2233. }
  2234. }
  2235. const std::string result = fileLockResult.GetOutputMessage();
  2236. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2237. std::ostringstream e;
  2238. e << "error locking file\n \"" << path << "\"\n" << result << ".";
  2239. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2240. cmSystemTools::SetFatalErrorOccured();
  2241. return false;
  2242. }
  2243. if (!resultVariable.empty()) {
  2244. this->Makefile->AddDefinition(resultVariable, result.c_str());
  2245. }
  2246. return true;
  2247. #else
  2248. static_cast<void>(args);
  2249. this->SetError("sub-command LOCK not implemented in bootstrap cmake");
  2250. return false;
  2251. #endif
  2252. }
  2253. bool cmFileCommand::HandleTimestampCommand(
  2254. std::vector<std::string> const& args)
  2255. {
  2256. if (args.size() < 3) {
  2257. this->SetError("sub-command TIMESTAMP requires at least two arguments.");
  2258. return false;
  2259. }
  2260. if (args.size() > 5) {
  2261. this->SetError("sub-command TIMESTAMP takes at most four arguments.");
  2262. return false;
  2263. }
  2264. unsigned int argsIndex = 1;
  2265. const std::string& filename = args[argsIndex++];
  2266. const std::string& outputVariable = args[argsIndex++];
  2267. std::string formatString;
  2268. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2269. formatString = args[argsIndex++];
  2270. }
  2271. bool utcFlag = false;
  2272. if (args.size() > argsIndex) {
  2273. if (args[argsIndex] == "UTC") {
  2274. utcFlag = true;
  2275. } else {
  2276. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2277. args[argsIndex] + ".";
  2278. this->SetError(e);
  2279. return false;
  2280. }
  2281. }
  2282. cmTimestamp timestamp;
  2283. std::string result =
  2284. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2285. this->Makefile->AddDefinition(outputVariable, result.c_str());
  2286. return true;
  2287. }
  2288. bool cmFileCommand::HandleSizeCommand(std::vector<std::string> const& args)
  2289. {
  2290. if (args.size() != 3) {
  2291. std::ostringstream e;
  2292. e << args[0] << " requires a file name and output variable";
  2293. this->SetError(e.str());
  2294. return false;
  2295. }
  2296. unsigned int argsIndex = 1;
  2297. const std::string& filename = args[argsIndex++];
  2298. const std::string& outputVariable = args[argsIndex++];
  2299. if (!cmSystemTools::FileExists(filename, true)) {
  2300. std::ostringstream e;
  2301. e << "SIZE requested of path that is not readable:\n " << filename;
  2302. this->SetError(e.str());
  2303. return false;
  2304. }
  2305. this->Makefile->AddDefinition(
  2306. outputVariable,
  2307. std::to_string(cmSystemTools::FileLength(filename)).c_str());
  2308. return true;
  2309. }
  2310. bool cmFileCommand::HandleReadSymlinkCommand(
  2311. std::vector<std::string> const& args)
  2312. {
  2313. if (args.size() != 3) {
  2314. std::ostringstream e;
  2315. e << args[0] << " requires a file name and output variable";
  2316. this->SetError(e.str());
  2317. return false;
  2318. }
  2319. const std::string& filename = args[1];
  2320. const std::string& outputVariable = args[2];
  2321. std::string result;
  2322. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2323. std::ostringstream e;
  2324. e << "READ_SYMLINK requested of path that is not a symlink:\n "
  2325. << filename;
  2326. this->SetError(e.str());
  2327. return false;
  2328. }
  2329. this->Makefile->AddDefinition(outputVariable, result.c_str());
  2330. return true;
  2331. }
  2332. bool cmFileCommand::HandleCreateLinkCommand(
  2333. std::vector<std::string> const& args)
  2334. {
  2335. if (args.size() < 3) {
  2336. this->SetError("CREATE_LINK must be called with at least two additional "
  2337. "arguments");
  2338. return false;
  2339. }
  2340. std::string const& fileName = args[1];
  2341. std::string const& newFileName = args[2];
  2342. struct Arguments
  2343. {
  2344. std::string Result;
  2345. bool CopyOnError = false;
  2346. bool Symbolic = false;
  2347. };
  2348. static auto const parser =
  2349. cmArgumentParser<Arguments>{}
  2350. .Bind("RESULT"_s, &Arguments::Result)
  2351. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2352. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2353. std::vector<std::string> unconsumedArgs;
  2354. Arguments const arguments =
  2355. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2356. if (!unconsumedArgs.empty()) {
  2357. this->SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2358. return false;
  2359. }
  2360. // The system error message generated in the operation.
  2361. std::string result;
  2362. // Check if the paths are distinct.
  2363. if (fileName == newFileName) {
  2364. result = "CREATE_LINK cannot use same file and newfile";
  2365. if (!arguments.Result.empty()) {
  2366. this->Makefile->AddDefinition(arguments.Result, result.c_str());
  2367. return true;
  2368. }
  2369. this->SetError(result);
  2370. return false;
  2371. }
  2372. // Hard link requires original file to exist.
  2373. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2374. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2375. if (!arguments.Result.empty()) {
  2376. this->Makefile->AddDefinition(arguments.Result, result.c_str());
  2377. return true;
  2378. }
  2379. this->SetError(result);
  2380. return false;
  2381. }
  2382. // Check if the new file already exists and remove it.
  2383. if ((cmSystemTools::FileExists(newFileName) ||
  2384. cmSystemTools::FileIsSymlink(newFileName)) &&
  2385. !cmSystemTools::RemoveFile(newFileName)) {
  2386. std::ostringstream e;
  2387. e << "Failed to create link '" << newFileName
  2388. << "' because existing path cannot be removed: "
  2389. << cmSystemTools::GetLastSystemError() << "\n";
  2390. if (!arguments.Result.empty()) {
  2391. this->Makefile->AddDefinition(arguments.Result, e.str().c_str());
  2392. return true;
  2393. }
  2394. this->SetError(e.str());
  2395. return false;
  2396. }
  2397. // Whether the operation completed successfully.
  2398. bool completed = false;
  2399. // Check if the command requires a symbolic link.
  2400. if (arguments.Symbolic) {
  2401. completed = cmSystemTools::CreateSymlink(fileName, newFileName, &result);
  2402. } else {
  2403. completed = cmSystemTools::CreateLink(fileName, newFileName, &result);
  2404. }
  2405. // Check if copy-on-error is enabled in the arguments.
  2406. if (!completed && arguments.CopyOnError) {
  2407. completed = cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2408. if (!completed) {
  2409. result = "Copy failed: " + cmSystemTools::GetLastSystemError();
  2410. }
  2411. }
  2412. // Check if the operation was successful.
  2413. if (completed) {
  2414. result = "0";
  2415. } else if (arguments.Result.empty()) {
  2416. // The operation failed and the result is not reported in a variable.
  2417. this->SetError(result);
  2418. return false;
  2419. }
  2420. if (!arguments.Result.empty()) {
  2421. this->Makefile->AddDefinition(arguments.Result, result.c_str());
  2422. }
  2423. return true;
  2424. }