cmTargetLinkLibrariesCommand.cxx 18 KB

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