cmOrderDirectories.cxx 17 KB

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