cmFileCommand.cxx 100 KB

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