cmFileCommand.cxx 99 KB

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