cmFileCommand.cxx 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702
  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 (fileName.empty()) {
  1308. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1309. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING,
  1310. "Ignoring empty file name in " + r + ".");
  1311. continue;
  1312. }
  1313. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1314. fileName = this->Makefile->GetCurrentSourceDirectory();
  1315. fileName += "/" + arg;
  1316. }
  1317. if (cmSystemTools::FileIsDirectory(fileName) &&
  1318. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1319. cmSystemTools::RemoveADirectory(fileName);
  1320. } else {
  1321. cmSystemTools::RemoveFile(fileName);
  1322. }
  1323. }
  1324. return true;
  1325. }
  1326. namespace {
  1327. std::string ToNativePath(const std::string& path)
  1328. {
  1329. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1330. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1331. outPath.back() == '\"') {
  1332. return outPath.substr(1, outPath.size() - 2);
  1333. }
  1334. return outPath;
  1335. }
  1336. std::string ToCMakePath(const std::string& path)
  1337. {
  1338. auto temp = path;
  1339. cmSystemTools::ConvertToUnixSlashes(temp);
  1340. return temp;
  1341. }
  1342. }
  1343. bool cmFileCommand::HandleCMakePathCommand(
  1344. std::vector<std::string> const& args, bool nativePath)
  1345. {
  1346. if (args.size() != 3) {
  1347. this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1348. "called with exactly three arguments.");
  1349. return false;
  1350. }
  1351. #if defined(_WIN32) && !defined(__CYGWIN__)
  1352. char pathSep = ';';
  1353. #else
  1354. char pathSep = ':';
  1355. #endif
  1356. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1357. std::string value = cmJoin(
  1358. cmMakeRange(path).transform(nativePath ? ToNativePath : ToCMakePath), ";");
  1359. this->Makefile->AddDefinition(args[2], value.c_str());
  1360. return true;
  1361. }
  1362. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1363. // Stuff for curl download/upload
  1364. typedef std::vector<char> cmFileCommandVectorOfChar;
  1365. namespace {
  1366. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1367. {
  1368. int realsize = static_cast<int>(size * nmemb);
  1369. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1370. const char* chPtr = static_cast<char*>(ptr);
  1371. fout->write(chPtr, realsize);
  1372. return realsize;
  1373. }
  1374. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1375. void* data)
  1376. {
  1377. int realsize = static_cast<int>(size * nmemb);
  1378. cmFileCommandVectorOfChar* vec =
  1379. static_cast<cmFileCommandVectorOfChar*>(data);
  1380. const char* chPtr = static_cast<char*>(ptr);
  1381. vec->insert(vec->end(), chPtr, chPtr + realsize);
  1382. return realsize;
  1383. }
  1384. size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1385. size_t size, void* data)
  1386. {
  1387. cmFileCommandVectorOfChar* vec =
  1388. static_cast<cmFileCommandVectorOfChar*>(data);
  1389. switch (type) {
  1390. case CURLINFO_TEXT:
  1391. case CURLINFO_HEADER_IN:
  1392. case CURLINFO_HEADER_OUT:
  1393. vec->insert(vec->end(), chPtr, chPtr + size);
  1394. break;
  1395. case CURLINFO_DATA_IN:
  1396. case CURLINFO_DATA_OUT:
  1397. case CURLINFO_SSL_DATA_IN:
  1398. case CURLINFO_SSL_DATA_OUT: {
  1399. char buf[128];
  1400. int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1401. static_cast<KWIML_INT_uint64_t>(size));
  1402. if (n > 0) {
  1403. vec->insert(vec->end(), buf, buf + n);
  1404. }
  1405. } break;
  1406. default:
  1407. break;
  1408. }
  1409. return 0;
  1410. }
  1411. class cURLProgressHelper
  1412. {
  1413. public:
  1414. cURLProgressHelper(cmFileCommand* fc, const char* text)
  1415. {
  1416. this->CurrentPercentage = -1;
  1417. this->FileCommand = fc;
  1418. this->Text = text;
  1419. }
  1420. bool UpdatePercentage(double value, double total, std::string& status)
  1421. {
  1422. long OldPercentage = this->CurrentPercentage;
  1423. if (total > 0.0) {
  1424. this->CurrentPercentage = std::lround(value / total * 100.0);
  1425. if (this->CurrentPercentage > 100) {
  1426. // Avoid extra progress reports for unexpected data beyond total.
  1427. this->CurrentPercentage = 100;
  1428. }
  1429. }
  1430. bool updated = (OldPercentage != this->CurrentPercentage);
  1431. if (updated) {
  1432. std::ostringstream oss;
  1433. oss << "[" << this->Text << " " << this->CurrentPercentage
  1434. << "% complete]";
  1435. status = oss.str();
  1436. }
  1437. return updated;
  1438. }
  1439. cmFileCommand* GetFileCommand() { return this->FileCommand; }
  1440. private:
  1441. long CurrentPercentage;
  1442. cmFileCommand* FileCommand;
  1443. std::string Text;
  1444. };
  1445. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1446. double ultotal, double ulnow)
  1447. {
  1448. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1449. static_cast<void>(ultotal);
  1450. static_cast<void>(ulnow);
  1451. std::string status;
  1452. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1453. cmFileCommand* fc = helper->GetFileCommand();
  1454. cmMakefile* mf = fc->GetMakefile();
  1455. mf->DisplayStatus(status, -1);
  1456. }
  1457. return 0;
  1458. }
  1459. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1460. double ultotal, double ulnow)
  1461. {
  1462. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1463. static_cast<void>(dltotal);
  1464. static_cast<void>(dlnow);
  1465. std::string status;
  1466. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1467. cmFileCommand* fc = helper->GetFileCommand();
  1468. cmMakefile* mf = fc->GetMakefile();
  1469. mf->DisplayStatus(status, -1);
  1470. }
  1471. return 0;
  1472. }
  1473. }
  1474. namespace {
  1475. class cURLEasyGuard
  1476. {
  1477. public:
  1478. cURLEasyGuard(CURL* easy)
  1479. : Easy(easy)
  1480. {
  1481. }
  1482. ~cURLEasyGuard()
  1483. {
  1484. if (this->Easy) {
  1485. ::curl_easy_cleanup(this->Easy);
  1486. }
  1487. }
  1488. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1489. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1490. void release() { this->Easy = nullptr; }
  1491. private:
  1492. ::CURL* Easy;
  1493. };
  1494. }
  1495. #endif
  1496. #define check_curl_result(result, errstr) \
  1497. do { \
  1498. if (result != CURLE_OK) { \
  1499. std::string e(errstr); \
  1500. e += ::curl_easy_strerror(result); \
  1501. this->SetError(e); \
  1502. return false; \
  1503. } \
  1504. } while (false)
  1505. bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
  1506. {
  1507. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1508. std::vector<std::string>::const_iterator i = args.begin();
  1509. if (args.size() < 3) {
  1510. this->SetError("DOWNLOAD must be called with at least three arguments.");
  1511. return false;
  1512. }
  1513. ++i; // Get rid of subcommand
  1514. std::string url = *i;
  1515. ++i;
  1516. std::string file = *i;
  1517. ++i;
  1518. long timeout = 0;
  1519. long inactivity_timeout = 0;
  1520. std::string logVar;
  1521. std::string statusVar;
  1522. bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
  1523. const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
  1524. std::string netrc_level = this->Makefile->GetSafeDefinition("CMAKE_NETRC");
  1525. std::string netrc_file =
  1526. this->Makefile->GetSafeDefinition("CMAKE_NETRC_FILE");
  1527. std::string expectedHash;
  1528. std::string hashMatchMSG;
  1529. std::unique_ptr<cmCryptoHash> hash;
  1530. bool showProgress = false;
  1531. std::string userpwd;
  1532. std::vector<std::string> curl_headers;
  1533. while (i != args.end()) {
  1534. if (*i == "TIMEOUT") {
  1535. ++i;
  1536. if (i != args.end()) {
  1537. timeout = atol(i->c_str());
  1538. } else {
  1539. this->SetError("DOWNLOAD missing time for TIMEOUT.");
  1540. return false;
  1541. }
  1542. } else if (*i == "INACTIVITY_TIMEOUT") {
  1543. ++i;
  1544. if (i != args.end()) {
  1545. inactivity_timeout = atol(i->c_str());
  1546. } else {
  1547. this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1548. return false;
  1549. }
  1550. } else if (*i == "LOG") {
  1551. ++i;
  1552. if (i == args.end()) {
  1553. this->SetError("DOWNLOAD missing VAR for LOG.");
  1554. return false;
  1555. }
  1556. logVar = *i;
  1557. } else if (*i == "STATUS") {
  1558. ++i;
  1559. if (i == args.end()) {
  1560. this->SetError("DOWNLOAD missing VAR for STATUS.");
  1561. return false;
  1562. }
  1563. statusVar = *i;
  1564. } else if (*i == "TLS_VERIFY") {
  1565. ++i;
  1566. if (i != args.end()) {
  1567. tls_verify = cmSystemTools::IsOn(*i);
  1568. } else {
  1569. this->SetError("TLS_VERIFY missing bool value.");
  1570. return false;
  1571. }
  1572. } else if (*i == "TLS_CAINFO") {
  1573. ++i;
  1574. if (i != args.end()) {
  1575. cainfo = i->c_str();
  1576. } else {
  1577. this->SetError("TLS_CAFILE missing file value.");
  1578. return false;
  1579. }
  1580. } else if (*i == "NETRC_FILE") {
  1581. ++i;
  1582. if (i != args.end()) {
  1583. netrc_file = *i;
  1584. } else {
  1585. this->SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1586. return false;
  1587. }
  1588. } else if (*i == "NETRC") {
  1589. ++i;
  1590. if (i != args.end()) {
  1591. netrc_level = *i;
  1592. } else {
  1593. this->SetError("DOWNLOAD missing level value for NETRC.");
  1594. return false;
  1595. }
  1596. } else if (*i == "EXPECTED_MD5") {
  1597. ++i;
  1598. if (i == args.end()) {
  1599. this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1600. return false;
  1601. }
  1602. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1603. hashMatchMSG = "MD5 sum";
  1604. expectedHash = cmSystemTools::LowerCase(*i);
  1605. } else if (*i == "SHOW_PROGRESS") {
  1606. showProgress = true;
  1607. } else if (*i == "EXPECTED_HASH") {
  1608. ++i;
  1609. if (i == args.end()) {
  1610. this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1611. return false;
  1612. }
  1613. std::string::size_type pos = i->find("=");
  1614. if (pos == std::string::npos) {
  1615. std::string err =
  1616. "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
  1617. err += *i;
  1618. this->SetError(err);
  1619. return false;
  1620. }
  1621. std::string algo = i->substr(0, pos);
  1622. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1623. hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
  1624. if (!hash) {
  1625. std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
  1626. err += algo;
  1627. this->SetError(err);
  1628. return false;
  1629. }
  1630. hashMatchMSG = algo + " hash";
  1631. } else if (*i == "USERPWD") {
  1632. ++i;
  1633. if (i == args.end()) {
  1634. this->SetError("DOWNLOAD missing string for USERPWD.");
  1635. return false;
  1636. }
  1637. userpwd = *i;
  1638. } else if (*i == "HTTPHEADER") {
  1639. ++i;
  1640. if (i == args.end()) {
  1641. this->SetError("DOWNLOAD missing string for HTTPHEADER.");
  1642. return false;
  1643. }
  1644. curl_headers.push_back(*i);
  1645. } else {
  1646. // Do not return error for compatibility reason.
  1647. std::string err = "Unexpected argument: ";
  1648. err += *i;
  1649. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, err);
  1650. }
  1651. ++i;
  1652. }
  1653. // If file exists already, and caller specified an expected md5 or sha,
  1654. // and the existing file already has the expected hash, then simply
  1655. // return.
  1656. //
  1657. if (cmSystemTools::FileExists(file) && hash.get()) {
  1658. std::string msg;
  1659. std::string actualHash = hash->HashFile(file);
  1660. if (actualHash == expectedHash) {
  1661. msg = "returning early; file already exists with expected ";
  1662. msg += hashMatchMSG;
  1663. msg += "\"";
  1664. if (!statusVar.empty()) {
  1665. std::ostringstream result;
  1666. result << 0 << ";\"" << msg;
  1667. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  1668. }
  1669. return true;
  1670. }
  1671. }
  1672. // Make sure parent directory exists so we can write to the file
  1673. // as we receive downloaded bits from curl...
  1674. //
  1675. std::string dir = cmSystemTools::GetFilenamePath(file);
  1676. if (!cmSystemTools::FileExists(dir) && !cmSystemTools::MakeDirectory(dir)) {
  1677. std::string errstring = "DOWNLOAD error: cannot create directory '" + dir +
  1678. "' - Specify file by full path name and verify that you "
  1679. "have directory creation and file write privileges.";
  1680. this->SetError(errstring);
  1681. return false;
  1682. }
  1683. cmsys::ofstream fout(file.c_str(), std::ios::binary);
  1684. if (!fout) {
  1685. this->SetError("DOWNLOAD cannot open file for write.");
  1686. return false;
  1687. }
  1688. # if defined(_WIN32)
  1689. url = fix_file_url_windows(url);
  1690. # endif
  1691. ::CURL* curl;
  1692. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1693. curl = ::curl_easy_init();
  1694. if (!curl) {
  1695. this->SetError("DOWNLOAD error initializing curl.");
  1696. return false;
  1697. }
  1698. cURLEasyGuard g_curl(curl);
  1699. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1700. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1701. // enable HTTP ERROR parsing
  1702. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1703. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1704. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1705. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1706. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1707. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1708. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1709. cmFileCommandCurlDebugCallback);
  1710. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1711. // check to see if TLS verification is requested
  1712. if (tls_verify) {
  1713. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1714. check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
  1715. } else {
  1716. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1717. check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
  1718. }
  1719. // check to see if a CAINFO file has been specified
  1720. // command arg comes first
  1721. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  1722. if (!cainfo_err.empty()) {
  1723. this->SetError(cainfo_err);
  1724. return false;
  1725. }
  1726. // check to see if netrc parameters have been specified
  1727. // local command args takes precedence over CMAKE_NETRC*
  1728. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1729. std::string const& netrc_option_err =
  1730. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1731. if (!netrc_option_err.empty()) {
  1732. this->SetError(netrc_option_err);
  1733. return false;
  1734. }
  1735. cmFileCommandVectorOfChar chunkDebug;
  1736. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fout);
  1737. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1738. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1739. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1740. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1741. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1742. if (!logVar.empty()) {
  1743. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1744. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1745. }
  1746. if (timeout > 0) {
  1747. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1748. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1749. }
  1750. if (inactivity_timeout > 0) {
  1751. // Give up if there is no progress for a long time.
  1752. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1753. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1754. }
  1755. // Need the progress helper's scope to last through the duration of
  1756. // the curl_easy_perform call... so this object is declared at function
  1757. // scope intentionally, rather than inside the "if(showProgress)"
  1758. // block...
  1759. //
  1760. cURLProgressHelper helper(this, "download");
  1761. if (showProgress) {
  1762. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1763. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1764. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1765. cmFileDownloadProgressCallback);
  1766. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1767. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1768. reinterpret_cast<void*>(&helper));
  1769. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1770. }
  1771. if (!userpwd.empty()) {
  1772. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1773. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1774. }
  1775. struct curl_slist* headers = nullptr;
  1776. for (std::string const& h : curl_headers) {
  1777. headers = ::curl_slist_append(headers, h.c_str());
  1778. }
  1779. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1780. res = ::curl_easy_perform(curl);
  1781. ::curl_slist_free_all(headers);
  1782. /* always cleanup */
  1783. g_curl.release();
  1784. ::curl_easy_cleanup(curl);
  1785. if (!statusVar.empty()) {
  1786. std::ostringstream result;
  1787. result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
  1788. << "\"";
  1789. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  1790. }
  1791. ::curl_global_cleanup();
  1792. // Explicitly flush/close so we can measure the md5 accurately.
  1793. //
  1794. fout.flush();
  1795. fout.close();
  1796. // Verify MD5 sum if requested:
  1797. //
  1798. if (hash) {
  1799. std::string actualHash = hash->HashFile(file);
  1800. if (actualHash.empty()) {
  1801. this->SetError("DOWNLOAD cannot compute hash on downloaded file");
  1802. return false;
  1803. }
  1804. if (expectedHash != actualHash) {
  1805. std::ostringstream oss;
  1806. oss << "DOWNLOAD HASH mismatch" << std::endl
  1807. << " for file: [" << file << "]" << std::endl
  1808. << " expected hash: [" << expectedHash << "]" << std::endl
  1809. << " actual hash: [" << actualHash << "]" << std::endl
  1810. << " status: [" << static_cast<int>(res) << ";\""
  1811. << ::curl_easy_strerror(res) << "\"]" << std::endl;
  1812. if (!statusVar.empty() && res == 0) {
  1813. std::string status = "1;HASH mismatch: "
  1814. "expected: " +
  1815. expectedHash + " actual: " + actualHash;
  1816. this->Makefile->AddDefinition(statusVar, status.c_str());
  1817. }
  1818. this->SetError(oss.str());
  1819. return false;
  1820. }
  1821. }
  1822. if (!logVar.empty()) {
  1823. chunkDebug.push_back(0);
  1824. this->Makefile->AddDefinition(logVar, chunkDebug.data());
  1825. }
  1826. return true;
  1827. #else
  1828. this->SetError("DOWNLOAD not supported by bootstrap cmake.");
  1829. return false;
  1830. #endif
  1831. }
  1832. bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
  1833. {
  1834. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1835. if (args.size() < 3) {
  1836. this->SetError("UPLOAD must be called with at least three arguments.");
  1837. return false;
  1838. }
  1839. std::vector<std::string>::const_iterator i = args.begin();
  1840. ++i;
  1841. std::string filename = *i;
  1842. ++i;
  1843. std::string url = *i;
  1844. ++i;
  1845. long timeout = 0;
  1846. long inactivity_timeout = 0;
  1847. std::string logVar;
  1848. std::string statusVar;
  1849. bool showProgress = false;
  1850. std::string userpwd;
  1851. std::string netrc_level = this->Makefile->GetSafeDefinition("CMAKE_NETRC");
  1852. std::string netrc_file =
  1853. this->Makefile->GetSafeDefinition("CMAKE_NETRC_FILE");
  1854. std::vector<std::string> curl_headers;
  1855. while (i != args.end()) {
  1856. if (*i == "TIMEOUT") {
  1857. ++i;
  1858. if (i != args.end()) {
  1859. timeout = atol(i->c_str());
  1860. } else {
  1861. this->SetError("UPLOAD missing time for TIMEOUT.");
  1862. return false;
  1863. }
  1864. } else if (*i == "INACTIVITY_TIMEOUT") {
  1865. ++i;
  1866. if (i != args.end()) {
  1867. inactivity_timeout = atol(i->c_str());
  1868. } else {
  1869. this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1870. return false;
  1871. }
  1872. } else if (*i == "LOG") {
  1873. ++i;
  1874. if (i == args.end()) {
  1875. this->SetError("UPLOAD missing VAR for LOG.");
  1876. return false;
  1877. }
  1878. logVar = *i;
  1879. } else if (*i == "STATUS") {
  1880. ++i;
  1881. if (i == args.end()) {
  1882. this->SetError("UPLOAD missing VAR for STATUS.");
  1883. return false;
  1884. }
  1885. statusVar = *i;
  1886. } else if (*i == "SHOW_PROGRESS") {
  1887. showProgress = true;
  1888. } else if (*i == "NETRC_FILE") {
  1889. ++i;
  1890. if (i != args.end()) {
  1891. netrc_file = *i;
  1892. } else {
  1893. this->SetError("UPLOAD missing file value for NETRC_FILE.");
  1894. return false;
  1895. }
  1896. } else if (*i == "NETRC") {
  1897. ++i;
  1898. if (i != args.end()) {
  1899. netrc_level = *i;
  1900. } else {
  1901. this->SetError("UPLOAD missing level value for NETRC.");
  1902. return false;
  1903. }
  1904. } else if (*i == "USERPWD") {
  1905. ++i;
  1906. if (i == args.end()) {
  1907. this->SetError("UPLOAD missing string for USERPWD.");
  1908. return false;
  1909. }
  1910. userpwd = *i;
  1911. } else if (*i == "HTTPHEADER") {
  1912. ++i;
  1913. if (i == args.end()) {
  1914. this->SetError("UPLOAD missing string for HTTPHEADER.");
  1915. return false;
  1916. }
  1917. curl_headers.push_back(*i);
  1918. } else {
  1919. // Do not return error for compatibility reason.
  1920. std::string err = "Unexpected argument: ";
  1921. err += *i;
  1922. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, err);
  1923. }
  1924. ++i;
  1925. }
  1926. // Open file for reading:
  1927. //
  1928. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  1929. if (!fin) {
  1930. std::string errStr = "UPLOAD cannot open file '";
  1931. errStr += filename + "' for reading.";
  1932. this->SetError(errStr);
  1933. return false;
  1934. }
  1935. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  1936. # if defined(_WIN32)
  1937. url = fix_file_url_windows(url);
  1938. # endif
  1939. ::CURL* curl;
  1940. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1941. curl = ::curl_easy_init();
  1942. if (!curl) {
  1943. this->SetError("UPLOAD error initializing curl.");
  1944. fclose(fin);
  1945. return false;
  1946. }
  1947. cURLEasyGuard g_curl(curl);
  1948. // enable HTTP ERROR parsing
  1949. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1950. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  1951. // enable uploading
  1952. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  1953. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  1954. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1955. check_curl_result(res, "UPLOAD cannot set url: ");
  1956. res =
  1957. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  1958. check_curl_result(res, "UPLOAD cannot set write function: ");
  1959. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1960. cmFileCommandCurlDebugCallback);
  1961. check_curl_result(res, "UPLOAD cannot set debug function: ");
  1962. cmFileCommandVectorOfChar chunkResponse;
  1963. cmFileCommandVectorOfChar chunkDebug;
  1964. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  1965. check_curl_result(res, "UPLOAD cannot set write data: ");
  1966. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1967. check_curl_result(res, "UPLOAD cannot set debug data: ");
  1968. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1969. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  1970. if (!logVar.empty()) {
  1971. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1972. check_curl_result(res, "UPLOAD cannot set verbose: ");
  1973. }
  1974. if (timeout > 0) {
  1975. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1976. check_curl_result(res, "UPLOAD cannot set timeout: ");
  1977. }
  1978. if (inactivity_timeout > 0) {
  1979. // Give up if there is no progress for a long time.
  1980. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1981. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1982. }
  1983. // Need the progress helper's scope to last through the duration of
  1984. // the curl_easy_perform call... so this object is declared at function
  1985. // scope intentionally, rather than inside the "if(showProgress)"
  1986. // block...
  1987. //
  1988. cURLProgressHelper helper(this, "upload");
  1989. if (showProgress) {
  1990. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1991. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  1992. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1993. cmFileUploadProgressCallback);
  1994. check_curl_result(res, "UPLOAD cannot set progress function: ");
  1995. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1996. reinterpret_cast<void*>(&helper));
  1997. check_curl_result(res, "UPLOAD cannot set progress data: ");
  1998. }
  1999. // now specify which file to upload
  2000. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2001. check_curl_result(res, "UPLOAD cannot set input file: ");
  2002. // and give the size of the upload (optional)
  2003. res =
  2004. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2005. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2006. if (!userpwd.empty()) {
  2007. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2008. check_curl_result(res, "UPLOAD cannot set user password: ");
  2009. }
  2010. // check to see if netrc parameters have been specified
  2011. // local command args takes precedence over CMAKE_NETRC*
  2012. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2013. std::string const& netrc_option_err =
  2014. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2015. if (!netrc_option_err.empty()) {
  2016. this->SetError(netrc_option_err);
  2017. return false;
  2018. }
  2019. struct curl_slist* headers = nullptr;
  2020. for (std::string const& h : curl_headers) {
  2021. headers = ::curl_slist_append(headers, h.c_str());
  2022. }
  2023. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2024. res = ::curl_easy_perform(curl);
  2025. ::curl_slist_free_all(headers);
  2026. /* always cleanup */
  2027. g_curl.release();
  2028. ::curl_easy_cleanup(curl);
  2029. if (!statusVar.empty()) {
  2030. std::ostringstream result;
  2031. result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
  2032. << "\"";
  2033. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  2034. }
  2035. ::curl_global_cleanup();
  2036. fclose(fin);
  2037. fin = nullptr;
  2038. if (!logVar.empty()) {
  2039. std::string log;
  2040. if (!chunkResponse.empty()) {
  2041. chunkResponse.push_back(0);
  2042. log += "Response:\n";
  2043. log += chunkResponse.data();
  2044. log += "\n";
  2045. }
  2046. if (!chunkDebug.empty()) {
  2047. chunkDebug.push_back(0);
  2048. log += "Debug:\n";
  2049. log += chunkDebug.data();
  2050. log += "\n";
  2051. }
  2052. this->Makefile->AddDefinition(logVar, log.c_str());
  2053. }
  2054. return true;
  2055. #else
  2056. this->SetError("UPLOAD not supported by bootstrap cmake.");
  2057. return false;
  2058. #endif
  2059. }
  2060. void cmFileCommand::AddEvaluationFile(const std::string& inputName,
  2061. const std::string& outputExpr,
  2062. const std::string& condition,
  2063. bool inputIsContent)
  2064. {
  2065. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2066. cmGeneratorExpression outputGe(lfbt);
  2067. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2068. outputGe.Parse(outputExpr);
  2069. cmGeneratorExpression conditionGe(lfbt);
  2070. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2071. conditionGe.Parse(condition);
  2072. this->Makefile->AddEvaluationFile(inputName, std::move(outputCge),
  2073. std::move(conditionCge), inputIsContent);
  2074. }
  2075. bool cmFileCommand::HandleGenerateCommand(std::vector<std::string> const& args)
  2076. {
  2077. if (args.size() < 5) {
  2078. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2079. return false;
  2080. }
  2081. if (args[1] != "OUTPUT") {
  2082. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2083. return false;
  2084. }
  2085. std::string condition;
  2086. if (args.size() > 5) {
  2087. if (args[5] != "CONDITION") {
  2088. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2089. return false;
  2090. }
  2091. if (args.size() != 7) {
  2092. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2093. return false;
  2094. }
  2095. condition = args[6];
  2096. if (condition.empty()) {
  2097. this->SetError("CONDITION of sub-command GENERATE must not be empty if "
  2098. "specified.");
  2099. return false;
  2100. }
  2101. }
  2102. std::string output = args[2];
  2103. const bool inputIsContent = args[3] != "INPUT";
  2104. if (inputIsContent && args[3] != "CONTENT") {
  2105. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2106. return false;
  2107. }
  2108. std::string input = args[4];
  2109. this->AddEvaluationFile(input, output, condition, inputIsContent);
  2110. return true;
  2111. }
  2112. bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args)
  2113. {
  2114. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2115. // Default values
  2116. bool directory = false;
  2117. bool release = false;
  2118. enum Guard
  2119. {
  2120. GUARD_FUNCTION,
  2121. GUARD_FILE,
  2122. GUARD_PROCESS
  2123. };
  2124. Guard guard = GUARD_PROCESS;
  2125. std::string resultVariable;
  2126. unsigned long timeout = static_cast<unsigned long>(-1);
  2127. // Parse arguments
  2128. if (args.size() < 2) {
  2129. this->Makefile->IssueMessage(
  2130. MessageType::FATAL_ERROR,
  2131. "sub-command LOCK requires at least two arguments.");
  2132. return false;
  2133. }
  2134. std::string path = args[1];
  2135. for (unsigned i = 2; i < args.size(); ++i) {
  2136. if (args[i] == "DIRECTORY") {
  2137. directory = true;
  2138. } else if (args[i] == "RELEASE") {
  2139. release = true;
  2140. } else if (args[i] == "GUARD") {
  2141. ++i;
  2142. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2143. if (i >= args.size()) {
  2144. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, merr);
  2145. return false;
  2146. }
  2147. if (args[i] == "FUNCTION") {
  2148. guard = GUARD_FUNCTION;
  2149. } else if (args[i] == "FILE") {
  2150. guard = GUARD_FILE;
  2151. } else if (args[i] == "PROCESS") {
  2152. guard = GUARD_PROCESS;
  2153. } else {
  2154. std::ostringstream e;
  2155. e << merr << ", but got:\n \"" << args[i] << "\".";
  2156. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2157. return false;
  2158. }
  2159. } else if (args[i] == "RESULT_VARIABLE") {
  2160. ++i;
  2161. if (i >= args.size()) {
  2162. this->Makefile->IssueMessage(
  2163. MessageType::FATAL_ERROR,
  2164. "expected variable name after RESULT_VARIABLE");
  2165. return false;
  2166. }
  2167. resultVariable = args[i];
  2168. } else if (args[i] == "TIMEOUT") {
  2169. ++i;
  2170. if (i >= args.size()) {
  2171. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  2172. "expected timeout value after TIMEOUT");
  2173. return false;
  2174. }
  2175. long scanned;
  2176. if (!cmSystemTools::StringToLong(args[i].c_str(), &scanned) ||
  2177. scanned < 0) {
  2178. std::ostringstream e;
  2179. e << "TIMEOUT value \"" << args[i] << "\" is not an unsigned integer.";
  2180. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2181. return false;
  2182. }
  2183. timeout = static_cast<unsigned long>(scanned);
  2184. } else {
  2185. std::ostringstream e;
  2186. e << "expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or TIMEOUT\n";
  2187. e << "but got: \"" << args[i] << "\".";
  2188. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2189. return false;
  2190. }
  2191. }
  2192. if (directory) {
  2193. path += "/cmake.lock";
  2194. }
  2195. if (!cmsys::SystemTools::FileIsFullPath(path)) {
  2196. path = this->Makefile->GetCurrentSourceDirectory() + "/" + path;
  2197. }
  2198. // Unify path (remove '//', '/../', ...)
  2199. path = cmSystemTools::CollapseFullPath(path);
  2200. // Create file and directories if needed
  2201. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2202. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2203. std::ostringstream e;
  2204. e << "directory\n \"" << parentDir << "\"\ncreation failed ";
  2205. e << "(check permissions).";
  2206. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2207. cmSystemTools::SetFatalErrorOccured();
  2208. return false;
  2209. }
  2210. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2211. if (!file) {
  2212. std::ostringstream e;
  2213. e << "file\n \"" << path << "\"\ncreation failed (check permissions).";
  2214. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2215. cmSystemTools::SetFatalErrorOccured();
  2216. return false;
  2217. }
  2218. fclose(file);
  2219. // Actual lock/unlock
  2220. cmFileLockPool& lockPool =
  2221. this->Makefile->GetGlobalGenerator()->GetFileLockPool();
  2222. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2223. if (release) {
  2224. fileLockResult = lockPool.Release(path);
  2225. } else {
  2226. switch (guard) {
  2227. case GUARD_FUNCTION:
  2228. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2229. break;
  2230. case GUARD_FILE:
  2231. fileLockResult = lockPool.LockFileScope(path, timeout);
  2232. break;
  2233. case GUARD_PROCESS:
  2234. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2235. break;
  2236. default:
  2237. cmSystemTools::SetFatalErrorOccured();
  2238. return false;
  2239. }
  2240. }
  2241. const std::string result = fileLockResult.GetOutputMessage();
  2242. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2243. std::ostringstream e;
  2244. e << "error locking file\n \"" << path << "\"\n" << result << ".";
  2245. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2246. cmSystemTools::SetFatalErrorOccured();
  2247. return false;
  2248. }
  2249. if (!resultVariable.empty()) {
  2250. this->Makefile->AddDefinition(resultVariable, result.c_str());
  2251. }
  2252. return true;
  2253. #else
  2254. static_cast<void>(args);
  2255. this->SetError("sub-command LOCK not implemented in bootstrap cmake");
  2256. return false;
  2257. #endif
  2258. }
  2259. bool cmFileCommand::HandleTimestampCommand(
  2260. std::vector<std::string> const& args)
  2261. {
  2262. if (args.size() < 3) {
  2263. this->SetError("sub-command TIMESTAMP requires at least two arguments.");
  2264. return false;
  2265. }
  2266. if (args.size() > 5) {
  2267. this->SetError("sub-command TIMESTAMP takes at most four arguments.");
  2268. return false;
  2269. }
  2270. unsigned int argsIndex = 1;
  2271. const std::string& filename = args[argsIndex++];
  2272. const std::string& outputVariable = args[argsIndex++];
  2273. std::string formatString;
  2274. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2275. formatString = args[argsIndex++];
  2276. }
  2277. bool utcFlag = false;
  2278. if (args.size() > argsIndex) {
  2279. if (args[argsIndex] == "UTC") {
  2280. utcFlag = true;
  2281. } else {
  2282. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2283. args[argsIndex] + ".";
  2284. this->SetError(e);
  2285. return false;
  2286. }
  2287. }
  2288. cmTimestamp timestamp;
  2289. std::string result =
  2290. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2291. this->Makefile->AddDefinition(outputVariable, result.c_str());
  2292. return true;
  2293. }
  2294. bool cmFileCommand::HandleSizeCommand(std::vector<std::string> const& args)
  2295. {
  2296. if (args.size() != 3) {
  2297. std::ostringstream e;
  2298. e << args[0] << " requires a file name and output variable";
  2299. this->SetError(e.str());
  2300. return false;
  2301. }
  2302. unsigned int argsIndex = 1;
  2303. const std::string& filename = args[argsIndex++];
  2304. const std::string& outputVariable = args[argsIndex++];
  2305. if (!cmSystemTools::FileExists(filename, true)) {
  2306. std::ostringstream e;
  2307. e << "SIZE requested of path that is not readable:\n " << filename;
  2308. this->SetError(e.str());
  2309. return false;
  2310. }
  2311. this->Makefile->AddDefinition(
  2312. outputVariable,
  2313. std::to_string(cmSystemTools::FileLength(filename)).c_str());
  2314. return true;
  2315. }
  2316. bool cmFileCommand::HandleReadSymlinkCommand(
  2317. std::vector<std::string> const& args)
  2318. {
  2319. if (args.size() != 3) {
  2320. std::ostringstream e;
  2321. e << args[0] << " requires a file name and output variable";
  2322. this->SetError(e.str());
  2323. return false;
  2324. }
  2325. const std::string& filename = args[1];
  2326. const std::string& outputVariable = args[2];
  2327. std::string result;
  2328. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2329. std::ostringstream e;
  2330. e << "READ_SYMLINK requested of path that is not a symlink:\n "
  2331. << filename;
  2332. this->SetError(e.str());
  2333. return false;
  2334. }
  2335. this->Makefile->AddDefinition(outputVariable, result.c_str());
  2336. return true;
  2337. }
  2338. bool cmFileCommand::HandleCreateLinkCommand(
  2339. std::vector<std::string> const& args)
  2340. {
  2341. if (args.size() < 3) {
  2342. this->SetError("CREATE_LINK must be called with at least two additional "
  2343. "arguments");
  2344. return false;
  2345. }
  2346. std::string const& fileName = args[1];
  2347. std::string const& newFileName = args[2];
  2348. struct Arguments
  2349. {
  2350. std::string Result;
  2351. bool CopyOnError = false;
  2352. bool Symbolic = false;
  2353. };
  2354. static auto const parser =
  2355. cmArgumentParser<Arguments>{}
  2356. .Bind("RESULT"_s, &Arguments::Result)
  2357. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2358. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2359. std::vector<std::string> unconsumedArgs;
  2360. Arguments const arguments =
  2361. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2362. if (!unconsumedArgs.empty()) {
  2363. this->SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2364. return false;
  2365. }
  2366. // The system error message generated in the operation.
  2367. std::string result;
  2368. // Check if the paths are distinct.
  2369. if (fileName == newFileName) {
  2370. result = "CREATE_LINK cannot use same file and newfile";
  2371. if (!arguments.Result.empty()) {
  2372. this->Makefile->AddDefinition(arguments.Result, result.c_str());
  2373. return true;
  2374. }
  2375. this->SetError(result);
  2376. return false;
  2377. }
  2378. // Hard link requires original file to exist.
  2379. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2380. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2381. if (!arguments.Result.empty()) {
  2382. this->Makefile->AddDefinition(arguments.Result, result.c_str());
  2383. return true;
  2384. }
  2385. this->SetError(result);
  2386. return false;
  2387. }
  2388. // Check if the new file already exists and remove it.
  2389. if ((cmSystemTools::FileExists(newFileName) ||
  2390. cmSystemTools::FileIsSymlink(newFileName)) &&
  2391. !cmSystemTools::RemoveFile(newFileName)) {
  2392. std::ostringstream e;
  2393. e << "Failed to create link '" << newFileName
  2394. << "' because existing path cannot be removed: "
  2395. << cmSystemTools::GetLastSystemError() << "\n";
  2396. if (!arguments.Result.empty()) {
  2397. this->Makefile->AddDefinition(arguments.Result, e.str().c_str());
  2398. return true;
  2399. }
  2400. this->SetError(e.str());
  2401. return false;
  2402. }
  2403. // Whether the operation completed successfully.
  2404. bool completed = false;
  2405. // Check if the command requires a symbolic link.
  2406. if (arguments.Symbolic) {
  2407. completed = cmSystemTools::CreateSymlink(fileName, newFileName, &result);
  2408. } else {
  2409. completed = cmSystemTools::CreateLink(fileName, newFileName, &result);
  2410. }
  2411. // Check if copy-on-error is enabled in the arguments.
  2412. if (!completed && arguments.CopyOnError) {
  2413. completed = cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2414. if (!completed) {
  2415. result = "Copy failed: " + cmSystemTools::GetLastSystemError();
  2416. }
  2417. }
  2418. // Check if the operation was successful.
  2419. if (completed) {
  2420. result = "0";
  2421. } else if (arguments.Result.empty()) {
  2422. // The operation failed and the result is not reported in a variable.
  2423. this->SetError(result);
  2424. return false;
  2425. }
  2426. if (!arguments.Result.empty()) {
  2427. this->Makefile->AddDefinition(arguments.Result, result.c_str());
  2428. }
  2429. return true;
  2430. }