cmOrderDirectories.cxx 17 KB

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