cmFileCommand.cxx 111 KB

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