cmFileCommand.cxx 105 KB

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