cmTargetLinkLibrariesCommand.cxx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 "cmTargetLinkLibrariesCommand.h"
  4. #include <cassert>
  5. #include <cstddef>
  6. #include <memory>
  7. #include <sstream>
  8. #include <unordered_set>
  9. #include <utility>
  10. #include <cm/optional>
  11. #include <cm/string_view>
  12. #include "cmExecutionStatus.h"
  13. #include "cmGeneratorExpression.h"
  14. #include "cmGlobalGenerator.h"
  15. #include "cmListFileCache.h"
  16. #include "cmMakefile.h"
  17. #include "cmMessageType.h"
  18. #include "cmPolicies.h"
  19. #include "cmState.h"
  20. #include "cmStateTypes.h"
  21. #include "cmStringAlgorithms.h"
  22. #include "cmSystemTools.h"
  23. #include "cmTarget.h"
  24. #include "cmTargetLinkLibraryType.h"
  25. namespace {
  26. enum ProcessingState
  27. {
  28. ProcessingLinkLibraries,
  29. ProcessingPlainLinkInterface,
  30. ProcessingKeywordLinkInterface,
  31. ProcessingPlainPublicInterface,
  32. ProcessingKeywordPublicInterface,
  33. ProcessingPlainPrivateInterface,
  34. ProcessingKeywordPrivateInterface
  35. };
  36. const char* LinkLibraryTypeNames[3] = { "general", "debug", "optimized" };
  37. struct TLL
  38. {
  39. cmMakefile& Makefile;
  40. cmTarget* Target;
  41. bool WarnRemoteInterface = false;
  42. bool RejectRemoteLinking = false;
  43. bool EncodeRemoteReference = false;
  44. std::string DirectoryId;
  45. std::unordered_set<std::string> Props;
  46. TLL(cmMakefile& mf, cmTarget* target);
  47. ~TLL();
  48. bool HandleLibrary(ProcessingState currentProcessingState,
  49. const std::string& lib, cmTargetLinkLibraryType llt);
  50. void AppendProperty(std::string const& prop, std::string const& value);
  51. void AffectsProperty(std::string const& prop);
  52. };
  53. } // namespace
  54. static void LinkLibraryTypeSpecifierWarning(cmMakefile& mf, int left,
  55. int right);
  56. bool cmTargetLinkLibrariesCommand(std::vector<std::string> const& args,
  57. cmExecutionStatus& status)
  58. {
  59. // Must have at least one argument.
  60. if (args.empty()) {
  61. status.SetError("called with incorrect number of arguments");
  62. return false;
  63. }
  64. cmMakefile& mf = status.GetMakefile();
  65. // Alias targets cannot be on the LHS of this command.
  66. if (mf.IsAlias(args[0])) {
  67. status.SetError("can not be used on an ALIAS target.");
  68. return false;
  69. }
  70. // Lookup the target for which libraries are specified.
  71. cmTarget* target = mf.GetGlobalGenerator()->FindTarget(args[0]);
  72. if (!target) {
  73. for (const auto& importedTarget : mf.GetOwnedImportedTargets()) {
  74. if (importedTarget->GetName() == args[0]) {
  75. target = importedTarget.get();
  76. break;
  77. }
  78. }
  79. }
  80. if (!target) {
  81. mf.IssueMessage(MessageType::FATAL_ERROR,
  82. cmStrCat("Cannot specify link libraries for target \"",
  83. args[0],
  84. "\" which is not built by this project."));
  85. cmSystemTools::SetFatalErrorOccurred();
  86. return true;
  87. }
  88. // Having a UTILITY library on the LHS is a bug.
  89. if (target->GetType() == cmStateEnums::UTILITY) {
  90. std::ostringstream e;
  91. const char* modal = nullptr;
  92. MessageType messageType = MessageType::AUTHOR_WARNING;
  93. switch (mf.GetPolicyStatus(cmPolicies::CMP0039)) {
  94. case cmPolicies::WARN:
  95. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0039) << '\n';
  96. modal = "should";
  97. CM_FALLTHROUGH;
  98. case cmPolicies::OLD:
  99. break;
  100. case cmPolicies::NEW:
  101. modal = "must";
  102. messageType = MessageType::FATAL_ERROR;
  103. break;
  104. }
  105. if (modal) {
  106. e << "Utility target \"" << target->GetName() << "\" " << modal
  107. << " not be used as the target of a target_link_libraries call.";
  108. mf.IssueMessage(messageType, e.str());
  109. if (messageType == MessageType::FATAL_ERROR) {
  110. return false;
  111. }
  112. }
  113. }
  114. // But we might not have any libs after variable expansion.
  115. if (args.size() < 2) {
  116. return true;
  117. }
  118. TLL tll(mf, target);
  119. // Keep track of link configuration specifiers.
  120. cmTargetLinkLibraryType llt = GENERAL_LibraryType;
  121. bool haveLLT = false;
  122. // Start with primary linking and switch to link interface
  123. // specification if the keyword is encountered as the first argument.
  124. ProcessingState currentProcessingState = ProcessingLinkLibraries;
  125. // Accumulate consecutive non-keyword arguments into one entry in
  126. // order to handle unquoted generator expressions containing ';'.
  127. std::size_t genexNesting = 0;
  128. cm::optional<std::string> currentEntry;
  129. auto processCurrentEntry = [&]() -> bool {
  130. // FIXME: Warn about partial genex if genexNesting > 0?
  131. genexNesting = 0;
  132. if (currentEntry) {
  133. assert(!haveLLT);
  134. if (!tll.HandleLibrary(currentProcessingState, *currentEntry,
  135. GENERAL_LibraryType)) {
  136. return false;
  137. }
  138. currentEntry = cm::nullopt;
  139. }
  140. return true;
  141. };
  142. auto extendCurrentEntry = [&currentEntry](std::string const& arg) {
  143. if (currentEntry) {
  144. currentEntry = cmStrCat(*currentEntry, ';', arg);
  145. } else {
  146. currentEntry = arg;
  147. }
  148. };
  149. // Keep this list in sync with the keyword dispatch below.
  150. static std::unordered_set<std::string> const keywords{
  151. "LINK_INTERFACE_LIBRARIES",
  152. "INTERFACE",
  153. "LINK_PUBLIC",
  154. "PUBLIC",
  155. "LINK_PRIVATE",
  156. "PRIVATE",
  157. "debug",
  158. "optimized",
  159. "general",
  160. };
  161. // Add libraries, note that there is an optional prefix
  162. // of debug and optimized that can be used.
  163. for (unsigned int i = 1; i < args.size(); ++i) {
  164. if (keywords.count(args[i])) {
  165. // A keyword argument terminates any accumulated partial genex.
  166. if (!processCurrentEntry()) {
  167. return false;
  168. }
  169. // Process this keyword argument.
  170. if (args[i] == "LINK_INTERFACE_LIBRARIES") {
  171. currentProcessingState = ProcessingPlainLinkInterface;
  172. if (i != 1) {
  173. mf.IssueMessage(
  174. MessageType::FATAL_ERROR,
  175. "The LINK_INTERFACE_LIBRARIES option must appear as the "
  176. "second argument, just after the target name.");
  177. return true;
  178. }
  179. } else if (args[i] == "INTERFACE") {
  180. if (i != 1 &&
  181. currentProcessingState != ProcessingKeywordPrivateInterface &&
  182. currentProcessingState != ProcessingKeywordPublicInterface &&
  183. currentProcessingState != ProcessingKeywordLinkInterface) {
  184. mf.IssueMessage(MessageType::FATAL_ERROR,
  185. "The INTERFACE, PUBLIC or PRIVATE option must "
  186. "appear as the second argument, just after the "
  187. "target name.");
  188. return true;
  189. }
  190. currentProcessingState = ProcessingKeywordLinkInterface;
  191. } else if (args[i] == "LINK_PUBLIC") {
  192. if (i != 1 &&
  193. currentProcessingState != ProcessingPlainPrivateInterface &&
  194. currentProcessingState != ProcessingPlainPublicInterface) {
  195. mf.IssueMessage(
  196. MessageType::FATAL_ERROR,
  197. "The LINK_PUBLIC or LINK_PRIVATE option must appear as the "
  198. "second argument, just after the target name.");
  199. return true;
  200. }
  201. currentProcessingState = ProcessingPlainPublicInterface;
  202. } else if (args[i] == "PUBLIC") {
  203. if (i != 1 &&
  204. currentProcessingState != ProcessingKeywordPrivateInterface &&
  205. currentProcessingState != ProcessingKeywordPublicInterface &&
  206. currentProcessingState != ProcessingKeywordLinkInterface) {
  207. mf.IssueMessage(MessageType::FATAL_ERROR,
  208. "The INTERFACE, PUBLIC or PRIVATE option must "
  209. "appear as the second argument, just after the "
  210. "target name.");
  211. return true;
  212. }
  213. currentProcessingState = ProcessingKeywordPublicInterface;
  214. } else if (args[i] == "LINK_PRIVATE") {
  215. if (i != 1 &&
  216. currentProcessingState != ProcessingPlainPublicInterface &&
  217. currentProcessingState != ProcessingPlainPrivateInterface) {
  218. mf.IssueMessage(
  219. MessageType::FATAL_ERROR,
  220. "The LINK_PUBLIC or LINK_PRIVATE option must appear as the "
  221. "second argument, just after the target name.");
  222. return true;
  223. }
  224. currentProcessingState = ProcessingPlainPrivateInterface;
  225. } else if (args[i] == "PRIVATE") {
  226. if (i != 1 &&
  227. currentProcessingState != ProcessingKeywordPrivateInterface &&
  228. currentProcessingState != ProcessingKeywordPublicInterface &&
  229. currentProcessingState != ProcessingKeywordLinkInterface) {
  230. mf.IssueMessage(MessageType::FATAL_ERROR,
  231. "The INTERFACE, PUBLIC or PRIVATE option must "
  232. "appear as the second argument, just after the "
  233. "target name.");
  234. return true;
  235. }
  236. currentProcessingState = ProcessingKeywordPrivateInterface;
  237. } else if (args[i] == "debug") {
  238. if (haveLLT) {
  239. LinkLibraryTypeSpecifierWarning(mf, llt, DEBUG_LibraryType);
  240. }
  241. llt = DEBUG_LibraryType;
  242. haveLLT = true;
  243. } else if (args[i] == "optimized") {
  244. if (haveLLT) {
  245. LinkLibraryTypeSpecifierWarning(mf, llt, OPTIMIZED_LibraryType);
  246. }
  247. llt = OPTIMIZED_LibraryType;
  248. haveLLT = true;
  249. } else if (args[i] == "general") {
  250. if (haveLLT) {
  251. LinkLibraryTypeSpecifierWarning(mf, llt, GENERAL_LibraryType);
  252. }
  253. llt = GENERAL_LibraryType;
  254. haveLLT = true;
  255. }
  256. } else if (haveLLT) {
  257. // The link type was specified by the previous argument.
  258. haveLLT = false;
  259. assert(!currentEntry);
  260. if (!tll.HandleLibrary(currentProcessingState, args[i], llt)) {
  261. return false;
  262. }
  263. llt = GENERAL_LibraryType;
  264. } else {
  265. // Track the genex nesting level.
  266. {
  267. cm::string_view arg = args[i];
  268. for (std::string::size_type pos = 0; pos < arg.size(); ++pos) {
  269. cm::string_view cur = arg.substr(pos);
  270. if (cmHasLiteralPrefix(cur, "$<")) {
  271. ++genexNesting;
  272. ++pos;
  273. } else if (genexNesting > 0 && cmHasLiteralPrefix(cur, ">")) {
  274. --genexNesting;
  275. }
  276. }
  277. }
  278. // Accumulate this argument in the current entry.
  279. extendCurrentEntry(args[i]);
  280. // Process this entry if it does not end inside a genex.
  281. if (genexNesting == 0) {
  282. if (!processCurrentEntry()) {
  283. return false;
  284. }
  285. }
  286. }
  287. }
  288. // Process the last accumulated partial genex, if any.
  289. if (!processCurrentEntry()) {
  290. return false;
  291. }
  292. // Make sure the last argument was not a library type specifier.
  293. if (haveLLT) {
  294. mf.IssueMessage(MessageType::FATAL_ERROR,
  295. cmStrCat("The \"", LinkLibraryTypeNames[llt],
  296. "\" argument must be followed by a library."));
  297. cmSystemTools::SetFatalErrorOccurred();
  298. }
  299. return true;
  300. }
  301. static void LinkLibraryTypeSpecifierWarning(cmMakefile& mf, int left,
  302. int right)
  303. {
  304. mf.IssueMessage(
  305. MessageType::AUTHOR_WARNING,
  306. cmStrCat(
  307. "Link library type specifier \"", LinkLibraryTypeNames[left],
  308. "\" is followed by specifier \"", LinkLibraryTypeNames[right],
  309. "\" instead of a library name. The first specifier will be ignored."));
  310. }
  311. namespace {
  312. TLL::TLL(cmMakefile& mf, cmTarget* target)
  313. : Makefile(mf)
  314. , Target(target)
  315. {
  316. if (&this->Makefile != this->Target->GetMakefile()) {
  317. // The LHS target was created in another directory.
  318. switch (this->Makefile.GetPolicyStatus(cmPolicies::CMP0079)) {
  319. case cmPolicies::WARN:
  320. this->WarnRemoteInterface = true;
  321. CM_FALLTHROUGH;
  322. case cmPolicies::OLD:
  323. this->RejectRemoteLinking = true;
  324. break;
  325. case cmPolicies::NEW:
  326. this->EncodeRemoteReference = true;
  327. break;
  328. }
  329. }
  330. if (this->EncodeRemoteReference) {
  331. cmDirectoryId const dirId = this->Makefile.GetDirectoryId();
  332. this->DirectoryId = cmStrCat(CMAKE_DIRECTORY_ID_SEP, dirId.String);
  333. }
  334. }
  335. bool TLL::HandleLibrary(ProcessingState currentProcessingState,
  336. const std::string& lib, cmTargetLinkLibraryType llt)
  337. {
  338. if (this->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY &&
  339. currentProcessingState != ProcessingKeywordLinkInterface) {
  340. this->Makefile.IssueMessage(
  341. MessageType::FATAL_ERROR,
  342. "INTERFACE library can only be used with the INTERFACE keyword of "
  343. "target_link_libraries");
  344. return false;
  345. }
  346. if (this->Target->IsImported() &&
  347. currentProcessingState != ProcessingKeywordLinkInterface) {
  348. this->Makefile.IssueMessage(
  349. MessageType::FATAL_ERROR,
  350. "IMPORTED library can only be used with the INTERFACE keyword of "
  351. "target_link_libraries");
  352. return false;
  353. }
  354. cmTarget::TLLSignature sig =
  355. (currentProcessingState == ProcessingPlainPrivateInterface ||
  356. currentProcessingState == ProcessingPlainPublicInterface ||
  357. currentProcessingState == ProcessingKeywordPrivateInterface ||
  358. currentProcessingState == ProcessingKeywordPublicInterface ||
  359. currentProcessingState == ProcessingKeywordLinkInterface)
  360. ? cmTarget::KeywordTLLSignature
  361. : cmTarget::PlainTLLSignature;
  362. if (!this->Target->PushTLLCommandTrace(
  363. sig, this->Makefile.GetBacktrace().Top())) {
  364. std::ostringstream e;
  365. // If the sig is a keyword form and there is a conflict, the existing
  366. // form must be the plain form.
  367. const char* existingSig =
  368. (sig == cmTarget::KeywordTLLSignature ? "plain" : "keyword");
  369. e << "The " << existingSig
  370. << " signature for target_link_libraries has "
  371. "already been used with the target \""
  372. << this->Target->GetName()
  373. << "\". All uses of target_link_libraries with a target must "
  374. << " be either all-keyword or all-plain.\n";
  375. this->Target->GetTllSignatureTraces(e,
  376. sig == cmTarget::KeywordTLLSignature
  377. ? cmTarget::PlainTLLSignature
  378. : cmTarget::KeywordTLLSignature);
  379. this->Makefile.IssueMessage(MessageType::FATAL_ERROR, e.str());
  380. return false;
  381. }
  382. // Handle normal case where the command was called with another keyword than
  383. // INTERFACE / LINK_INTERFACE_LIBRARIES or none at all. (The "LINK_LIBRARIES"
  384. // property of the target on the LHS shall be populated.)
  385. if (currentProcessingState != ProcessingKeywordLinkInterface &&
  386. currentProcessingState != ProcessingPlainLinkInterface) {
  387. if (this->RejectRemoteLinking) {
  388. this->Makefile.IssueMessage(
  389. MessageType::FATAL_ERROR,
  390. cmStrCat("Attempt to add link library \"", lib, "\" to target \"",
  391. this->Target->GetName(),
  392. "\" which is not built in this "
  393. "directory.\nThis is allowed only when policy CMP0079 "
  394. "is set to NEW."));
  395. return false;
  396. }
  397. cmTarget* tgt = this->Makefile.GetGlobalGenerator()->FindTarget(lib);
  398. if (tgt && (tgt->GetType() != cmStateEnums::STATIC_LIBRARY) &&
  399. (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) &&
  400. (tgt->GetType() != cmStateEnums::UNKNOWN_LIBRARY) &&
  401. (tgt->GetType() != cmStateEnums::OBJECT_LIBRARY) &&
  402. (tgt->GetType() != cmStateEnums::INTERFACE_LIBRARY) &&
  403. !tgt->IsExecutableWithExports()) {
  404. this->Makefile.IssueMessage(
  405. MessageType::FATAL_ERROR,
  406. cmStrCat(
  407. "Target \"", lib, "\" of type ",
  408. cmState::GetTargetTypeName(tgt->GetType()),
  409. " may not be linked into another target. One may link only to "
  410. "INTERFACE, OBJECT, STATIC or SHARED libraries, or to ",
  411. "executables with the ENABLE_EXPORTS property set."));
  412. }
  413. this->AffectsProperty("LINK_LIBRARIES");
  414. this->Target->AddLinkLibrary(this->Makefile, lib, llt);
  415. }
  416. if (this->WarnRemoteInterface) {
  417. this->Makefile.IssueMessage(
  418. MessageType::AUTHOR_WARNING,
  419. cmStrCat(
  420. cmPolicies::GetPolicyWarning(cmPolicies::CMP0079), "\nTarget\n ",
  421. this->Target->GetName(),
  422. "\nis not created in this "
  423. "directory. For compatibility with older versions of CMake, link "
  424. "library\n ",
  425. lib,
  426. "\nwill be looked up in the directory in which "
  427. "the target was created rather than in this calling directory."));
  428. }
  429. // Handle (additional) case where the command was called with PRIVATE /
  430. // LINK_PRIVATE and stop its processing. (The "INTERFACE_LINK_LIBRARIES"
  431. // property of the target on the LHS shall only be populated if it is a
  432. // STATIC library.)
  433. if (currentProcessingState == ProcessingKeywordPrivateInterface ||
  434. currentProcessingState == ProcessingPlainPrivateInterface) {
  435. if (this->Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
  436. this->Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  437. // TODO: Detect and no-op `$<COMPILE_ONLY>` genexes here.
  438. std::string configLib =
  439. this->Target->GetDebugGeneratorExpressions(lib, llt);
  440. if (cmGeneratorExpression::IsValidTargetName(lib) ||
  441. cmGeneratorExpression::Find(lib) != std::string::npos) {
  442. configLib = "$<LINK_ONLY:" + configLib + ">";
  443. }
  444. this->AppendProperty("INTERFACE_LINK_LIBRARIES", configLib);
  445. }
  446. return true;
  447. }
  448. // Handle general case where the command was called with another keyword than
  449. // PRIVATE / LINK_PRIVATE or none at all. (The "INTERFACE_LINK_LIBRARIES"
  450. // property of the target on the LHS shall be populated.)
  451. this->AppendProperty("INTERFACE_LINK_LIBRARIES",
  452. this->Target->GetDebugGeneratorExpressions(lib, llt));
  453. return true;
  454. }
  455. void TLL::AppendProperty(std::string const& prop, std::string const& value)
  456. {
  457. this->AffectsProperty(prop);
  458. this->Target->AppendProperty(prop, value, this->Makefile.GetBacktrace());
  459. }
  460. void TLL::AffectsProperty(std::string const& prop)
  461. {
  462. if (!this->EncodeRemoteReference) {
  463. return;
  464. }
  465. // Add a wrapper to the expression to tell LookupLinkItem to look up
  466. // names in the caller's directory.
  467. if (this->Props.insert(prop).second) {
  468. this->Target->AppendProperty(prop, this->DirectoryId,
  469. this->Makefile.GetBacktrace());
  470. }
  471. }
  472. TLL::~TLL()
  473. {
  474. for (std::string const& prop : this->Props) {
  475. this->Target->AppendProperty(prop, CMAKE_DIRECTORY_ID_SEP,
  476. this->Makefile.GetBacktrace());
  477. }
  478. }
  479. } // namespace