cmFileCommand.cxx 106 KB

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