cmFileCommand.cxx 111 KB

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