cmFileCommand.cxx 100 KB

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