cmFileCommand.cxx 99 KB

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