cmFileCommand.cxx 84 KB

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