cmOrderDirectories.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmOrderDirectories.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <functional>
  7. #include <sstream>
  8. #include <vector>
  9. #include <cm/memory>
  10. #include <cmext/algorithm>
  11. #include "cmGeneratorTarget.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmMessageType.h"
  14. #include "cmStringAlgorithms.h"
  15. #include "cmSystemTools.h"
  16. #include "cmake.h"
  17. /*
  18. Directory ordering computation.
  19. - Useful to compute a safe runtime library path order
  20. - Need runtime path for supporting INSTALL_RPATH_USE_LINK_PATH
  21. - Need runtime path at link time to pickup transitive link dependencies
  22. for shared libraries.
  23. */
  24. class cmOrderDirectoriesConstraint
  25. {
  26. public:
  27. cmOrderDirectoriesConstraint(cmOrderDirectories* od, std::string const& file)
  28. : OD(od)
  29. , GlobalGenerator(od->GlobalGenerator)
  30. {
  31. this->FullPath = file;
  32. if (file.rfind(".framework") != std::string::npos) {
  33. static cmsys::RegularExpression splitFramework(
  34. "^(.*)/(.*).framework/(.*)$");
  35. if (splitFramework.find(file) &&
  36. (std::string::npos !=
  37. splitFramework.match(3).find(splitFramework.match(2)))) {
  38. this->Directory = splitFramework.match(1);
  39. this->FileName =
  40. std::string(file.begin() + this->Directory.size() + 1, file.end());
  41. }
  42. }
  43. if (this->FileName.empty()) {
  44. this->Directory = cmSystemTools::GetFilenamePath(file);
  45. this->FileName = cmSystemTools::GetFilenameName(file);
  46. }
  47. }
  48. virtual ~cmOrderDirectoriesConstraint() = default;
  49. void AddDirectory()
  50. {
  51. this->DirectoryIndex = this->OD->AddOriginalDirectory(this->Directory);
  52. }
  53. virtual void Report(std::ostream& e) = 0;
  54. void FindConflicts(unsigned int index)
  55. {
  56. for (unsigned int i = 0; i < this->OD->OriginalDirectories.size(); ++i) {
  57. // Check if this directory conflicts with the entry.
  58. std::string const& dir = this->OD->OriginalDirectories[i];
  59. if (!this->OD->IsSameDirectory(dir, this->Directory) &&
  60. this->FindConflict(dir)) {
  61. // The library will be found in this directory but this is not
  62. // the directory named for it. Add an entry to make sure the
  63. // desired directory comes before this one.
  64. cmOrderDirectories::ConflictPair p(this->DirectoryIndex, index);
  65. this->OD->ConflictGraph[i].push_back(p);
  66. }
  67. }
  68. }
  69. void FindImplicitConflicts(std::ostringstream& w)
  70. {
  71. bool first = true;
  72. for (std::string const& dir : this->OD->OriginalDirectories) {
  73. // Check if this directory conflicts with the entry.
  74. if (dir != this->Directory &&
  75. cmSystemTools::GetRealPath(dir) !=
  76. cmSystemTools::GetRealPath(this->Directory) &&
  77. this->FindConflict(dir)) {
  78. // The library will be found in this directory but it is
  79. // supposed to be found in an implicit search directory.
  80. if (first) {
  81. first = false;
  82. w << " ";
  83. this->Report(w);
  84. w << " in " << this->Directory << " may be hidden by files in:\n";
  85. }
  86. w << " " << dir << "\n";
  87. }
  88. }
  89. }
  90. protected:
  91. virtual bool FindConflict(std::string const& dir) = 0;
  92. bool FileMayConflict(std::string const& dir, std::string const& name);
  93. cmOrderDirectories* OD;
  94. cmGlobalGenerator* GlobalGenerator;
  95. // The location in which the item is supposed to be found.
  96. std::string FullPath;
  97. std::string Directory;
  98. std::string FileName;
  99. // The index assigned to the directory.
  100. int DirectoryIndex;
  101. };
  102. bool cmOrderDirectoriesConstraint::FileMayConflict(std::string const& dir,
  103. std::string const& name)
  104. {
  105. // Check if the file exists on disk.
  106. std::string file = cmStrCat(dir, '/', name);
  107. if (cmSystemTools::FileExists(file, true)) {
  108. // The file conflicts only if it is not the same as the original
  109. // file due to a symlink or hardlink.
  110. return !cmSystemTools::SameFile(this->FullPath, file);
  111. }
  112. // Check if the file will be built by cmake.
  113. std::set<std::string> const& files =
  114. (this->GlobalGenerator->GetDirectoryContent(dir, false));
  115. auto fi = files.find(name);
  116. return fi != files.end();
  117. }
  118. class cmOrderDirectoriesConstraintSOName : public cmOrderDirectoriesConstraint
  119. {
  120. public:
  121. cmOrderDirectoriesConstraintSOName(cmOrderDirectories* od,
  122. std::string const& file,
  123. const char* soname)
  124. : cmOrderDirectoriesConstraint(od, file)
  125. , SOName(soname ? soname : "")
  126. {
  127. if (this->SOName.empty()) {
  128. // Try to guess the soname.
  129. std::string soguess;
  130. if (cmSystemTools::GuessLibrarySOName(file, soguess)) {
  131. this->SOName = soguess;
  132. }
  133. }
  134. }
  135. void Report(std::ostream& e) override
  136. {
  137. e << "runtime library [";
  138. if (this->SOName.empty()) {
  139. e << this->FileName;
  140. } else {
  141. e << this->SOName;
  142. }
  143. e << "]";
  144. }
  145. bool FindConflict(std::string const& dir) override;
  146. private:
  147. // The soname of the shared library if it is known.
  148. std::string SOName;
  149. };
  150. bool cmOrderDirectoriesConstraintSOName::FindConflict(std::string const& dir)
  151. {
  152. // Determine which type of check to do.
  153. if (!this->SOName.empty()) {
  154. // We have the library soname. Check if it will be found.
  155. if (this->FileMayConflict(dir, this->SOName)) {
  156. return true;
  157. }
  158. } else {
  159. // We do not have the soname. Look for files in the directory
  160. // that may conflict.
  161. std::set<std::string> const& files =
  162. (this->GlobalGenerator->GetDirectoryContent(dir, true));
  163. // Get the set of files that might conflict. Since we do not
  164. // know the soname just look at all files that start with the
  165. // file name. Usually the soname starts with the library name.
  166. std::string base = this->FileName;
  167. auto first = files.lower_bound(base);
  168. ++base.back();
  169. auto last = files.upper_bound(base);
  170. if (first != last) {
  171. return true;
  172. }
  173. }
  174. return false;
  175. }
  176. class cmOrderDirectoriesConstraintLibrary : public cmOrderDirectoriesConstraint
  177. {
  178. public:
  179. cmOrderDirectoriesConstraintLibrary(cmOrderDirectories* od,
  180. std::string const& file)
  181. : cmOrderDirectoriesConstraint(od, file)
  182. {
  183. }
  184. void Report(std::ostream& e) override
  185. {
  186. e << "link library [" << this->FileName << "]";
  187. }
  188. bool FindConflict(std::string const& dir) override;
  189. };
  190. bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir)
  191. {
  192. // We have the library file name. Check if it will be found.
  193. if (this->FileMayConflict(dir, this->FileName)) {
  194. return true;
  195. }
  196. // Now check if the file exists with other extensions the linker
  197. // might consider.
  198. if (!this->OD->LinkExtensions.empty() &&
  199. this->OD->RemoveLibraryExtension.find(this->FileName)) {
  200. std::string lib = this->OD->RemoveLibraryExtension.match(1);
  201. std::string ext = this->OD->RemoveLibraryExtension.match(2);
  202. for (std::string const& LinkExtension : this->OD->LinkExtensions) {
  203. if (LinkExtension != ext) {
  204. std::string fname = cmStrCat(lib, LinkExtension);
  205. if (this->FileMayConflict(dir, fname)) {
  206. return true;
  207. }
  208. }
  209. }
  210. }
  211. return false;
  212. }
  213. cmOrderDirectories::cmOrderDirectories(cmGlobalGenerator* gg,
  214. const cmGeneratorTarget* target,
  215. const char* purpose)
  216. {
  217. this->GlobalGenerator = gg;
  218. this->Target = target;
  219. this->Purpose = purpose;
  220. this->Computed = false;
  221. }
  222. cmOrderDirectories::~cmOrderDirectories() = default;
  223. std::vector<std::string> const& cmOrderDirectories::GetOrderedDirectories()
  224. {
  225. if (!this->Computed) {
  226. this->Computed = true;
  227. this->CollectOriginalDirectories();
  228. this->FindConflicts();
  229. this->OrderDirectories();
  230. }
  231. return this->OrderedDirectories;
  232. }
  233. void cmOrderDirectories::AddRuntimeLibrary(std::string const& fullPath,
  234. const char* soname)
  235. {
  236. // Add the runtime library at most once.
  237. if (this->EmmittedConstraintSOName.insert(fullPath).second) {
  238. // Implicit link directories need special handling.
  239. if (!this->ImplicitDirectories.empty()) {
  240. std::string dir = cmSystemTools::GetFilenamePath(fullPath);
  241. if (fullPath.rfind(".framework") != std::string::npos) {
  242. static cmsys::RegularExpression splitFramework(
  243. "^(.*)/(.*).framework/(.*)$");
  244. if (splitFramework.find(fullPath) &&
  245. (std::string::npos !=
  246. splitFramework.match(3).find(splitFramework.match(2)))) {
  247. dir = splitFramework.match(1);
  248. }
  249. }
  250. if (this->IsImplicitDirectory(dir)) {
  251. this->ImplicitDirEntries.push_back(
  252. cm::make_unique<cmOrderDirectoriesConstraintSOName>(this, fullPath,
  253. soname));
  254. return;
  255. }
  256. }
  257. // Construct the runtime information entry for this library.
  258. this->ConstraintEntries.push_back(
  259. cm::make_unique<cmOrderDirectoriesConstraintSOName>(this, fullPath,
  260. soname));
  261. } else {
  262. // This can happen if the same library is linked multiple times.
  263. // In that case the runtime information check need be done only
  264. // once anyway. For shared libs we could add a check in AddItem
  265. // to not repeat them.
  266. }
  267. }
  268. void cmOrderDirectories::AddLinkLibrary(std::string const& fullPath)
  269. {
  270. // Link extension info is required for library constraints.
  271. assert(!this->LinkExtensions.empty());
  272. // Add the link library at most once.
  273. if (this->EmmittedConstraintLibrary.insert(fullPath).second) {
  274. // Implicit link directories need special handling.
  275. if (!this->ImplicitDirectories.empty()) {
  276. std::string dir = cmSystemTools::GetFilenamePath(fullPath);
  277. if (this->IsImplicitDirectory(dir)) {
  278. this->ImplicitDirEntries.push_back(
  279. cm::make_unique<cmOrderDirectoriesConstraintLibrary>(this,
  280. fullPath));
  281. return;
  282. }
  283. }
  284. // Construct the link library entry.
  285. this->ConstraintEntries.push_back(
  286. cm::make_unique<cmOrderDirectoriesConstraintLibrary>(this, fullPath));
  287. }
  288. }
  289. void cmOrderDirectories::AddUserDirectories(
  290. std::vector<std::string> const& extra)
  291. {
  292. cm::append(this->UserDirectories, extra);
  293. }
  294. void cmOrderDirectories::AddLanguageDirectories(
  295. std::vector<std::string> const& dirs)
  296. {
  297. cm::append(this->LanguageDirectories, dirs);
  298. }
  299. void cmOrderDirectories::SetImplicitDirectories(
  300. std::set<std::string> const& implicitDirs)
  301. {
  302. this->ImplicitDirectories.clear();
  303. for (std::string const& implicitDir : implicitDirs) {
  304. this->ImplicitDirectories.insert(this->GetRealPath(implicitDir));
  305. }
  306. }
  307. bool cmOrderDirectories::IsImplicitDirectory(std::string const& dir)
  308. {
  309. std::string const& real = this->GetRealPath(dir);
  310. return this->ImplicitDirectories.find(real) !=
  311. this->ImplicitDirectories.end();
  312. }
  313. void cmOrderDirectories::SetLinkExtensionInfo(
  314. std::vector<std::string> const& linkExtensions,
  315. std::string const& removeExtRegex)
  316. {
  317. this->LinkExtensions = linkExtensions;
  318. this->RemoveLibraryExtension.compile(removeExtRegex);
  319. }
  320. void cmOrderDirectories::CollectOriginalDirectories()
  321. {
  322. // Add user directories specified for inclusion. These should be
  323. // indexed first so their original order is preserved as much as
  324. // possible subject to the constraints.
  325. this->AddOriginalDirectories(this->UserDirectories);
  326. // Add directories containing constraints.
  327. for (const auto& entry : this->ConstraintEntries) {
  328. entry->AddDirectory();
  329. }
  330. // Add language runtime directories last.
  331. this->AddOriginalDirectories(this->LanguageDirectories);
  332. }
  333. int cmOrderDirectories::AddOriginalDirectory(std::string const& dir)
  334. {
  335. // Add the runtime directory with a unique index.
  336. auto i = this->DirectoryIndex.find(dir);
  337. if (i == this->DirectoryIndex.end()) {
  338. std::map<std::string, int>::value_type entry(
  339. dir, static_cast<int>(this->OriginalDirectories.size()));
  340. i = this->DirectoryIndex.insert(entry).first;
  341. this->OriginalDirectories.push_back(dir);
  342. }
  343. return i->second;
  344. }
  345. void cmOrderDirectories::AddOriginalDirectories(
  346. std::vector<std::string> const& dirs)
  347. {
  348. for (std::string const& dir : dirs) {
  349. // We never explicitly specify implicit link directories.
  350. if (this->IsImplicitDirectory(dir)) {
  351. continue;
  352. }
  353. // Skip the empty string.
  354. if (dir.empty()) {
  355. continue;
  356. }
  357. // Add this directory.
  358. this->AddOriginalDirectory(dir);
  359. }
  360. }
  361. struct cmOrderDirectoriesCompare
  362. {
  363. using ConflictPair = std::pair<int, int>;
  364. // The conflict pair is unique based on just the directory
  365. // (first). The second element is only used for displaying
  366. // information about why the entry is present.
  367. bool operator()(ConflictPair l, ConflictPair r)
  368. {
  369. return l.first == r.first;
  370. }
  371. };
  372. void cmOrderDirectories::FindConflicts()
  373. {
  374. // Allocate the conflict graph.
  375. this->ConflictGraph.resize(this->OriginalDirectories.size());
  376. this->DirectoryVisited.resize(this->OriginalDirectories.size(), 0);
  377. // Find directories conflicting with each entry.
  378. for (unsigned int i = 0; i < this->ConstraintEntries.size(); ++i) {
  379. this->ConstraintEntries[i]->FindConflicts(i);
  380. }
  381. // Clean up the conflict graph representation.
  382. for (ConflictList& cl : this->ConflictGraph) {
  383. // Sort the outgoing edges for each graph node so that the
  384. // original order will be preserved as much as possible.
  385. std::sort(cl.begin(), cl.end());
  386. // Make the edge list unique so cycle detection will be reliable.
  387. auto last = std::unique(cl.begin(), cl.end(), cmOrderDirectoriesCompare());
  388. cl.erase(last, cl.end());
  389. }
  390. // Check items in implicit link directories.
  391. this->FindImplicitConflicts();
  392. }
  393. void cmOrderDirectories::FindImplicitConflicts()
  394. {
  395. // Check for items in implicit link directories that have conflicts
  396. // in the explicit directories.
  397. std::ostringstream conflicts;
  398. for (const auto& entry : this->ImplicitDirEntries) {
  399. entry->FindImplicitConflicts(conflicts);
  400. }
  401. // Skip warning if there were no conflicts.
  402. std::string const text = conflicts.str();
  403. if (text.empty()) {
  404. return;
  405. }
  406. // Warn about the conflicts.
  407. this->GlobalGenerator->GetCMakeInstance()->IssueMessage(
  408. MessageType::WARNING,
  409. cmStrCat("Cannot generate a safe ", this->Purpose, " for target ",
  410. this->Target->GetName(),
  411. " because files in some directories may "
  412. "conflict with libraries in implicit directories:\n",
  413. text, "Some of these libraries may not be found correctly."),
  414. this->Target->GetBacktrace());
  415. }
  416. void cmOrderDirectories::OrderDirectories()
  417. {
  418. // Allow a cycle to be diagnosed once.
  419. this->CycleDiagnosed = false;
  420. this->WalkId = 0;
  421. // Iterate through the directories in the original order.
  422. for (unsigned int i = 0; i < this->OriginalDirectories.size(); ++i) {
  423. // Start a new DFS from this node.
  424. ++this->WalkId;
  425. this->VisitDirectory(i);
  426. }
  427. }
  428. void cmOrderDirectories::VisitDirectory(unsigned int i)
  429. {
  430. // Skip nodes already visited.
  431. if (this->DirectoryVisited[i]) {
  432. if (this->DirectoryVisited[i] == this->WalkId) {
  433. // We have reached a node previously visited on this DFS.
  434. // There is a cycle.
  435. this->DiagnoseCycle();
  436. }
  437. return;
  438. }
  439. // We are now visiting this node so mark it.
  440. this->DirectoryVisited[i] = this->WalkId;
  441. // Visit the neighbors of the node first.
  442. ConflictList const& clist = this->ConflictGraph[i];
  443. for (ConflictPair const& j : clist) {
  444. this->VisitDirectory(j.first);
  445. }
  446. // Now that all directories required to come before this one have
  447. // been emitted, emit this directory.
  448. this->OrderedDirectories.push_back(this->OriginalDirectories[i]);
  449. }
  450. void cmOrderDirectories::DiagnoseCycle()
  451. {
  452. // Report the cycle at most once.
  453. if (this->CycleDiagnosed) {
  454. return;
  455. }
  456. this->CycleDiagnosed = true;
  457. // Construct the message.
  458. std::ostringstream e;
  459. e << "Cannot generate a safe " << this->Purpose << " for target "
  460. << this->Target->GetName()
  461. << " because there is a cycle in the constraint graph:\n";
  462. // Display the conflict graph.
  463. for (unsigned int i = 0; i < this->ConflictGraph.size(); ++i) {
  464. ConflictList const& clist = this->ConflictGraph[i];
  465. e << " dir " << i << " is [" << this->OriginalDirectories[i] << "]\n";
  466. for (ConflictPair const& j : clist) {
  467. e << " dir " << j.first << " must precede it due to ";
  468. this->ConstraintEntries[j.second]->Report(e);
  469. e << "\n";
  470. }
  471. }
  472. e << "Some of these libraries may not be found correctly.";
  473. this->GlobalGenerator->GetCMakeInstance()->IssueMessage(
  474. MessageType::WARNING, e.str(), this->Target->GetBacktrace());
  475. }
  476. bool cmOrderDirectories::IsSameDirectory(std::string const& l,
  477. std::string const& r)
  478. {
  479. return this->GetRealPath(l) == this->GetRealPath(r);
  480. }
  481. std::string const& cmOrderDirectories::GetRealPath(std::string const& dir)
  482. {
  483. auto i = this->RealPaths.lower_bound(dir);
  484. if (i == this->RealPaths.end() ||
  485. this->RealPaths.key_comp()(dir, i->first)) {
  486. using value_type = std::map<std::string, std::string>::value_type;
  487. i = this->RealPaths.insert(
  488. i, value_type(dir, cmSystemTools::GetRealPath(dir)));
  489. }
  490. return i->second;
  491. }