cmFileCommand.cxx 100 KB

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