cmFileCommand.cxx 82 KB

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