cmFileCommand.cxx 84 KB

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