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