PageRenderTime 65ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/cmake-2.8.9-rc2/Source/cmFileCommand.cxx

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