cmFileCommand.cxx 102 KB

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