cmFileCommand.cxx 100 KB

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