cmFileCommand.cxx 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455
  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 <sstream>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <vector>
  17. #include "cmAlgorithms.h"
  18. #include "cmCommandArgumentsHelper.h"
  19. #include "cmCryptoHash.h"
  20. #include "cmFileLockPool.h"
  21. #include "cmFileTimeComparison.h"
  22. #include "cmGeneratorExpression.h"
  23. #include "cmGlobalGenerator.h"
  24. #include "cmHexFileConverter.h"
  25. #include "cmInstallType.h"
  26. #include "cmListFileCache.h"
  27. #include "cmMakefile.h"
  28. #include "cmPolicies.h"
  29. #include "cmSystemTools.h"
  30. #include "cmTimestamp.h"
  31. #include "cm_auto_ptr.hxx"
  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. CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
  340. if (hash.get()) {
  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 = "";
  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 = "";
  623. break;
  624. }
  625. strings.push_back(s);
  626. }
  627. // Reset the string to empty.
  628. s = "";
  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 = "";
  638. break;
  639. }
  640. strings.push_back(s);
  641. }
  642. // Reset the string to empty.
  643. s = "";
  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 = "";
  653. break;
  654. }
  655. strings.push_back(s);
  656. }
  657. s = "";
  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::vector<std::string>::const_iterator si = strings.begin();
  674. si != strings.end(); ++si) {
  675. // Separate the strings in the output to make it a list.
  676. output += sep;
  677. sep = ";";
  678. // Store the string in the output, but escape semicolons to
  679. // make sure it is a list.
  680. std::string const& sr = *si;
  681. for (unsigned int i = 0; i < sr.size(); ++i) {
  682. if (sr[i] == ';') {
  683. output += '\\';
  684. }
  685. output += sr[i];
  686. }
  687. }
  688. // Save the output in a makefile variable.
  689. this->Makefile->AddDefinition(outVar, output.c_str());
  690. return true;
  691. }
  692. bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
  693. bool recurse)
  694. {
  695. // File commands has at least one argument
  696. assert(args.size() > 1);
  697. std::vector<std::string>::const_iterator i = args.begin();
  698. i++; // Get rid of subcommand
  699. std::string variable = *i;
  700. i++;
  701. cmsys::Glob g;
  702. g.SetRecurse(recurse);
  703. bool explicitFollowSymlinks = false;
  704. cmPolicies::PolicyStatus status =
  705. this->Makefile->GetPolicyStatus(cmPolicies::CMP0009);
  706. if (recurse) {
  707. switch (status) {
  708. case cmPolicies::REQUIRED_IF_USED:
  709. case cmPolicies::REQUIRED_ALWAYS:
  710. case cmPolicies::NEW:
  711. g.RecurseThroughSymlinksOff();
  712. break;
  713. case cmPolicies::OLD:
  714. case cmPolicies::WARN:
  715. g.RecurseThroughSymlinksOn();
  716. break;
  717. }
  718. }
  719. std::string output;
  720. bool first = true;
  721. for (; i != args.end(); ++i) {
  722. if (*i == "LIST_DIRECTORIES") {
  723. ++i;
  724. if (i != args.end()) {
  725. if (cmSystemTools::IsOn(i->c_str())) {
  726. g.SetListDirs(true);
  727. g.SetRecurseListDirs(true);
  728. } else if (cmSystemTools::IsOff(i->c_str())) {
  729. g.SetListDirs(false);
  730. g.SetRecurseListDirs(false);
  731. } else {
  732. this->SetError("LIST_DIRECTORIES missing bool value.");
  733. return false;
  734. }
  735. } else {
  736. this->SetError("LIST_DIRECTORIES missing bool value.");
  737. return false;
  738. }
  739. continue;
  740. }
  741. if (recurse && (*i == "FOLLOW_SYMLINKS")) {
  742. explicitFollowSymlinks = true;
  743. g.RecurseThroughSymlinksOn();
  744. ++i;
  745. if (i == args.end()) {
  746. this->SetError(
  747. "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS");
  748. return false;
  749. }
  750. }
  751. if (*i == "RELATIVE") {
  752. ++i; // skip RELATIVE
  753. if (i == args.end()) {
  754. this->SetError("GLOB requires a directory after the RELATIVE tag");
  755. return false;
  756. }
  757. g.SetRelative(i->c_str());
  758. ++i;
  759. if (i == args.end()) {
  760. this->SetError("GLOB requires a glob expression after the directory");
  761. return false;
  762. }
  763. }
  764. cmsys::Glob::GlobMessages globMessages;
  765. if (!cmsys::SystemTools::FileIsFullPath(i->c_str())) {
  766. std::string expr = this->Makefile->GetCurrentSourceDirectory();
  767. // Handle script mode
  768. if (!expr.empty()) {
  769. expr += "/" + *i;
  770. g.FindFiles(expr, &globMessages);
  771. } else {
  772. g.FindFiles(*i, &globMessages);
  773. }
  774. } else {
  775. g.FindFiles(*i, &globMessages);
  776. }
  777. if (!globMessages.empty()) {
  778. bool shouldExit = false;
  779. for (cmsys::Glob::GlobMessagesIterator it = globMessages.begin();
  780. it != globMessages.end(); ++it) {
  781. if (it->type == cmsys::Glob::cyclicRecursion) {
  782. this->Makefile->IssueMessage(
  783. cmake::AUTHOR_WARNING,
  784. "Cyclic recursion detected while globbing for '" + *i + "':\n" +
  785. it->content);
  786. } else {
  787. this->Makefile->IssueMessage(
  788. cmake::FATAL_ERROR, "Error has occurred while globbing for '" +
  789. *i + "' - " + it->content);
  790. shouldExit = true;
  791. }
  792. }
  793. if (shouldExit) {
  794. return false;
  795. }
  796. }
  797. std::vector<std::string>::size_type cc;
  798. std::vector<std::string>& files = g.GetFiles();
  799. std::sort(files.begin(), files.end());
  800. for (cc = 0; cc < files.size(); cc++) {
  801. if (!first) {
  802. output += ";";
  803. }
  804. output += files[cc];
  805. first = false;
  806. }
  807. }
  808. if (recurse && !explicitFollowSymlinks) {
  809. switch (status) {
  810. case cmPolicies::REQUIRED_IF_USED:
  811. case cmPolicies::REQUIRED_ALWAYS:
  812. case cmPolicies::NEW:
  813. // Correct behavior, yay!
  814. break;
  815. case cmPolicies::OLD:
  816. // Probably not really the expected behavior, but the author explicitly
  817. // asked for the old behavior... no warning.
  818. case cmPolicies::WARN:
  819. // Possibly unexpected old behavior *and* we actually traversed
  820. // symlinks without being explicitly asked to: warn the author.
  821. if (g.GetFollowedSymlinkCount() != 0) {
  822. this->Makefile->IssueMessage(
  823. cmake::AUTHOR_WARNING,
  824. cmPolicies::GetPolicyWarning(cmPolicies::CMP0009));
  825. }
  826. break;
  827. }
  828. }
  829. this->Makefile->AddDefinition(variable, output.c_str());
  830. return true;
  831. }
  832. bool cmFileCommand::HandleMakeDirectoryCommand(
  833. std::vector<std::string> const& args)
  834. {
  835. // File command has at least one argument
  836. assert(args.size() > 1);
  837. std::vector<std::string>::const_iterator i = args.begin();
  838. i++; // Get rid of subcommand
  839. std::string expr;
  840. for (; i != args.end(); ++i) {
  841. const std::string* cdir = &(*i);
  842. if (!cmsys::SystemTools::FileIsFullPath(i->c_str())) {
  843. expr = this->Makefile->GetCurrentSourceDirectory();
  844. expr += "/" + *i;
  845. cdir = &expr;
  846. }
  847. if (!this->Makefile->CanIWriteThisFile(cdir->c_str())) {
  848. std::string e = "attempted to create a directory: " + *cdir +
  849. " into a source directory.";
  850. this->SetError(e);
  851. cmSystemTools::SetFatalErrorOccured();
  852. return false;
  853. }
  854. if (!cmSystemTools::MakeDirectory(cdir->c_str())) {
  855. std::string error = "problem creating directory: " + *cdir;
  856. this->SetError(error);
  857. return false;
  858. }
  859. }
  860. return true;
  861. }
  862. bool cmFileCommand::HandleDifferentCommand(
  863. std::vector<std::string> const& args)
  864. {
  865. /*
  866. FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
  867. */
  868. // Evaluate arguments.
  869. const char* file_lhs = nullptr;
  870. const char* file_rhs = nullptr;
  871. const char* var = nullptr;
  872. enum Doing
  873. {
  874. DoingNone,
  875. DoingVar,
  876. DoingFileLHS,
  877. DoingFileRHS
  878. };
  879. Doing doing = DoingVar;
  880. for (unsigned int i = 1; i < args.size(); ++i) {
  881. if (args[i] == "FILES") {
  882. doing = DoingFileLHS;
  883. } else if (doing == DoingVar) {
  884. var = args[i].c_str();
  885. doing = DoingNone;
  886. } else if (doing == DoingFileLHS) {
  887. file_lhs = args[i].c_str();
  888. doing = DoingFileRHS;
  889. } else if (doing == DoingFileRHS) {
  890. file_rhs = args[i].c_str();
  891. doing = DoingNone;
  892. } else {
  893. std::ostringstream e;
  894. e << "DIFFERENT given unknown argument " << args[i];
  895. this->SetError(e.str());
  896. return false;
  897. }
  898. }
  899. if (!var) {
  900. this->SetError("DIFFERENT not given result variable name.");
  901. return false;
  902. }
  903. if (!file_lhs || !file_rhs) {
  904. this->SetError("DIFFERENT not given FILES option with two file names.");
  905. return false;
  906. }
  907. // Compare the files.
  908. const char* result =
  909. cmSystemTools::FilesDiffer(file_lhs, file_rhs) ? "1" : "0";
  910. this->Makefile->AddDefinition(var, result);
  911. return true;
  912. }
  913. // File installation helper class.
  914. struct cmFileCopier
  915. {
  916. cmFileCopier(cmFileCommand* command, const char* name = "COPY")
  917. : FileCommand(command)
  918. , Makefile(command->GetMakefile())
  919. , Name(name)
  920. , Always(false)
  921. , MatchlessFiles(true)
  922. , FilePermissions(0)
  923. , DirPermissions(0)
  924. , CurrentMatchRule(nullptr)
  925. , UseGivenPermissionsFile(false)
  926. , UseGivenPermissionsDir(false)
  927. , UseSourcePermissions(true)
  928. , Doing(DoingNone)
  929. {
  930. }
  931. virtual ~cmFileCopier() {}
  932. bool Run(std::vector<std::string> const& args);
  933. protected:
  934. cmFileCommand* FileCommand;
  935. cmMakefile* Makefile;
  936. const char* Name;
  937. bool Always;
  938. cmFileTimeComparison FileTimes;
  939. // Whether to install a file not matching any expression.
  940. bool MatchlessFiles;
  941. // Permissions for files and directories installed by this object.
  942. mode_t FilePermissions;
  943. mode_t DirPermissions;
  944. // Properties set by pattern and regex match rules.
  945. struct MatchProperties
  946. {
  947. bool Exclude;
  948. mode_t Permissions;
  949. MatchProperties()
  950. : Exclude(false)
  951. , Permissions(0)
  952. {
  953. }
  954. };
  955. struct MatchRule
  956. {
  957. cmsys::RegularExpression Regex;
  958. MatchProperties Properties;
  959. std::string RegexString;
  960. MatchRule(std::string const& regex)
  961. : Regex(regex.c_str())
  962. , RegexString(regex)
  963. {
  964. }
  965. };
  966. std::vector<MatchRule> MatchRules;
  967. // Get the properties from rules matching this input file.
  968. MatchProperties CollectMatchProperties(const char* file)
  969. {
  970. // Match rules are case-insensitive on some platforms.
  971. #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
  972. std::string lower = cmSystemTools::LowerCase(file);
  973. const char* file_to_match = lower.c_str();
  974. #else
  975. const char* file_to_match = file;
  976. #endif
  977. // Collect properties from all matching rules.
  978. bool matched = false;
  979. MatchProperties result;
  980. for (std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
  981. mr != this->MatchRules.end(); ++mr) {
  982. if (mr->Regex.find(file_to_match)) {
  983. matched = true;
  984. result.Exclude |= mr->Properties.Exclude;
  985. result.Permissions |= mr->Properties.Permissions;
  986. }
  987. }
  988. if (!matched && !this->MatchlessFiles) {
  989. result.Exclude = !cmSystemTools::FileIsDirectory(file);
  990. }
  991. return result;
  992. }
  993. bool SetPermissions(const char* toFile, mode_t permissions)
  994. {
  995. if (permissions) {
  996. #ifdef WIN32
  997. if (Makefile->IsOn("CMAKE_CROSSCOMPILING")) {
  998. std::string mode_t_adt_filename =
  999. std::string(toFile) + ":cmake_mode_t";
  1000. cmsys::ofstream permissionStream(mode_t_adt_filename.c_str());
  1001. if (permissionStream) {
  1002. permissionStream << std::oct << permissions << std::endl;
  1003. }
  1004. }
  1005. #endif
  1006. if (!cmSystemTools::SetPermissions(toFile, permissions)) {
  1007. std::ostringstream e;
  1008. e << this->Name << " cannot set permissions on \"" << toFile << "\"";
  1009. this->FileCommand->SetError(e.str());
  1010. return false;
  1011. }
  1012. }
  1013. return true;
  1014. }
  1015. // Translate an argument to a permissions bit.
  1016. bool CheckPermissions(std::string const& arg, mode_t& permissions)
  1017. {
  1018. if (arg == "OWNER_READ") {
  1019. permissions |= mode_owner_read;
  1020. } else if (arg == "OWNER_WRITE") {
  1021. permissions |= mode_owner_write;
  1022. } else if (arg == "OWNER_EXECUTE") {
  1023. permissions |= mode_owner_execute;
  1024. } else if (arg == "GROUP_READ") {
  1025. permissions |= mode_group_read;
  1026. } else if (arg == "GROUP_WRITE") {
  1027. permissions |= mode_group_write;
  1028. } else if (arg == "GROUP_EXECUTE") {
  1029. permissions |= mode_group_execute;
  1030. } else if (arg == "WORLD_READ") {
  1031. permissions |= mode_world_read;
  1032. } else if (arg == "WORLD_WRITE") {
  1033. permissions |= mode_world_write;
  1034. } else if (arg == "WORLD_EXECUTE") {
  1035. permissions |= mode_world_execute;
  1036. } else if (arg == "SETUID") {
  1037. permissions |= mode_setuid;
  1038. } else if (arg == "SETGID") {
  1039. permissions |= mode_setgid;
  1040. } else {
  1041. std::ostringstream e;
  1042. e << this->Name << " given invalid permission \"" << arg << "\".";
  1043. this->FileCommand->SetError(e.str());
  1044. return false;
  1045. }
  1046. return true;
  1047. }
  1048. bool InstallSymlink(const char* fromFile, const char* toFile);
  1049. bool InstallFile(const char* fromFile, const char* toFile,
  1050. MatchProperties match_properties);
  1051. bool InstallDirectory(const char* source, const char* destination,
  1052. MatchProperties match_properties);
  1053. virtual bool Install(const char* fromFile, const char* toFile);
  1054. virtual std::string const& ToName(std::string const& fromName)
  1055. {
  1056. return fromName;
  1057. }
  1058. enum Type
  1059. {
  1060. TypeFile,
  1061. TypeDir,
  1062. TypeLink
  1063. };
  1064. virtual void ReportCopy(const char*, Type, bool) {}
  1065. virtual bool ReportMissing(const char* fromFile)
  1066. {
  1067. // The input file does not exist and installation is not optional.
  1068. std::ostringstream e;
  1069. e << this->Name << " cannot find \"" << fromFile << "\".";
  1070. this->FileCommand->SetError(e.str());
  1071. return false;
  1072. }
  1073. MatchRule* CurrentMatchRule;
  1074. bool UseGivenPermissionsFile;
  1075. bool UseGivenPermissionsDir;
  1076. bool UseSourcePermissions;
  1077. std::string Destination;
  1078. std::string FilesFromDir;
  1079. std::vector<std::string> Files;
  1080. int Doing;
  1081. virtual bool Parse(std::vector<std::string> const& args);
  1082. enum
  1083. {
  1084. DoingNone,
  1085. DoingError,
  1086. DoingDestination,
  1087. DoingFilesFromDir,
  1088. DoingFiles,
  1089. DoingPattern,
  1090. DoingRegex,
  1091. DoingPermissionsFile,
  1092. DoingPermissionsDir,
  1093. DoingPermissionsMatch,
  1094. DoingLast1
  1095. };
  1096. virtual bool CheckKeyword(std::string const& arg);
  1097. virtual bool CheckValue(std::string const& arg);
  1098. void NotBeforeMatch(std::string const& arg)
  1099. {
  1100. std::ostringstream e;
  1101. e << "option " << arg << " may not appear before PATTERN or REGEX.";
  1102. this->FileCommand->SetError(e.str());
  1103. this->Doing = DoingError;
  1104. }
  1105. void NotAfterMatch(std::string const& arg)
  1106. {
  1107. std::ostringstream e;
  1108. e << "option " << arg << " may not appear after PATTERN or REGEX.";
  1109. this->FileCommand->SetError(e.str());
  1110. this->Doing = DoingError;
  1111. }
  1112. virtual void DefaultFilePermissions()
  1113. {
  1114. // Use read/write permissions.
  1115. this->FilePermissions = 0;
  1116. this->FilePermissions |= mode_owner_read;
  1117. this->FilePermissions |= mode_owner_write;
  1118. this->FilePermissions |= mode_group_read;
  1119. this->FilePermissions |= mode_world_read;
  1120. }
  1121. virtual void DefaultDirectoryPermissions()
  1122. {
  1123. // Use read/write/executable permissions.
  1124. this->DirPermissions = 0;
  1125. this->DirPermissions |= mode_owner_read;
  1126. this->DirPermissions |= mode_owner_write;
  1127. this->DirPermissions |= mode_owner_execute;
  1128. this->DirPermissions |= mode_group_read;
  1129. this->DirPermissions |= mode_group_execute;
  1130. this->DirPermissions |= mode_world_read;
  1131. this->DirPermissions |= mode_world_execute;
  1132. }
  1133. };
  1134. bool cmFileCopier::Parse(std::vector<std::string> const& args)
  1135. {
  1136. this->Doing = DoingFiles;
  1137. for (unsigned int i = 1; i < args.size(); ++i) {
  1138. // Check this argument.
  1139. if (!this->CheckKeyword(args[i]) && !this->CheckValue(args[i])) {
  1140. std::ostringstream e;
  1141. e << "called with unknown argument \"" << args[i] << "\".";
  1142. this->FileCommand->SetError(e.str());
  1143. return false;
  1144. }
  1145. // Quit if an argument is invalid.
  1146. if (this->Doing == DoingError) {
  1147. return false;
  1148. }
  1149. }
  1150. // Require a destination.
  1151. if (this->Destination.empty()) {
  1152. std::ostringstream e;
  1153. e << this->Name << " given no DESTINATION";
  1154. this->FileCommand->SetError(e.str());
  1155. return false;
  1156. }
  1157. // If file permissions were not specified set default permissions.
  1158. if (!this->UseGivenPermissionsFile && !this->UseSourcePermissions) {
  1159. this->DefaultFilePermissions();
  1160. }
  1161. // If directory permissions were not specified set default permissions.
  1162. if (!this->UseGivenPermissionsDir && !this->UseSourcePermissions) {
  1163. this->DefaultDirectoryPermissions();
  1164. }
  1165. return true;
  1166. }
  1167. bool cmFileCopier::CheckKeyword(std::string const& arg)
  1168. {
  1169. if (arg == "DESTINATION") {
  1170. if (this->CurrentMatchRule) {
  1171. this->NotAfterMatch(arg);
  1172. } else {
  1173. this->Doing = DoingDestination;
  1174. }
  1175. } else if (arg == "FILES_FROM_DIR") {
  1176. if (this->CurrentMatchRule) {
  1177. this->NotAfterMatch(arg);
  1178. } else {
  1179. this->Doing = DoingFilesFromDir;
  1180. }
  1181. } else if (arg == "PATTERN") {
  1182. this->Doing = DoingPattern;
  1183. } else if (arg == "REGEX") {
  1184. this->Doing = DoingRegex;
  1185. } else if (arg == "EXCLUDE") {
  1186. // Add this property to the current match rule.
  1187. if (this->CurrentMatchRule) {
  1188. this->CurrentMatchRule->Properties.Exclude = true;
  1189. this->Doing = DoingNone;
  1190. } else {
  1191. this->NotBeforeMatch(arg);
  1192. }
  1193. } else if (arg == "PERMISSIONS") {
  1194. if (this->CurrentMatchRule) {
  1195. this->Doing = DoingPermissionsMatch;
  1196. } else {
  1197. this->NotBeforeMatch(arg);
  1198. }
  1199. } else if (arg == "FILE_PERMISSIONS") {
  1200. if (this->CurrentMatchRule) {
  1201. this->NotAfterMatch(arg);
  1202. } else {
  1203. this->Doing = DoingPermissionsFile;
  1204. this->UseGivenPermissionsFile = true;
  1205. }
  1206. } else if (arg == "DIRECTORY_PERMISSIONS") {
  1207. if (this->CurrentMatchRule) {
  1208. this->NotAfterMatch(arg);
  1209. } else {
  1210. this->Doing = DoingPermissionsDir;
  1211. this->UseGivenPermissionsDir = true;
  1212. }
  1213. } else if (arg == "USE_SOURCE_PERMISSIONS") {
  1214. if (this->CurrentMatchRule) {
  1215. this->NotAfterMatch(arg);
  1216. } else {
  1217. this->Doing = DoingNone;
  1218. this->UseSourcePermissions = true;
  1219. }
  1220. } else if (arg == "NO_SOURCE_PERMISSIONS") {
  1221. if (this->CurrentMatchRule) {
  1222. this->NotAfterMatch(arg);
  1223. } else {
  1224. this->Doing = DoingNone;
  1225. this->UseSourcePermissions = false;
  1226. }
  1227. } else if (arg == "FILES_MATCHING") {
  1228. if (this->CurrentMatchRule) {
  1229. this->NotAfterMatch(arg);
  1230. } else {
  1231. this->Doing = DoingNone;
  1232. this->MatchlessFiles = false;
  1233. }
  1234. } else {
  1235. return false;
  1236. }
  1237. return true;
  1238. }
  1239. bool cmFileCopier::CheckValue(std::string const& arg)
  1240. {
  1241. switch (this->Doing) {
  1242. case DoingFiles:
  1243. this->Files.push_back(arg);
  1244. break;
  1245. case DoingDestination:
  1246. if (arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str())) {
  1247. this->Destination = arg;
  1248. } else {
  1249. this->Destination = this->Makefile->GetCurrentBinaryDirectory();
  1250. this->Destination += "/" + arg;
  1251. }
  1252. this->Doing = DoingNone;
  1253. break;
  1254. case DoingFilesFromDir:
  1255. if (cmSystemTools::FileIsFullPath(arg.c_str())) {
  1256. this->FilesFromDir = arg;
  1257. } else {
  1258. this->FilesFromDir = this->Makefile->GetCurrentSourceDirectory();
  1259. this->FilesFromDir += "/" + arg;
  1260. }
  1261. cmSystemTools::ConvertToUnixSlashes(this->FilesFromDir);
  1262. this->Doing = DoingNone;
  1263. break;
  1264. case DoingPattern: {
  1265. // Convert the pattern to a regular expression. Require a
  1266. // leading slash and trailing end-of-string in the matched
  1267. // string to make sure the pattern matches only whole file
  1268. // names.
  1269. std::string regex = "/";
  1270. regex += cmsys::Glob::PatternToRegex(arg, false);
  1271. regex += "$";
  1272. this->MatchRules.push_back(MatchRule(regex));
  1273. this->CurrentMatchRule = &*(this->MatchRules.end() - 1);
  1274. if (this->CurrentMatchRule->Regex.is_valid()) {
  1275. this->Doing = DoingNone;
  1276. } else {
  1277. std::ostringstream e;
  1278. e << "could not compile PATTERN \"" << arg << "\".";
  1279. this->FileCommand->SetError(e.str());
  1280. this->Doing = DoingError;
  1281. }
  1282. } break;
  1283. case DoingRegex:
  1284. this->MatchRules.push_back(MatchRule(arg));
  1285. this->CurrentMatchRule = &*(this->MatchRules.end() - 1);
  1286. if (this->CurrentMatchRule->Regex.is_valid()) {
  1287. this->Doing = DoingNone;
  1288. } else {
  1289. std::ostringstream e;
  1290. e << "could not compile REGEX \"" << arg << "\".";
  1291. this->FileCommand->SetError(e.str());
  1292. this->Doing = DoingError;
  1293. }
  1294. break;
  1295. case DoingPermissionsFile:
  1296. if (!this->CheckPermissions(arg, this->FilePermissions)) {
  1297. this->Doing = DoingError;
  1298. }
  1299. break;
  1300. case DoingPermissionsDir:
  1301. if (!this->CheckPermissions(arg, this->DirPermissions)) {
  1302. this->Doing = DoingError;
  1303. }
  1304. break;
  1305. case DoingPermissionsMatch:
  1306. if (!this->CheckPermissions(
  1307. arg, this->CurrentMatchRule->Properties.Permissions)) {
  1308. this->Doing = DoingError;
  1309. }
  1310. break;
  1311. default:
  1312. return false;
  1313. }
  1314. return true;
  1315. }
  1316. bool cmFileCopier::Run(std::vector<std::string> const& args)
  1317. {
  1318. if (!this->Parse(args)) {
  1319. return false;
  1320. }
  1321. for (std::vector<std::string>::const_iterator i = this->Files.begin();
  1322. i != this->Files.end(); ++i) {
  1323. std::string file;
  1324. if (!i->empty() && !cmSystemTools::FileIsFullPath(*i)) {
  1325. if (!this->FilesFromDir.empty()) {
  1326. file = this->FilesFromDir;
  1327. } else {
  1328. file = this->Makefile->GetCurrentSourceDirectory();
  1329. }
  1330. file += "/";
  1331. file += *i;
  1332. } else if (!this->FilesFromDir.empty()) {
  1333. this->FileCommand->SetError("option FILES_FROM_DIR requires all files "
  1334. "to be specified as relative paths.");
  1335. return false;
  1336. } else {
  1337. file = *i;
  1338. }
  1339. // Split the input file into its directory and name components.
  1340. std::vector<std::string> fromPathComponents;
  1341. cmSystemTools::SplitPath(file, fromPathComponents);
  1342. std::string fromName = *(fromPathComponents.end() - 1);
  1343. std::string fromDir = cmSystemTools::JoinPath(
  1344. fromPathComponents.begin(), fromPathComponents.end() - 1);
  1345. // Compute the full path to the destination file.
  1346. std::string toFile = this->Destination;
  1347. if (!this->FilesFromDir.empty()) {
  1348. std::string dir = cmSystemTools::GetFilenamePath(*i);
  1349. if (!dir.empty()) {
  1350. toFile += "/";
  1351. toFile += dir;
  1352. }
  1353. }
  1354. std::string const& toName = this->ToName(fromName);
  1355. if (!toName.empty()) {
  1356. toFile += "/";
  1357. toFile += toName;
  1358. }
  1359. // Construct the full path to the source file. The file name may
  1360. // have been changed above.
  1361. std::string fromFile = fromDir;
  1362. if (!fromName.empty()) {
  1363. fromFile += "/";
  1364. fromFile += fromName;
  1365. }
  1366. if (!this->Install(fromFile.c_str(), toFile.c_str())) {
  1367. return false;
  1368. }
  1369. }
  1370. return true;
  1371. }
  1372. bool cmFileCopier::Install(const char* fromFile, const char* toFile)
  1373. {
  1374. if (!*fromFile) {
  1375. std::ostringstream e;
  1376. e << "INSTALL encountered an empty string input file name.";
  1377. this->FileCommand->SetError(e.str());
  1378. return false;
  1379. }
  1380. // Collect any properties matching this file name.
  1381. MatchProperties match_properties = this->CollectMatchProperties(fromFile);
  1382. // Skip the file if it is excluded.
  1383. if (match_properties.Exclude) {
  1384. return true;
  1385. }
  1386. if (cmSystemTools::SameFile(fromFile, toFile)) {
  1387. return true;
  1388. }
  1389. if (cmSystemTools::FileIsSymlink(fromFile)) {
  1390. return this->InstallSymlink(fromFile, toFile);
  1391. }
  1392. if (cmSystemTools::FileIsDirectory(fromFile)) {
  1393. return this->InstallDirectory(fromFile, toFile, match_properties);
  1394. }
  1395. if (cmSystemTools::FileExists(fromFile)) {
  1396. return this->InstallFile(fromFile, toFile, match_properties);
  1397. }
  1398. return this->ReportMissing(fromFile);
  1399. }
  1400. bool cmFileCopier::InstallSymlink(const char* fromFile, const char* toFile)
  1401. {
  1402. // Read the original symlink.
  1403. std::string symlinkTarget;
  1404. if (!cmSystemTools::ReadSymlink(fromFile, symlinkTarget)) {
  1405. std::ostringstream e;
  1406. e << this->Name << " cannot read symlink \"" << fromFile
  1407. << "\" to duplicate at \"" << toFile << "\".";
  1408. this->FileCommand->SetError(e.str());
  1409. return false;
  1410. }
  1411. // Compare the symlink value to that at the destination if not
  1412. // always installing.
  1413. bool copy = true;
  1414. if (!this->Always) {
  1415. std::string oldSymlinkTarget;
  1416. if (cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget)) {
  1417. if (symlinkTarget == oldSymlinkTarget) {
  1418. copy = false;
  1419. }
  1420. }
  1421. }
  1422. // Inform the user about this file installation.
  1423. this->ReportCopy(toFile, TypeLink, copy);
  1424. if (copy) {
  1425. // Remove the destination file so we can always create the symlink.
  1426. cmSystemTools::RemoveFile(toFile);
  1427. // Create destination directory if it doesn't exist
  1428. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(toFile));
  1429. // Create the symlink.
  1430. if (!cmSystemTools::CreateSymlink(symlinkTarget, toFile)) {
  1431. std::ostringstream e;
  1432. e << this->Name << " cannot duplicate symlink \"" << fromFile
  1433. << "\" at \"" << toFile << "\".";
  1434. this->FileCommand->SetError(e.str());
  1435. return false;
  1436. }
  1437. }
  1438. return true;
  1439. }
  1440. bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile,
  1441. MatchProperties match_properties)
  1442. {
  1443. // Determine whether we will copy the file.
  1444. bool copy = true;
  1445. if (!this->Always) {
  1446. // If both files exist with the same time do not copy.
  1447. if (!this->FileTimes.FileTimesDiffer(fromFile, toFile)) {
  1448. copy = false;
  1449. }
  1450. }
  1451. // Inform the user about this file installation.
  1452. this->ReportCopy(toFile, TypeFile, copy);
  1453. // Copy the file.
  1454. if (copy && !cmSystemTools::CopyAFile(fromFile, toFile, true)) {
  1455. std::ostringstream e;
  1456. e << this->Name << " cannot copy file \"" << fromFile << "\" to \""
  1457. << toFile << "\".";
  1458. this->FileCommand->SetError(e.str());
  1459. return false;
  1460. }
  1461. // Set the file modification time of the destination file.
  1462. if (copy && !this->Always) {
  1463. // Add write permission so we can set the file time.
  1464. // Permissions are set unconditionally below anyway.
  1465. mode_t perm = 0;
  1466. if (cmSystemTools::GetPermissions(toFile, perm)) {
  1467. cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
  1468. }
  1469. if (!cmSystemTools::CopyFileTime(fromFile, toFile)) {
  1470. std::ostringstream e;
  1471. e << this->Name << " cannot set modification time on \"" << toFile
  1472. << "\"";
  1473. this->FileCommand->SetError(e.str());
  1474. return false;
  1475. }
  1476. }
  1477. // Set permissions of the destination file.
  1478. mode_t permissions =
  1479. (match_properties.Permissions ? match_properties.Permissions
  1480. : this->FilePermissions);
  1481. if (!permissions) {
  1482. // No permissions were explicitly provided but the user requested
  1483. // that the source file permissions be used.
  1484. cmSystemTools::GetPermissions(fromFile, permissions);
  1485. }
  1486. return this->SetPermissions(toFile, permissions);
  1487. }
  1488. bool cmFileCopier::InstallDirectory(const char* source,
  1489. const char* destination,
  1490. MatchProperties match_properties)
  1491. {
  1492. // Inform the user about this directory installation.
  1493. this->ReportCopy(destination, TypeDir,
  1494. !cmSystemTools::FileIsDirectory(destination));
  1495. // Make sure the destination directory exists.
  1496. if (!cmSystemTools::MakeDirectory(destination)) {
  1497. std::ostringstream e;
  1498. e << this->Name << " cannot make directory \"" << destination
  1499. << "\": " << cmSystemTools::GetLastSystemError();
  1500. this->FileCommand->SetError(e.str());
  1501. return false;
  1502. }
  1503. // Compute the requested permissions for the destination directory.
  1504. mode_t permissions =
  1505. (match_properties.Permissions ? match_properties.Permissions
  1506. : this->DirPermissions);
  1507. if (!permissions) {
  1508. // No permissions were explicitly provided but the user requested
  1509. // that the source directory permissions be used.
  1510. cmSystemTools::GetPermissions(source, permissions);
  1511. }
  1512. // Compute the set of permissions required on this directory to
  1513. // recursively install files and subdirectories safely.
  1514. mode_t required_permissions =
  1515. mode_owner_read | mode_owner_write | mode_owner_execute;
  1516. // If the required permissions are specified it is safe to set the
  1517. // final permissions now. Otherwise we must add the required
  1518. // permissions temporarily during file installation.
  1519. mode_t permissions_before = 0;
  1520. mode_t permissions_after = 0;
  1521. if ((permissions & required_permissions) == required_permissions) {
  1522. permissions_before = permissions;
  1523. } else {
  1524. permissions_before = permissions | required_permissions;
  1525. permissions_after = permissions;
  1526. }
  1527. // Set the required permissions of the destination directory.
  1528. if (!this->SetPermissions(destination, permissions_before)) {
  1529. return false;
  1530. }
  1531. // Load the directory contents to traverse it recursively.
  1532. cmsys::Directory dir;
  1533. if (source && *source) {
  1534. dir.Load(source);
  1535. }
  1536. unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
  1537. for (unsigned long fileNum = 0; fileNum < numFiles; ++fileNum) {
  1538. if (!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
  1539. strcmp(dir.GetFile(fileNum), "..") == 0)) {
  1540. std::string fromPath = source;
  1541. fromPath += "/";
  1542. fromPath += dir.GetFile(fileNum);
  1543. std::string toPath = destination;
  1544. toPath += "/";
  1545. toPath += dir.GetFile(fileNum);
  1546. if (!this->Install(fromPath.c_str(), toPath.c_str())) {
  1547. return false;
  1548. }
  1549. }
  1550. }
  1551. // Set the requested permissions of the destination directory.
  1552. return this->SetPermissions(destination, permissions_after);
  1553. }
  1554. bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
  1555. {
  1556. cmFileCopier copier(this);
  1557. return copier.Run(args);
  1558. }
  1559. struct cmFileInstaller : public cmFileCopier
  1560. {
  1561. cmFileInstaller(cmFileCommand* command)
  1562. : cmFileCopier(command, "INSTALL")
  1563. , InstallType(cmInstallType_FILES)
  1564. , Optional(false)
  1565. , MessageAlways(false)
  1566. , MessageLazy(false)
  1567. , MessageNever(false)
  1568. , DestDirLength(0)
  1569. {
  1570. // Installation does not use source permissions by default.
  1571. this->UseSourcePermissions = false;
  1572. // Check whether to copy files always or only if they have changed.
  1573. std::string install_always;
  1574. if (cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS", install_always)) {
  1575. this->Always = cmSystemTools::IsOn(install_always.c_str());
  1576. }
  1577. // Get the current manifest.
  1578. this->Manifest =
  1579. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
  1580. }
  1581. ~cmFileInstaller() CM_OVERRIDE
  1582. {
  1583. // Save the updated install manifest.
  1584. this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
  1585. this->Manifest.c_str());
  1586. }
  1587. protected:
  1588. cmInstallType InstallType;
  1589. bool Optional;
  1590. bool MessageAlways;
  1591. bool MessageLazy;
  1592. bool MessageNever;
  1593. int DestDirLength;
  1594. std::string Rename;
  1595. std::string Manifest;
  1596. void ManifestAppend(std::string const& file)
  1597. {
  1598. if (!this->Manifest.empty()) {
  1599. this->Manifest += ";";
  1600. }
  1601. this->Manifest += file.substr(this->DestDirLength);
  1602. }
  1603. std::string const& ToName(std::string const& fromName) CM_OVERRIDE
  1604. {
  1605. return this->Rename.empty() ? fromName : this->Rename;
  1606. }
  1607. void ReportCopy(const char* toFile, Type type, bool copy) CM_OVERRIDE
  1608. {
  1609. if (!this->MessageNever && (copy || !this->MessageLazy)) {
  1610. std::string message = (copy ? "Installing: " : "Up-to-date: ");
  1611. message += toFile;
  1612. this->Makefile->DisplayStatus(message.c_str(), -1);
  1613. }
  1614. if (type != TypeDir) {
  1615. // Add the file to the manifest.
  1616. this->ManifestAppend(toFile);
  1617. }
  1618. }
  1619. bool ReportMissing(const char* fromFile) CM_OVERRIDE
  1620. {
  1621. return (this->Optional || this->cmFileCopier::ReportMissing(fromFile));
  1622. }
  1623. bool Install(const char* fromFile, const char* toFile) CM_OVERRIDE
  1624. {
  1625. // Support installing from empty source to make a directory.
  1626. if (this->InstallType == cmInstallType_DIRECTORY && !*fromFile) {
  1627. return this->InstallDirectory(fromFile, toFile, MatchProperties());
  1628. }
  1629. return this->cmFileCopier::Install(fromFile, toFile);
  1630. }
  1631. bool Parse(std::vector<std::string> const& args) CM_OVERRIDE;
  1632. enum
  1633. {
  1634. DoingType = DoingLast1,
  1635. DoingRename,
  1636. DoingLast2
  1637. };
  1638. bool CheckKeyword(std::string const& arg) CM_OVERRIDE;
  1639. bool CheckValue(std::string const& arg) CM_OVERRIDE;
  1640. void DefaultFilePermissions() CM_OVERRIDE
  1641. {
  1642. this->cmFileCopier::DefaultFilePermissions();
  1643. // Add execute permissions based on the target type.
  1644. switch (this->InstallType) {
  1645. case cmInstallType_SHARED_LIBRARY:
  1646. case cmInstallType_MODULE_LIBRARY:
  1647. if (this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE")) {
  1648. break;
  1649. }
  1650. CM_FALLTHROUGH;
  1651. case cmInstallType_EXECUTABLE:
  1652. case cmInstallType_PROGRAMS:
  1653. this->FilePermissions |= mode_owner_execute;
  1654. this->FilePermissions |= mode_group_execute;
  1655. this->FilePermissions |= mode_world_execute;
  1656. break;
  1657. default:
  1658. break;
  1659. }
  1660. }
  1661. bool GetTargetTypeFromString(const std::string& stype);
  1662. bool HandleInstallDestination();
  1663. };
  1664. bool cmFileInstaller::Parse(std::vector<std::string> const& args)
  1665. {
  1666. if (!this->cmFileCopier::Parse(args)) {
  1667. return false;
  1668. }
  1669. if (!this->Rename.empty()) {
  1670. if (!this->FilesFromDir.empty()) {
  1671. this->FileCommand->SetError("INSTALL option RENAME may not be "
  1672. "combined with FILES_FROM_DIR.");
  1673. return false;
  1674. }
  1675. if (this->InstallType != cmInstallType_FILES &&
  1676. this->InstallType != cmInstallType_PROGRAMS) {
  1677. this->FileCommand->SetError("INSTALL option RENAME may be used "
  1678. "only with FILES or PROGRAMS.");
  1679. return false;
  1680. }
  1681. if (this->Files.size() > 1) {
  1682. this->FileCommand->SetError("INSTALL option RENAME may be used "
  1683. "only with one file.");
  1684. return false;
  1685. }
  1686. }
  1687. if (!this->HandleInstallDestination()) {
  1688. return false;
  1689. }
  1690. if (((this->MessageAlways ? 1 : 0) + (this->MessageLazy ? 1 : 0) +
  1691. (this->MessageNever ? 1 : 0)) > 1) {
  1692. this->FileCommand->SetError("INSTALL options MESSAGE_ALWAYS, "
  1693. "MESSAGE_LAZY, and MESSAGE_NEVER "
  1694. "are mutually exclusive.");
  1695. return false;
  1696. }
  1697. return true;
  1698. }
  1699. bool cmFileInstaller::CheckKeyword(std::string const& arg)
  1700. {
  1701. if (arg == "TYPE") {
  1702. if (this->CurrentMatchRule) {
  1703. this->NotAfterMatch(arg);
  1704. } else {
  1705. this->Doing = DoingType;
  1706. }
  1707. } else if (arg == "FILES") {
  1708. if (this->CurrentMatchRule) {
  1709. this->NotAfterMatch(arg);
  1710. } else {
  1711. this->Doing = DoingFiles;
  1712. }
  1713. } else if (arg == "RENAME") {
  1714. if (this->CurrentMatchRule) {
  1715. this->NotAfterMatch(arg);
  1716. } else {
  1717. this->Doing = DoingRename;
  1718. }
  1719. } else if (arg == "OPTIONAL") {
  1720. if (this->CurrentMatchRule) {
  1721. this->NotAfterMatch(arg);
  1722. } else {
  1723. this->Doing = DoingNone;
  1724. this->Optional = true;
  1725. }
  1726. } else if (arg == "MESSAGE_ALWAYS") {
  1727. if (this->CurrentMatchRule) {
  1728. this->NotAfterMatch(arg);
  1729. } else {
  1730. this->Doing = DoingNone;
  1731. this->MessageAlways = true;
  1732. }
  1733. } else if (arg == "MESSAGE_LAZY") {
  1734. if (this->CurrentMatchRule) {
  1735. this->NotAfterMatch(arg);
  1736. } else {
  1737. this->Doing = DoingNone;
  1738. this->MessageLazy = true;
  1739. }
  1740. } else if (arg == "MESSAGE_NEVER") {
  1741. if (this->CurrentMatchRule) {
  1742. this->NotAfterMatch(arg);
  1743. } else {
  1744. this->Doing = DoingNone;
  1745. this->MessageNever = true;
  1746. }
  1747. } else if (arg == "PERMISSIONS") {
  1748. if (this->CurrentMatchRule) {
  1749. this->Doing = DoingPermissionsMatch;
  1750. } else {
  1751. // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
  1752. this->Doing = DoingPermissionsFile;
  1753. this->UseGivenPermissionsFile = true;
  1754. }
  1755. } else if (arg == "DIR_PERMISSIONS") {
  1756. if (this->CurrentMatchRule) {
  1757. this->NotAfterMatch(arg);
  1758. } else {
  1759. // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
  1760. this->Doing = DoingPermissionsDir;
  1761. this->UseGivenPermissionsDir = true;
  1762. }
  1763. } else if (arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
  1764. arg == "PROPERTIES") {
  1765. std::ostringstream e;
  1766. e << "INSTALL called with old-style " << arg << " argument. "
  1767. << "This script was generated with an older version of CMake. "
  1768. << "Re-run this cmake version on your build tree.";
  1769. this->FileCommand->SetError(e.str());
  1770. this->Doing = DoingError;
  1771. } else {
  1772. return this->cmFileCopier::CheckKeyword(arg);
  1773. }
  1774. return true;
  1775. }
  1776. bool cmFileInstaller::CheckValue(std::string const& arg)
  1777. {
  1778. switch (this->Doing) {
  1779. case DoingType:
  1780. if (!this->GetTargetTypeFromString(arg)) {
  1781. this->Doing = DoingError;
  1782. }
  1783. break;
  1784. case DoingRename:
  1785. this->Rename = arg;
  1786. break;
  1787. default:
  1788. return this->cmFileCopier::CheckValue(arg);
  1789. }
  1790. return true;
  1791. }
  1792. bool cmFileInstaller::GetTargetTypeFromString(const std::string& stype)
  1793. {
  1794. if (stype == "EXECUTABLE") {
  1795. this->InstallType = cmInstallType_EXECUTABLE;
  1796. } else if (stype == "FILE") {
  1797. this->InstallType = cmInstallType_FILES;
  1798. } else if (stype == "PROGRAM") {
  1799. this->InstallType = cmInstallType_PROGRAMS;
  1800. } else if (stype == "STATIC_LIBRARY") {
  1801. this->InstallType = cmInstallType_STATIC_LIBRARY;
  1802. } else if (stype == "SHARED_LIBRARY") {
  1803. this->InstallType = cmInstallType_SHARED_LIBRARY;
  1804. } else if (stype == "MODULE") {
  1805. this->InstallType = cmInstallType_MODULE_LIBRARY;
  1806. } else if (stype == "DIRECTORY") {
  1807. this->InstallType = cmInstallType_DIRECTORY;
  1808. } else {
  1809. std::ostringstream e;
  1810. e << "Option TYPE given unknown value \"" << stype << "\".";
  1811. this->FileCommand->SetError(e.str());
  1812. return false;
  1813. }
  1814. return true;
  1815. }
  1816. bool cmFileInstaller::HandleInstallDestination()
  1817. {
  1818. std::string& destination = this->Destination;
  1819. // allow for / to be a valid destination
  1820. if (destination.size() < 2 && destination != "/") {
  1821. this->FileCommand->SetError("called with inappropriate arguments. "
  1822. "No DESTINATION provided or .");
  1823. return false;
  1824. }
  1825. std::string sdestdir;
  1826. if (cmSystemTools::GetEnv("DESTDIR", sdestdir) && !sdestdir.empty()) {
  1827. cmSystemTools::ConvertToUnixSlashes(sdestdir);
  1828. char ch1 = destination[0];
  1829. char ch2 = destination[1];
  1830. char ch3 = 0;
  1831. if (destination.size() > 2) {
  1832. ch3 = destination[2];
  1833. }
  1834. int skip = 0;
  1835. if (ch1 != '/') {
  1836. int relative = 0;
  1837. if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
  1838. ch2 == ':') {
  1839. // Assume windows
  1840. // let's do some destdir magic:
  1841. skip = 2;
  1842. if (ch3 != '/') {
  1843. relative = 1;
  1844. }
  1845. } else {
  1846. relative = 1;
  1847. }
  1848. if (relative) {
  1849. // This is relative path on unix or windows. Since we are doing
  1850. // destdir, this case does not make sense.
  1851. this->FileCommand->SetError(
  1852. "called with relative DESTINATION. This "
  1853. "does not make sense when using DESTDIR. Specify "
  1854. "absolute path or remove DESTDIR environment variable.");
  1855. return false;
  1856. }
  1857. } else {
  1858. if (ch2 == '/') {
  1859. // looks like a network path.
  1860. std::string message =
  1861. "called with network path DESTINATION. This "
  1862. "does not make sense when using DESTDIR. Specify local "
  1863. "absolute path or remove DESTDIR environment variable."
  1864. "\nDESTINATION=\n";
  1865. message += destination;
  1866. this->FileCommand->SetError(message);
  1867. return false;
  1868. }
  1869. }
  1870. destination = sdestdir + (destination.c_str() + skip);
  1871. this->DestDirLength = int(sdestdir.size());
  1872. }
  1873. if (this->InstallType != cmInstallType_DIRECTORY) {
  1874. if (!cmSystemTools::FileExists(destination.c_str())) {
  1875. if (!cmSystemTools::MakeDirectory(destination.c_str())) {
  1876. std::string errstring = "cannot create directory: " + destination +
  1877. ". Maybe need administrative privileges.";
  1878. this->FileCommand->SetError(errstring);
  1879. return false;
  1880. }
  1881. }
  1882. if (!cmSystemTools::FileIsDirectory(destination)) {
  1883. std::string errstring =
  1884. "INSTALL destination: " + destination + " is not a directory.";
  1885. this->FileCommand->SetError(errstring);
  1886. return false;
  1887. }
  1888. }
  1889. return true;
  1890. }
  1891. bool cmFileCommand::HandleRPathChangeCommand(
  1892. std::vector<std::string> const& args)
  1893. {
  1894. // Evaluate arguments.
  1895. const char* file = nullptr;
  1896. const char* oldRPath = nullptr;
  1897. const char* newRPath = nullptr;
  1898. enum Doing
  1899. {
  1900. DoingNone,
  1901. DoingFile,
  1902. DoingOld,
  1903. DoingNew
  1904. };
  1905. Doing doing = DoingNone;
  1906. for (unsigned int i = 1; i < args.size(); ++i) {
  1907. if (args[i] == "OLD_RPATH") {
  1908. doing = DoingOld;
  1909. } else if (args[i] == "NEW_RPATH") {
  1910. doing = DoingNew;
  1911. } else if (args[i] == "FILE") {
  1912. doing = DoingFile;
  1913. } else if (doing == DoingFile) {
  1914. file = args[i].c_str();
  1915. doing = DoingNone;
  1916. } else if (doing == DoingOld) {
  1917. oldRPath = args[i].c_str();
  1918. doing = DoingNone;
  1919. } else if (doing == DoingNew) {
  1920. newRPath = args[i].c_str();
  1921. doing = DoingNone;
  1922. } else {
  1923. std::ostringstream e;
  1924. e << "RPATH_CHANGE given unknown argument " << args[i];
  1925. this->SetError(e.str());
  1926. return false;
  1927. }
  1928. }
  1929. if (!file) {
  1930. this->SetError("RPATH_CHANGE not given FILE option.");
  1931. return false;
  1932. }
  1933. if (!oldRPath) {
  1934. this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
  1935. return false;
  1936. }
  1937. if (!newRPath) {
  1938. this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
  1939. return false;
  1940. }
  1941. if (!cmSystemTools::FileExists(file, true)) {
  1942. std::ostringstream e;
  1943. e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
  1944. this->SetError(e.str());
  1945. return false;
  1946. }
  1947. bool success = true;
  1948. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  1949. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  1950. std::string emsg;
  1951. bool changed;
  1952. if (!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed)) {
  1953. std::ostringstream e;
  1954. /* clang-format off */
  1955. e << "RPATH_CHANGE could not write new RPATH:\n"
  1956. << " " << newRPath << "\n"
  1957. << "to the file:\n"
  1958. << " " << file << "\n"
  1959. << emsg;
  1960. /* clang-format on */
  1961. this->SetError(e.str());
  1962. success = false;
  1963. }
  1964. if (success) {
  1965. if (changed) {
  1966. std::string message = "Set runtime path of \"";
  1967. message += file;
  1968. message += "\" to \"";
  1969. message += newRPath;
  1970. message += "\"";
  1971. this->Makefile->DisplayStatus(message.c_str(), -1);
  1972. }
  1973. if (have_ft) {
  1974. cmSystemTools::FileTimeSet(file, ft);
  1975. }
  1976. }
  1977. cmSystemTools::FileTimeDelete(ft);
  1978. return success;
  1979. }
  1980. bool cmFileCommand::HandleRPathRemoveCommand(
  1981. std::vector<std::string> const& args)
  1982. {
  1983. // Evaluate arguments.
  1984. const char* file = nullptr;
  1985. enum Doing
  1986. {
  1987. DoingNone,
  1988. DoingFile
  1989. };
  1990. Doing doing = DoingNone;
  1991. for (unsigned int i = 1; i < args.size(); ++i) {
  1992. if (args[i] == "FILE") {
  1993. doing = DoingFile;
  1994. } else if (doing == DoingFile) {
  1995. file = args[i].c_str();
  1996. doing = DoingNone;
  1997. } else {
  1998. std::ostringstream e;
  1999. e << "RPATH_REMOVE given unknown argument " << args[i];
  2000. this->SetError(e.str());
  2001. return false;
  2002. }
  2003. }
  2004. if (!file) {
  2005. this->SetError("RPATH_REMOVE not given FILE option.");
  2006. return false;
  2007. }
  2008. if (!cmSystemTools::FileExists(file, true)) {
  2009. std::ostringstream e;
  2010. e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
  2011. this->SetError(e.str());
  2012. return false;
  2013. }
  2014. bool success = true;
  2015. cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
  2016. bool have_ft = cmSystemTools::FileTimeGet(file, ft);
  2017. std::string emsg;
  2018. bool removed;
  2019. if (!cmSystemTools::RemoveRPath(file, &emsg, &removed)) {
  2020. std::ostringstream e;
  2021. /* clang-format off */
  2022. e << "RPATH_REMOVE could not remove RPATH from file:\n"
  2023. << " " << file << "\n"
  2024. << emsg;
  2025. /* clang-format on */
  2026. this->SetError(e.str());
  2027. success = false;
  2028. }
  2029. if (success) {
  2030. if (removed) {
  2031. std::string message = "Removed runtime path from \"";
  2032. message += file;
  2033. message += "\"";
  2034. this->Makefile->DisplayStatus(message.c_str(), -1);
  2035. }
  2036. if (have_ft) {
  2037. cmSystemTools::FileTimeSet(file, ft);
  2038. }
  2039. }
  2040. cmSystemTools::FileTimeDelete(ft);
  2041. return success;
  2042. }
  2043. bool cmFileCommand::HandleRPathCheckCommand(
  2044. std::vector<std::string> const& args)
  2045. {
  2046. // Evaluate arguments.
  2047. const char* file = nullptr;
  2048. const char* rpath = nullptr;
  2049. enum Doing
  2050. {
  2051. DoingNone,
  2052. DoingFile,
  2053. DoingRPath
  2054. };
  2055. Doing doing = DoingNone;
  2056. for (unsigned int i = 1; i < args.size(); ++i) {
  2057. if (args[i] == "RPATH") {
  2058. doing = DoingRPath;
  2059. } else if (args[i] == "FILE") {
  2060. doing = DoingFile;
  2061. } else if (doing == DoingFile) {
  2062. file = args[i].c_str();
  2063. doing = DoingNone;
  2064. } else if (doing == DoingRPath) {
  2065. rpath = args[i].c_str();
  2066. doing = DoingNone;
  2067. } else {
  2068. std::ostringstream e;
  2069. e << "RPATH_CHECK given unknown argument " << args[i];
  2070. this->SetError(e.str());
  2071. return false;
  2072. }
  2073. }
  2074. if (!file) {
  2075. this->SetError("RPATH_CHECK not given FILE option.");
  2076. return false;
  2077. }
  2078. if (!rpath) {
  2079. this->SetError("RPATH_CHECK not given RPATH option.");
  2080. return false;
  2081. }
  2082. // If the file exists but does not have the desired RPath then
  2083. // delete it. This is used during installation to re-install a file
  2084. // if its RPath will change.
  2085. if (cmSystemTools::FileExists(file, true) &&
  2086. !cmSystemTools::CheckRPath(file, rpath)) {
  2087. cmSystemTools::RemoveFile(file);
  2088. }
  2089. return true;
  2090. }
  2091. bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args)
  2092. {
  2093. if (args.size() < 4) {
  2094. this->SetError("READ_ELF must be called with at least three additional "
  2095. "arguments.");
  2096. return false;
  2097. }
  2098. cmCommandArgumentsHelper argHelper;
  2099. cmCommandArgumentGroup group;
  2100. cmCAString readArg(&argHelper, "READ_ELF");
  2101. cmCAString fileNameArg(&argHelper, nullptr);
  2102. cmCAString rpathArg(&argHelper, "RPATH", &group);
  2103. cmCAString runpathArg(&argHelper, "RUNPATH", &group);
  2104. cmCAString errorArg(&argHelper, "CAPTURE_ERROR", &group);
  2105. readArg.Follows(nullptr);
  2106. fileNameArg.Follows(&readArg);
  2107. group.Follows(&fileNameArg);
  2108. argHelper.Parse(&args, nullptr);
  2109. if (!cmSystemTools::FileExists(fileNameArg.GetString(), true)) {
  2110. std::ostringstream e;
  2111. e << "READ_ELF given FILE \"" << fileNameArg.GetString()
  2112. << "\" that does not exist.";
  2113. this->SetError(e.str());
  2114. return false;
  2115. }
  2116. #if defined(CMAKE_USE_ELF_PARSER)
  2117. cmELF elf(fileNameArg.GetCString());
  2118. if (!rpathArg.GetString().empty()) {
  2119. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  2120. std::string rpath(se_rpath->Value);
  2121. std::replace(rpath.begin(), rpath.end(), ':', ';');
  2122. this->Makefile->AddDefinition(rpathArg.GetString(), rpath.c_str());
  2123. }
  2124. }
  2125. if (!runpathArg.GetString().empty()) {
  2126. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  2127. std::string runpath(se_runpath->Value);
  2128. std::replace(runpath.begin(), runpath.end(), ':', ';');
  2129. this->Makefile->AddDefinition(runpathArg.GetString(), runpath.c_str());
  2130. }
  2131. }
  2132. return true;
  2133. #else
  2134. std::string error = "ELF parser not available on this platform.";
  2135. if (errorArg.GetString().empty()) {
  2136. this->SetError(error);
  2137. return false;
  2138. } else {
  2139. this->Makefile->AddDefinition(errorArg.GetString(), error.c_str());
  2140. return true;
  2141. }
  2142. #endif
  2143. }
  2144. bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
  2145. {
  2146. cmFileInstaller installer(this);
  2147. return installer.Run(args);
  2148. }
  2149. bool cmFileCommand::HandleRelativePathCommand(
  2150. std::vector<std::string> const& args)
  2151. {
  2152. if (args.size() != 4) {
  2153. this->SetError("RELATIVE_PATH called with incorrect number of arguments");
  2154. return false;
  2155. }
  2156. const std::string& outVar = args[1];
  2157. const std::string& directoryName = args[2];
  2158. const std::string& fileName = args[3];
  2159. if (!cmSystemTools::FileIsFullPath(directoryName.c_str())) {
  2160. std::string errstring =
  2161. "RELATIVE_PATH must be passed a full path to the directory: " +
  2162. directoryName;
  2163. this->SetError(errstring);
  2164. return false;
  2165. }
  2166. if (!cmSystemTools::FileIsFullPath(fileName.c_str())) {
  2167. std::string errstring =
  2168. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  2169. this->SetError(errstring);
  2170. return false;
  2171. }
  2172. std::string res =
  2173. cmSystemTools::RelativePath(directoryName.c_str(), fileName.c_str());
  2174. this->Makefile->AddDefinition(outVar, res.c_str());
  2175. return true;
  2176. }
  2177. bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
  2178. {
  2179. if (args.size() != 3) {
  2180. this->SetError("RENAME given incorrect number of arguments.");
  2181. return false;
  2182. }
  2183. // Compute full path for old and new names.
  2184. std::string oldname = args[1];
  2185. if (!cmsys::SystemTools::FileIsFullPath(oldname.c_str())) {
  2186. oldname = this->Makefile->GetCurrentSourceDirectory();
  2187. oldname += "/" + args[1];
  2188. }
  2189. std::string newname = args[2];
  2190. if (!cmsys::SystemTools::FileIsFullPath(newname.c_str())) {
  2191. newname = this->Makefile->GetCurrentSourceDirectory();
  2192. newname += "/" + args[2];
  2193. }
  2194. if (!cmSystemTools::RenameFile(oldname.c_str(), newname.c_str())) {
  2195. std::string err = cmSystemTools::GetLastSystemError();
  2196. std::ostringstream e;
  2197. /* clang-format off */
  2198. e << "RENAME failed to rename\n"
  2199. << " " << oldname << "\n"
  2200. << "to\n"
  2201. << " " << newname << "\n"
  2202. << "because: " << err << "\n";
  2203. /* clang-format on */
  2204. this->SetError(e.str());
  2205. return false;
  2206. }
  2207. return true;
  2208. }
  2209. bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
  2210. bool recurse)
  2211. {
  2212. std::string message;
  2213. std::vector<std::string>::const_iterator i = args.begin();
  2214. i++; // Get rid of subcommand
  2215. for (; i != args.end(); ++i) {
  2216. std::string fileName = *i;
  2217. if (!cmsys::SystemTools::FileIsFullPath(fileName.c_str())) {
  2218. fileName = this->Makefile->GetCurrentSourceDirectory();
  2219. fileName += "/" + *i;
  2220. }
  2221. if (cmSystemTools::FileIsDirectory(fileName) &&
  2222. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  2223. cmSystemTools::RemoveADirectory(fileName);
  2224. } else {
  2225. cmSystemTools::RemoveFile(fileName);
  2226. }
  2227. }
  2228. return true;
  2229. }
  2230. bool cmFileCommand::HandleCMakePathCommand(
  2231. std::vector<std::string> const& args, bool nativePath)
  2232. {
  2233. std::vector<std::string>::const_iterator i = args.begin();
  2234. if (args.size() != 3) {
  2235. this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  2236. "called with exactly three arguments.");
  2237. return false;
  2238. }
  2239. i++; // Get rid of subcommand
  2240. #if defined(_WIN32) && !defined(__CYGWIN__)
  2241. char pathSep = ';';
  2242. #else
  2243. char pathSep = ':';
  2244. #endif
  2245. std::vector<cmsys::String> path = cmSystemTools::SplitString(*i, pathSep);
  2246. i++;
  2247. const char* var = i->c_str();
  2248. std::string value;
  2249. for (std::vector<cmsys::String>::iterator j = path.begin(); j != path.end();
  2250. ++j) {
  2251. if (j != path.begin()) {
  2252. value += ";";
  2253. }
  2254. if (!nativePath) {
  2255. cmSystemTools::ConvertToUnixSlashes(*j);
  2256. } else {
  2257. *j = cmSystemTools::ConvertToOutputPath(j->c_str());
  2258. // remove double quotes in the path
  2259. cmsys::String& s = *j;
  2260. if (s.size() > 1 && s[0] == '\"' && s[s.size() - 1] == '\"') {
  2261. s = s.substr(1, s.size() - 2);
  2262. }
  2263. }
  2264. value += *j;
  2265. }
  2266. this->Makefile->AddDefinition(var, value.c_str());
  2267. return true;
  2268. }
  2269. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2270. // Stuff for curl download/upload
  2271. typedef std::vector<char> cmFileCommandVectorOfChar;
  2272. namespace {
  2273. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  2274. {
  2275. int realsize = static_cast<int>(size * nmemb);
  2276. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  2277. const char* chPtr = static_cast<char*>(ptr);
  2278. fout->write(chPtr, realsize);
  2279. return realsize;
  2280. }
  2281. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  2282. void* data)
  2283. {
  2284. int realsize = static_cast<int>(size * nmemb);
  2285. cmFileCommandVectorOfChar* vec =
  2286. static_cast<cmFileCommandVectorOfChar*>(data);
  2287. const char* chPtr = static_cast<char*>(ptr);
  2288. vec->insert(vec->end(), chPtr, chPtr + realsize);
  2289. return realsize;
  2290. }
  2291. size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  2292. size_t size, void* data)
  2293. {
  2294. cmFileCommandVectorOfChar* vec =
  2295. static_cast<cmFileCommandVectorOfChar*>(data);
  2296. switch (type) {
  2297. case CURLINFO_TEXT:
  2298. case CURLINFO_HEADER_IN:
  2299. case CURLINFO_HEADER_OUT:
  2300. vec->insert(vec->end(), chPtr, chPtr + size);
  2301. break;
  2302. case CURLINFO_DATA_IN:
  2303. case CURLINFO_DATA_OUT:
  2304. case CURLINFO_SSL_DATA_IN:
  2305. case CURLINFO_SSL_DATA_OUT: {
  2306. char buf[128];
  2307. int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
  2308. static_cast<KWIML_INT_uint64_t>(size));
  2309. if (n > 0) {
  2310. vec->insert(vec->end(), buf, buf + n);
  2311. }
  2312. } break;
  2313. default:
  2314. break;
  2315. }
  2316. return 0;
  2317. }
  2318. class cURLProgressHelper
  2319. {
  2320. public:
  2321. cURLProgressHelper(cmFileCommand* fc, const char* text)
  2322. {
  2323. this->CurrentPercentage = -1;
  2324. this->FileCommand = fc;
  2325. this->Text = text;
  2326. }
  2327. bool UpdatePercentage(double value, double total, std::string& status)
  2328. {
  2329. int OldPercentage = this->CurrentPercentage;
  2330. if (total > 0.0) {
  2331. this->CurrentPercentage = static_cast<int>(value / total * 100.0 + 0.5);
  2332. if (this->CurrentPercentage > 100) {
  2333. // Avoid extra progress reports for unexpected data beyond total.
  2334. this->CurrentPercentage = 100;
  2335. }
  2336. }
  2337. bool updated = (OldPercentage != this->CurrentPercentage);
  2338. if (updated) {
  2339. std::ostringstream oss;
  2340. oss << "[" << this->Text << " " << this->CurrentPercentage
  2341. << "% complete]";
  2342. status = oss.str();
  2343. }
  2344. return updated;
  2345. }
  2346. cmFileCommand* GetFileCommand() { return this->FileCommand; }
  2347. private:
  2348. int CurrentPercentage;
  2349. cmFileCommand* FileCommand;
  2350. std::string Text;
  2351. };
  2352. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  2353. double ultotal, double ulnow)
  2354. {
  2355. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  2356. static_cast<void>(ultotal);
  2357. static_cast<void>(ulnow);
  2358. std::string status;
  2359. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  2360. cmFileCommand* fc = helper->GetFileCommand();
  2361. cmMakefile* mf = fc->GetMakefile();
  2362. mf->DisplayStatus(status.c_str(), -1);
  2363. }
  2364. return 0;
  2365. }
  2366. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  2367. double ultotal, double ulnow)
  2368. {
  2369. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  2370. static_cast<void>(dltotal);
  2371. static_cast<void>(dlnow);
  2372. std::string status;
  2373. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  2374. cmFileCommand* fc = helper->GetFileCommand();
  2375. cmMakefile* mf = fc->GetMakefile();
  2376. mf->DisplayStatus(status.c_str(), -1);
  2377. }
  2378. return 0;
  2379. }
  2380. }
  2381. namespace {
  2382. class cURLEasyGuard
  2383. {
  2384. public:
  2385. cURLEasyGuard(CURL* easy)
  2386. : Easy(easy)
  2387. {
  2388. }
  2389. ~cURLEasyGuard()
  2390. {
  2391. if (this->Easy) {
  2392. ::curl_easy_cleanup(this->Easy);
  2393. }
  2394. }
  2395. void release() { this->Easy = nullptr; }
  2396. private:
  2397. ::CURL* Easy;
  2398. };
  2399. }
  2400. #endif
  2401. #define check_curl_result(result, errstr) \
  2402. if (result != CURLE_OK) { \
  2403. std::string e(errstr); \
  2404. e += ::curl_easy_strerror(result); \
  2405. this->SetError(e); \
  2406. return false; \
  2407. }
  2408. bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
  2409. {
  2410. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2411. std::vector<std::string>::const_iterator i = args.begin();
  2412. if (args.size() < 3) {
  2413. this->SetError("DOWNLOAD must be called with at least three arguments.");
  2414. return false;
  2415. }
  2416. ++i; // Get rid of subcommand
  2417. std::string url = *i;
  2418. ++i;
  2419. std::string file = *i;
  2420. ++i;
  2421. long timeout = 0;
  2422. long inactivity_timeout = 0;
  2423. std::string logVar;
  2424. std::string statusVar;
  2425. bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
  2426. const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
  2427. std::string expectedHash;
  2428. std::string hashMatchMSG;
  2429. CM_AUTO_PTR<cmCryptoHash> hash;
  2430. bool showProgress = false;
  2431. std::string userpwd;
  2432. std::vector<std::string> curl_headers;
  2433. while (i != args.end()) {
  2434. if (*i == "TIMEOUT") {
  2435. ++i;
  2436. if (i != args.end()) {
  2437. timeout = atol(i->c_str());
  2438. } else {
  2439. this->SetError("DOWNLOAD missing time for TIMEOUT.");
  2440. return false;
  2441. }
  2442. } else if (*i == "INACTIVITY_TIMEOUT") {
  2443. ++i;
  2444. if (i != args.end()) {
  2445. inactivity_timeout = atol(i->c_str());
  2446. } else {
  2447. this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  2448. return false;
  2449. }
  2450. } else if (*i == "LOG") {
  2451. ++i;
  2452. if (i == args.end()) {
  2453. this->SetError("DOWNLOAD missing VAR for LOG.");
  2454. return false;
  2455. }
  2456. logVar = *i;
  2457. } else if (*i == "STATUS") {
  2458. ++i;
  2459. if (i == args.end()) {
  2460. this->SetError("DOWNLOAD missing VAR for STATUS.");
  2461. return false;
  2462. }
  2463. statusVar = *i;
  2464. } else if (*i == "TLS_VERIFY") {
  2465. ++i;
  2466. if (i != args.end()) {
  2467. tls_verify = cmSystemTools::IsOn(i->c_str());
  2468. } else {
  2469. this->SetError("TLS_VERIFY missing bool value.");
  2470. return false;
  2471. }
  2472. } else if (*i == "TLS_CAINFO") {
  2473. ++i;
  2474. if (i != args.end()) {
  2475. cainfo = i->c_str();
  2476. } else {
  2477. this->SetError("TLS_CAFILE missing file value.");
  2478. return false;
  2479. }
  2480. } else if (*i == "EXPECTED_MD5") {
  2481. ++i;
  2482. if (i == args.end()) {
  2483. this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  2484. return false;
  2485. }
  2486. hash =
  2487. CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(cmCryptoHash::AlgoMD5));
  2488. hashMatchMSG = "MD5 sum";
  2489. expectedHash = cmSystemTools::LowerCase(*i);
  2490. } else if (*i == "SHOW_PROGRESS") {
  2491. showProgress = true;
  2492. } else if (*i == "EXPECTED_HASH") {
  2493. ++i;
  2494. if (i == args.end()) {
  2495. this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  2496. return false;
  2497. }
  2498. std::string::size_type pos = i->find("=");
  2499. if (pos == std::string::npos) {
  2500. std::string err =
  2501. "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
  2502. err += *i;
  2503. this->SetError(err);
  2504. return false;
  2505. }
  2506. std::string algo = i->substr(0, pos);
  2507. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  2508. hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
  2509. if (!hash.get()) {
  2510. std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
  2511. err += algo;
  2512. this->SetError(err);
  2513. return false;
  2514. }
  2515. hashMatchMSG = algo + " hash";
  2516. } else if (*i == "USERPWD") {
  2517. ++i;
  2518. if (i == args.end()) {
  2519. this->SetError("DOWNLOAD missing string for USERPWD.");
  2520. return false;
  2521. }
  2522. userpwd = *i;
  2523. } else if (*i == "HTTPHEADER") {
  2524. ++i;
  2525. if (i == args.end()) {
  2526. this->SetError("DOWNLOAD missing string for HTTPHEADER.");
  2527. return false;
  2528. }
  2529. curl_headers.push_back(*i);
  2530. } else {
  2531. // Do not return error for compatibility reason.
  2532. std::string err = "Unexpected argument: ";
  2533. err += *i;
  2534. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err);
  2535. }
  2536. ++i;
  2537. }
  2538. // If file exists already, and caller specified an expected md5 or sha,
  2539. // and the existing file already has the expected hash, then simply
  2540. // return.
  2541. //
  2542. if (cmSystemTools::FileExists(file.c_str()) && hash.get()) {
  2543. std::string msg;
  2544. std::string actualHash = hash->HashFile(file);
  2545. if (actualHash == expectedHash) {
  2546. msg = "returning early; file already exists with expected ";
  2547. msg += hashMatchMSG;
  2548. msg += "\"";
  2549. if (!statusVar.empty()) {
  2550. std::ostringstream result;
  2551. result << 0 << ";\"" << msg;
  2552. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  2553. }
  2554. return true;
  2555. }
  2556. }
  2557. // Make sure parent directory exists so we can write to the file
  2558. // as we receive downloaded bits from curl...
  2559. //
  2560. std::string dir = cmSystemTools::GetFilenamePath(file);
  2561. if (!cmSystemTools::FileExists(dir.c_str()) &&
  2562. !cmSystemTools::MakeDirectory(dir.c_str())) {
  2563. std::string errstring = "DOWNLOAD error: cannot create directory '" + dir +
  2564. "' - Specify file by full path name and verify that you "
  2565. "have directory creation and file write privileges.";
  2566. this->SetError(errstring);
  2567. return false;
  2568. }
  2569. cmsys::ofstream fout(file.c_str(), std::ios::binary);
  2570. if (!fout) {
  2571. this->SetError("DOWNLOAD cannot open file for write.");
  2572. return false;
  2573. }
  2574. #if defined(_WIN32)
  2575. url = fix_file_url_windows(url);
  2576. #endif
  2577. ::CURL* curl;
  2578. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2579. curl = ::curl_easy_init();
  2580. if (!curl) {
  2581. this->SetError("DOWNLOAD error initializing curl.");
  2582. return false;
  2583. }
  2584. cURLEasyGuard g_curl(curl);
  2585. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2586. check_curl_result(res, "DOWNLOAD cannot set url: ");
  2587. // enable HTTP ERROR parsing
  2588. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2589. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  2590. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  2591. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  2592. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  2593. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  2594. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2595. cmFileCommandCurlDebugCallback);
  2596. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  2597. // check to see if TLS verification is requested
  2598. if (tls_verify) {
  2599. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2600. check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
  2601. } else {
  2602. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2603. check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
  2604. }
  2605. // check to see if a CAINFO file has been specified
  2606. // command arg comes first
  2607. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2608. if (!cainfo_err.empty()) {
  2609. this->SetError(cainfo_err);
  2610. return false;
  2611. }
  2612. cmFileCommandVectorOfChar chunkDebug;
  2613. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fout);
  2614. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  2615. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2616. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  2617. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2618. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  2619. if (!logVar.empty()) {
  2620. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2621. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  2622. }
  2623. if (timeout > 0) {
  2624. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2625. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  2626. }
  2627. if (inactivity_timeout > 0) {
  2628. // Give up if there is no progress for a long time.
  2629. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2630. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2631. }
  2632. // Need the progress helper's scope to last through the duration of
  2633. // the curl_easy_perform call... so this object is declared at function
  2634. // scope intentionally, rather than inside the "if(showProgress)"
  2635. // block...
  2636. //
  2637. cURLProgressHelper helper(this, "download");
  2638. if (showProgress) {
  2639. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2640. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  2641. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  2642. cmFileDownloadProgressCallback);
  2643. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  2644. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2645. reinterpret_cast<void*>(&helper));
  2646. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  2647. }
  2648. if (!userpwd.empty()) {
  2649. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2650. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  2651. }
  2652. struct curl_slist* headers = nullptr;
  2653. for (std::vector<std::string>::const_iterator h = curl_headers.begin();
  2654. h != curl_headers.end(); ++h) {
  2655. headers = ::curl_slist_append(headers, h->c_str());
  2656. }
  2657. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2658. res = ::curl_easy_perform(curl);
  2659. ::curl_slist_free_all(headers);
  2660. /* always cleanup */
  2661. g_curl.release();
  2662. ::curl_easy_cleanup(curl);
  2663. if (!statusVar.empty()) {
  2664. std::ostringstream result;
  2665. result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
  2666. << "\"";
  2667. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  2668. }
  2669. ::curl_global_cleanup();
  2670. // Explicitly flush/close so we can measure the md5 accurately.
  2671. //
  2672. fout.flush();
  2673. fout.close();
  2674. // Verify MD5 sum if requested:
  2675. //
  2676. if (hash.get()) {
  2677. std::string actualHash = hash->HashFile(file);
  2678. if (actualHash.empty()) {
  2679. this->SetError("DOWNLOAD cannot compute hash on downloaded file");
  2680. return false;
  2681. }
  2682. if (expectedHash != actualHash) {
  2683. std::ostringstream oss;
  2684. oss << "DOWNLOAD HASH mismatch" << std::endl
  2685. << " for file: [" << file << "]" << std::endl
  2686. << " expected hash: [" << expectedHash << "]" << std::endl
  2687. << " actual hash: [" << actualHash << "]" << std::endl
  2688. << " status: [" << static_cast<int>(res) << ";\""
  2689. << ::curl_easy_strerror(res) << "\"]" << std::endl;
  2690. if (!statusVar.empty() && res == 0) {
  2691. std::string status = "1;HASH mismatch: "
  2692. "expected: " +
  2693. expectedHash + " actual: " + actualHash;
  2694. this->Makefile->AddDefinition(statusVar, status.c_str());
  2695. }
  2696. this->SetError(oss.str());
  2697. return false;
  2698. }
  2699. }
  2700. if (!logVar.empty()) {
  2701. chunkDebug.push_back(0);
  2702. this->Makefile->AddDefinition(logVar, &*chunkDebug.begin());
  2703. }
  2704. return true;
  2705. #else
  2706. this->SetError("DOWNLOAD not supported by bootstrap cmake.");
  2707. return false;
  2708. #endif
  2709. }
  2710. bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
  2711. {
  2712. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2713. if (args.size() < 3) {
  2714. this->SetError("UPLOAD must be called with at least three arguments.");
  2715. return false;
  2716. }
  2717. std::vector<std::string>::const_iterator i = args.begin();
  2718. ++i;
  2719. std::string filename = *i;
  2720. ++i;
  2721. std::string url = *i;
  2722. ++i;
  2723. long timeout = 0;
  2724. long inactivity_timeout = 0;
  2725. std::string logVar;
  2726. std::string statusVar;
  2727. bool showProgress = false;
  2728. std::string userpwd;
  2729. std::vector<std::string> curl_headers;
  2730. while (i != args.end()) {
  2731. if (*i == "TIMEOUT") {
  2732. ++i;
  2733. if (i != args.end()) {
  2734. timeout = atol(i->c_str());
  2735. } else {
  2736. this->SetError("UPLOAD missing time for TIMEOUT.");
  2737. return false;
  2738. }
  2739. } else if (*i == "INACTIVITY_TIMEOUT") {
  2740. ++i;
  2741. if (i != args.end()) {
  2742. inactivity_timeout = atol(i->c_str());
  2743. } else {
  2744. this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  2745. return false;
  2746. }
  2747. } else if (*i == "LOG") {
  2748. ++i;
  2749. if (i == args.end()) {
  2750. this->SetError("UPLOAD missing VAR for LOG.");
  2751. return false;
  2752. }
  2753. logVar = *i;
  2754. } else if (*i == "STATUS") {
  2755. ++i;
  2756. if (i == args.end()) {
  2757. this->SetError("UPLOAD missing VAR for STATUS.");
  2758. return false;
  2759. }
  2760. statusVar = *i;
  2761. } else if (*i == "SHOW_PROGRESS") {
  2762. showProgress = true;
  2763. } else if (*i == "USERPWD") {
  2764. ++i;
  2765. if (i == args.end()) {
  2766. this->SetError("UPLOAD missing string for USERPWD.");
  2767. return false;
  2768. }
  2769. userpwd = *i;
  2770. } else if (*i == "HTTPHEADER") {
  2771. ++i;
  2772. if (i == args.end()) {
  2773. this->SetError("UPLOAD missing string for HTTPHEADER.");
  2774. return false;
  2775. }
  2776. curl_headers.push_back(*i);
  2777. } else {
  2778. // Do not return error for compatibility reason.
  2779. std::string err = "Unexpected argument: ";
  2780. err += *i;
  2781. this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err);
  2782. }
  2783. ++i;
  2784. }
  2785. // Open file for reading:
  2786. //
  2787. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  2788. if (!fin) {
  2789. std::string errStr = "UPLOAD cannot open file '";
  2790. errStr += filename + "' for reading.";
  2791. this->SetError(errStr);
  2792. return false;
  2793. }
  2794. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  2795. #if defined(_WIN32)
  2796. url = fix_file_url_windows(url);
  2797. #endif
  2798. ::CURL* curl;
  2799. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2800. curl = ::curl_easy_init();
  2801. if (!curl) {
  2802. this->SetError("UPLOAD error initializing curl.");
  2803. fclose(fin);
  2804. return false;
  2805. }
  2806. cURLEasyGuard g_curl(curl);
  2807. // enable HTTP ERROR parsing
  2808. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2809. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  2810. // enable uploading
  2811. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  2812. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  2813. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2814. check_curl_result(res, "UPLOAD cannot set url: ");
  2815. res =
  2816. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  2817. check_curl_result(res, "UPLOAD cannot set write function: ");
  2818. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2819. cmFileCommandCurlDebugCallback);
  2820. check_curl_result(res, "UPLOAD cannot set debug function: ");
  2821. cmFileCommandVectorOfChar chunkResponse;
  2822. cmFileCommandVectorOfChar chunkDebug;
  2823. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  2824. check_curl_result(res, "UPLOAD cannot set write data: ");
  2825. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2826. check_curl_result(res, "UPLOAD cannot set debug data: ");
  2827. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2828. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  2829. if (!logVar.empty()) {
  2830. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2831. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2832. }
  2833. if (timeout > 0) {
  2834. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2835. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2836. }
  2837. if (inactivity_timeout > 0) {
  2838. // Give up if there is no progress for a long time.
  2839. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2840. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2841. }
  2842. // Need the progress helper's scope to last through the duration of
  2843. // the curl_easy_perform call... so this object is declared at function
  2844. // scope intentionally, rather than inside the "if(showProgress)"
  2845. // block...
  2846. //
  2847. cURLProgressHelper helper(this, "upload");
  2848. if (showProgress) {
  2849. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2850. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2851. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  2852. cmFileUploadProgressCallback);
  2853. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2854. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2855. reinterpret_cast<void*>(&helper));
  2856. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2857. }
  2858. // now specify which file to upload
  2859. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2860. check_curl_result(res, "UPLOAD cannot set input file: ");
  2861. // and give the size of the upload (optional)
  2862. res =
  2863. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2864. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2865. if (!userpwd.empty()) {
  2866. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2867. check_curl_result(res, "UPLOAD cannot set user password: ");
  2868. }
  2869. struct curl_slist* headers = nullptr;
  2870. for (std::vector<std::string>::const_iterator h = curl_headers.begin();
  2871. h != curl_headers.end(); ++h) {
  2872. headers = ::curl_slist_append(headers, h->c_str());
  2873. }
  2874. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2875. res = ::curl_easy_perform(curl);
  2876. ::curl_slist_free_all(headers);
  2877. /* always cleanup */
  2878. g_curl.release();
  2879. ::curl_easy_cleanup(curl);
  2880. if (!statusVar.empty()) {
  2881. std::ostringstream result;
  2882. result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
  2883. << "\"";
  2884. this->Makefile->AddDefinition(statusVar, result.str().c_str());
  2885. }
  2886. ::curl_global_cleanup();
  2887. fclose(fin);
  2888. fin = nullptr;
  2889. if (!logVar.empty()) {
  2890. std::string log;
  2891. if (!chunkResponse.empty()) {
  2892. chunkResponse.push_back(0);
  2893. log += "Response:\n";
  2894. log += &*chunkResponse.begin();
  2895. log += "\n";
  2896. }
  2897. if (!chunkDebug.empty()) {
  2898. chunkDebug.push_back(0);
  2899. log += "Debug:\n";
  2900. log += &*chunkDebug.begin();
  2901. log += "\n";
  2902. }
  2903. this->Makefile->AddDefinition(logVar, log.c_str());
  2904. }
  2905. return true;
  2906. #else
  2907. this->SetError("UPLOAD not supported by bootstrap cmake.");
  2908. return false;
  2909. #endif
  2910. }
  2911. void cmFileCommand::AddEvaluationFile(const std::string& inputName,
  2912. const std::string& outputExpr,
  2913. const std::string& condition,
  2914. bool inputIsContent)
  2915. {
  2916. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2917. cmGeneratorExpression outputGe(lfbt);
  2918. CM_AUTO_PTR<cmCompiledGeneratorExpression> outputCge =
  2919. outputGe.Parse(outputExpr);
  2920. cmGeneratorExpression conditionGe(lfbt);
  2921. CM_AUTO_PTR<cmCompiledGeneratorExpression> conditionCge =
  2922. conditionGe.Parse(condition);
  2923. this->Makefile->AddEvaluationFile(inputName, outputCge, conditionCge,
  2924. inputIsContent);
  2925. }
  2926. bool cmFileCommand::HandleGenerateCommand(std::vector<std::string> const& args)
  2927. {
  2928. if (args.size() < 5) {
  2929. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2930. return false;
  2931. }
  2932. if (args[1] != "OUTPUT") {
  2933. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2934. return false;
  2935. }
  2936. std::string condition;
  2937. if (args.size() > 5) {
  2938. if (args[5] != "CONDITION") {
  2939. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2940. return false;
  2941. }
  2942. if (args.size() != 7) {
  2943. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2944. return false;
  2945. }
  2946. condition = args[6];
  2947. if (condition.empty()) {
  2948. this->SetError("CONDITION of sub-command GENERATE must not be empty if "
  2949. "specified.");
  2950. return false;
  2951. }
  2952. }
  2953. std::string output = args[2];
  2954. const bool inputIsContent = args[3] != "INPUT";
  2955. if (inputIsContent && args[3] != "CONTENT") {
  2956. this->SetError("Incorrect arguments to GENERATE subcommand.");
  2957. return false;
  2958. }
  2959. std::string input = args[4];
  2960. this->AddEvaluationFile(input, output, condition, inputIsContent);
  2961. return true;
  2962. }
  2963. bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args)
  2964. {
  2965. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2966. // Default values
  2967. bool directory = false;
  2968. bool release = false;
  2969. enum Guard
  2970. {
  2971. GUARD_FUNCTION,
  2972. GUARD_FILE,
  2973. GUARD_PROCESS
  2974. };
  2975. Guard guard = GUARD_PROCESS;
  2976. std::string resultVariable;
  2977. unsigned long timeout = static_cast<unsigned long>(-1);
  2978. // Parse arguments
  2979. if (args.size() < 2) {
  2980. this->Makefile->IssueMessage(
  2981. cmake::FATAL_ERROR, "sub-command LOCK requires at least two arguments.");
  2982. return false;
  2983. }
  2984. std::string path = args[1];
  2985. for (unsigned i = 2; i < args.size(); ++i) {
  2986. if (args[i] == "DIRECTORY") {
  2987. directory = true;
  2988. } else if (args[i] == "RELEASE") {
  2989. release = true;
  2990. } else if (args[i] == "GUARD") {
  2991. ++i;
  2992. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2993. if (i >= args.size()) {
  2994. this->Makefile->IssueMessage(cmake::FATAL_ERROR, merr);
  2995. return false;
  2996. }
  2997. if (args[i] == "FUNCTION") {
  2998. guard = GUARD_FUNCTION;
  2999. } else if (args[i] == "FILE") {
  3000. guard = GUARD_FILE;
  3001. } else if (args[i] == "PROCESS") {
  3002. guard = GUARD_PROCESS;
  3003. } else {
  3004. std::ostringstream e;
  3005. e << merr << ", but got:\n \"" << args[i] << "\".";
  3006. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3007. return false;
  3008. }
  3009. } else if (args[i] == "RESULT_VARIABLE") {
  3010. ++i;
  3011. if (i >= args.size()) {
  3012. this->Makefile->IssueMessage(
  3013. cmake::FATAL_ERROR, "expected variable name after RESULT_VARIABLE");
  3014. return false;
  3015. }
  3016. resultVariable = args[i];
  3017. } else if (args[i] == "TIMEOUT") {
  3018. ++i;
  3019. if (i >= args.size()) {
  3020. this->Makefile->IssueMessage(cmake::FATAL_ERROR,
  3021. "expected timeout value after TIMEOUT");
  3022. return false;
  3023. }
  3024. long scanned;
  3025. if (!cmSystemTools::StringToLong(args[i].c_str(), &scanned) ||
  3026. scanned < 0) {
  3027. std::ostringstream e;
  3028. e << "TIMEOUT value \"" << args[i] << "\" is not an unsigned integer.";
  3029. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3030. return false;
  3031. }
  3032. timeout = static_cast<unsigned long>(scanned);
  3033. } else {
  3034. std::ostringstream e;
  3035. e << "expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or TIMEOUT\n";
  3036. e << "but got: \"" << args[i] << "\".";
  3037. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3038. return false;
  3039. }
  3040. }
  3041. if (directory) {
  3042. path += "/cmake.lock";
  3043. }
  3044. if (!cmsys::SystemTools::FileIsFullPath(path)) {
  3045. path = this->Makefile->GetCurrentSourceDirectory() + ("/" + path);
  3046. }
  3047. // Unify path (remove '//', '/../', ...)
  3048. path = cmSystemTools::CollapseFullPath(path);
  3049. // Create file and directories if needed
  3050. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  3051. if (!cmSystemTools::MakeDirectory(parentDir)) {
  3052. std::ostringstream e;
  3053. e << "directory\n \"" << parentDir << "\"\ncreation failed ";
  3054. e << "(check permissions).";
  3055. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3056. cmSystemTools::SetFatalErrorOccured();
  3057. return false;
  3058. }
  3059. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  3060. if (!file) {
  3061. std::ostringstream e;
  3062. e << "file\n \"" << path << "\"\ncreation failed (check permissions).";
  3063. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3064. cmSystemTools::SetFatalErrorOccured();
  3065. return false;
  3066. }
  3067. fclose(file);
  3068. // Actual lock/unlock
  3069. cmFileLockPool& lockPool =
  3070. this->Makefile->GetGlobalGenerator()->GetFileLockPool();
  3071. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  3072. if (release) {
  3073. fileLockResult = lockPool.Release(path);
  3074. } else {
  3075. switch (guard) {
  3076. case GUARD_FUNCTION:
  3077. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  3078. break;
  3079. case GUARD_FILE:
  3080. fileLockResult = lockPool.LockFileScope(path, timeout);
  3081. break;
  3082. case GUARD_PROCESS:
  3083. fileLockResult = lockPool.LockProcessScope(path, timeout);
  3084. break;
  3085. default:
  3086. cmSystemTools::SetFatalErrorOccured();
  3087. return false;
  3088. }
  3089. }
  3090. const std::string result = fileLockResult.GetOutputMessage();
  3091. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  3092. std::ostringstream e;
  3093. e << "error locking file\n \"" << path << "\"\n" << result << ".";
  3094. this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
  3095. cmSystemTools::SetFatalErrorOccured();
  3096. return false;
  3097. }
  3098. if (!resultVariable.empty()) {
  3099. this->Makefile->AddDefinition(resultVariable, result.c_str());
  3100. }
  3101. return true;
  3102. #else
  3103. static_cast<void>(args);
  3104. this->SetError("sub-command LOCK not implemented in bootstrap cmake");
  3105. return false;
  3106. #endif
  3107. }
  3108. bool cmFileCommand::HandleTimestampCommand(
  3109. std::vector<std::string> const& args)
  3110. {
  3111. if (args.size() < 3) {
  3112. this->SetError("sub-command TIMESTAMP requires at least two arguments.");
  3113. return false;
  3114. }
  3115. if (args.size() > 5) {
  3116. this->SetError("sub-command TIMESTAMP takes at most four arguments.");
  3117. return false;
  3118. }
  3119. unsigned int argsIndex = 1;
  3120. const std::string& filename = args[argsIndex++];
  3121. const std::string& outputVariable = args[argsIndex++];
  3122. std::string formatString;
  3123. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  3124. formatString = args[argsIndex++];
  3125. }
  3126. bool utcFlag = false;
  3127. if (args.size() > argsIndex) {
  3128. if (args[argsIndex] == "UTC") {
  3129. utcFlag = true;
  3130. } else {
  3131. std::string e = " TIMESTAMP sub-command does not recognize option " +
  3132. args[argsIndex] + ".";
  3133. this->SetError(e);
  3134. return false;
  3135. }
  3136. }
  3137. cmTimestamp timestamp;
  3138. std::string result =
  3139. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  3140. this->Makefile->AddDefinition(outputVariable, result.c_str());
  3141. return true;
  3142. }