cmTargetLinkLibrariesCommand.cxx 18 KB

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