cmFileCommand.cxx 101 KB

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