cmFileCommand.cxx 102 KB

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