cmFileCommand.cxx 97 KB

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