cmFileCommand.cxx 102 KB

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