cmFileCommand.cxx 102 KB

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