cmQtAutoGenInitializer.cxx 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572
  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 "cmQtAutoGenInitializer.h"
  4. #include <array>
  5. #include <cstddef>
  6. #include <deque>
  7. #include <initializer_list>
  8. #include <limits>
  9. #include <map>
  10. #include <set>
  11. #include <sstream> // for basic_ios, istringstream
  12. #include <string>
  13. #include <unordered_set>
  14. #include <utility>
  15. #include <vector>
  16. #include <cm/algorithm>
  17. #include <cm/iterator>
  18. #include <cm/memory>
  19. #include <cm/string_view>
  20. #include <cmext/algorithm>
  21. #include <cmext/string_view>
  22. #include <cm3p/json/value.h>
  23. #include <cm3p/json/writer.h>
  24. #include "cmsys/SystemInformation.hxx"
  25. #include "cmAlgorithms.h"
  26. #include "cmCustomCommand.h"
  27. #include "cmCustomCommandLines.h"
  28. #include "cmEvaluatedTargetProperty.h"
  29. #include "cmGeneratedFileStream.h"
  30. #include "cmGeneratorExpression.h"
  31. #include "cmGeneratorExpressionDAGChecker.h"
  32. #include "cmGeneratorTarget.h"
  33. #include "cmGlobalGenerator.h"
  34. #include "cmLinkItem.h"
  35. #include "cmList.h"
  36. #include "cmListFileCache.h"
  37. #include "cmLocalGenerator.h"
  38. #include "cmMakefile.h"
  39. #include "cmMessageType.h"
  40. #include "cmPolicies.h"
  41. #include "cmQtAutoGen.h"
  42. #include "cmQtAutoGenGlobalInitializer.h"
  43. #include "cmSourceFile.h"
  44. #include "cmSourceFileLocationKind.h"
  45. #include "cmSourceGroup.h"
  46. #include "cmStandardLevelResolver.h"
  47. #include "cmState.h"
  48. #include "cmStateTypes.h"
  49. #include "cmStringAlgorithms.h"
  50. #include "cmSystemTools.h"
  51. #include "cmTarget.h"
  52. #include "cmValue.h"
  53. #include "cmake.h"
  54. namespace {
  55. unsigned int GetParallelCPUCount()
  56. {
  57. static unsigned int count = 0;
  58. // Detect only on the first call
  59. if (count == 0) {
  60. cmsys::SystemInformation info;
  61. info.RunCPUCheck();
  62. count =
  63. cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
  64. }
  65. return count;
  66. }
  67. std::string FileProjectRelativePath(cmMakefile const* makefile,
  68. std::string const& fileName)
  69. {
  70. std::string res;
  71. {
  72. std::string pSource = cmSystemTools::RelativePath(
  73. makefile->GetCurrentSourceDirectory(), fileName);
  74. std::string pBinary = cmSystemTools::RelativePath(
  75. makefile->GetCurrentBinaryDirectory(), fileName);
  76. if (pSource.size() < pBinary.size()) {
  77. res = std::move(pSource);
  78. } else if (pBinary.size() < fileName.size()) {
  79. res = std::move(pBinary);
  80. } else {
  81. res = fileName;
  82. }
  83. }
  84. return res;
  85. }
  86. /**
  87. * Tests if targetDepend is a STATIC_LIBRARY and if any of its
  88. * recursive STATIC_LIBRARY dependencies depends on targetOrigin
  89. * (STATIC_LIBRARY cycle).
  90. */
  91. bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
  92. cmGeneratorTarget const* targetDepend,
  93. std::string const& config)
  94. {
  95. bool cycle = false;
  96. if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  97. (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
  98. std::set<cmGeneratorTarget const*> knownLibs;
  99. std::deque<cmGeneratorTarget const*> testLibs;
  100. // Insert initial static_library dependency
  101. knownLibs.insert(targetDepend);
  102. testLibs.push_back(targetDepend);
  103. while (!testLibs.empty()) {
  104. cmGeneratorTarget const* testTarget = testLibs.front();
  105. testLibs.pop_front();
  106. // Check if the test target is the origin target (cycle)
  107. if (testTarget == targetOrigin) {
  108. cycle = true;
  109. break;
  110. }
  111. // Collect all static_library dependencies from the test target
  112. cmLinkImplementationLibraries const* libs =
  113. testTarget->GetLinkImplementationLibraries(
  114. config, cmGeneratorTarget::UseTo::Link);
  115. if (libs) {
  116. for (cmLinkItem const& item : libs->Libraries) {
  117. cmGeneratorTarget const* depTarget = item.Target;
  118. if (depTarget &&
  119. (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  120. knownLibs.insert(depTarget).second) {
  121. testLibs.push_back(depTarget);
  122. }
  123. }
  124. }
  125. }
  126. }
  127. return cycle;
  128. }
  129. /** Sanitizes file search paths. */
  130. class SearchPathSanitizer
  131. {
  132. public:
  133. SearchPathSanitizer(cmMakefile* makefile)
  134. : SourcePath_(makefile->GetCurrentSourceDirectory())
  135. {
  136. }
  137. std::vector<std::string> operator()(
  138. std::vector<std::string> const& paths) const;
  139. private:
  140. std::string SourcePath_;
  141. };
  142. std::vector<std::string> SearchPathSanitizer::operator()(
  143. std::vector<std::string> const& paths) const
  144. {
  145. std::vector<std::string> res;
  146. res.reserve(paths.size());
  147. for (std::string const& srcPath : paths) {
  148. // Collapse relative paths
  149. std::string path =
  150. cmSystemTools::CollapseFullPath(srcPath, this->SourcePath_);
  151. // Remove suffix slashes
  152. while (cmHasSuffix(path, '/')) {
  153. path.pop_back();
  154. }
  155. // Accept only non empty paths
  156. if (!path.empty()) {
  157. res.emplace_back(std::move(path));
  158. }
  159. }
  160. return res;
  161. }
  162. /** @brief Writes a CMake info file. */
  163. class InfoWriter
  164. {
  165. public:
  166. // -- Single value
  167. void Set(std::string const& key, std::string const& value)
  168. {
  169. this->Value_[key] = value;
  170. }
  171. void SetConfig(std::string const& key,
  172. cmQtAutoGenInitializer::ConfigString const& cfgStr);
  173. void SetBool(std::string const& key, bool value)
  174. {
  175. this->Value_[key] = value;
  176. }
  177. void SetUInt(std::string const& key, unsigned int value)
  178. {
  179. this->Value_[key] = value;
  180. }
  181. // -- Array utility
  182. template <typename CONT>
  183. static bool MakeArray(Json::Value& jval, CONT const& container);
  184. template <typename CONT>
  185. static void MakeStringArray(Json::Value& jval, CONT const& container);
  186. // -- Array value
  187. template <typename CONT>
  188. void SetArray(std::string const& key, CONT const& container);
  189. template <typename CONT>
  190. void SetConfigArray(
  191. std::string const& key,
  192. cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
  193. // -- Array of arrays
  194. template <typename CONT, typename FUNC>
  195. void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
  196. // -- Save to json file
  197. bool Save(std::string const& filename);
  198. private:
  199. Json::Value Value_;
  200. };
  201. void InfoWriter::SetConfig(std::string const& key,
  202. cmQtAutoGenInitializer::ConfigString const& cfgStr)
  203. {
  204. this->Set(key, cfgStr.Default);
  205. for (auto const& item : cfgStr.Config) {
  206. this->Set(cmStrCat(key, '_', item.first), item.second);
  207. }
  208. }
  209. template <typename CONT>
  210. bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
  211. {
  212. jval = Json::arrayValue;
  213. std::size_t const listSize = cm::size(container);
  214. if (listSize == 0) {
  215. return false;
  216. }
  217. jval.resize(static_cast<unsigned int>(listSize));
  218. return true;
  219. }
  220. template <typename CONT>
  221. void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
  222. {
  223. if (MakeArray(jval, container)) {
  224. Json::ArrayIndex ii = 0;
  225. for (std::string const& item : container) {
  226. jval[ii++] = item;
  227. }
  228. }
  229. }
  230. template <typename CONT>
  231. void InfoWriter::SetArray(std::string const& key, CONT const& container)
  232. {
  233. MakeStringArray(this->Value_[key], container);
  234. }
  235. template <typename CONT, typename FUNC>
  236. void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
  237. FUNC func)
  238. {
  239. Json::Value& jval = this->Value_[key];
  240. if (MakeArray(jval, container)) {
  241. Json::ArrayIndex ii = 0;
  242. for (auto const& citem : container) {
  243. Json::Value& aval = jval[ii++];
  244. aval = Json::arrayValue;
  245. func(aval, citem);
  246. }
  247. }
  248. }
  249. template <typename CONT>
  250. void InfoWriter::SetConfigArray(
  251. std::string const& key,
  252. cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
  253. {
  254. this->SetArray(key, cfgStr.Default);
  255. for (auto const& item : cfgStr.Config) {
  256. this->SetArray(cmStrCat(key, '_', item.first), item.second);
  257. }
  258. }
  259. bool InfoWriter::Save(std::string const& filename)
  260. {
  261. cmGeneratedFileStream fileStream;
  262. fileStream.SetCopyIfDifferent(true);
  263. fileStream.Open(filename, false, true);
  264. if (!fileStream) {
  265. return false;
  266. }
  267. Json::StyledStreamWriter jsonWriter;
  268. try {
  269. jsonWriter.write(fileStream, this->Value_);
  270. } catch (...) {
  271. return false;
  272. }
  273. return fileStream.Close();
  274. }
  275. cmQtAutoGen::ConfigStrings<std::vector<std::string>> generateListOptions(
  276. cmQtAutoGen::ConfigStrings<cmQtAutoGen::CompilerFeaturesHandle> const&
  277. executableFeatures,
  278. bool IsMultiConfig)
  279. {
  280. cmQtAutoGen::ConfigStrings<std::vector<std::string>> tempListOptions;
  281. if (IsMultiConfig) {
  282. for (auto const& executableFeature : executableFeatures.Config) {
  283. tempListOptions.Config[executableFeature.first] =
  284. executableFeature.second->ListOptions;
  285. }
  286. } else {
  287. tempListOptions.Default = executableFeatures.Default->ListOptions;
  288. }
  289. return tempListOptions;
  290. }
  291. } // End of unnamed namespace
  292. cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  293. cmQtAutoGenGlobalInitializer* globalInitializer,
  294. cmGeneratorTarget* genTarget, IntegerVersion qtVersion, bool mocEnabled,
  295. bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
  296. bool globalAutoRccTarget)
  297. : GlobalInitializer(globalInitializer)
  298. , GenTarget(genTarget)
  299. , GlobalGen(genTarget->GetGlobalGenerator())
  300. , LocalGen(genTarget->GetLocalGenerator())
  301. , Makefile(genTarget->Makefile)
  302. , PathCheckSum(genTarget->Makefile)
  303. , QtVersion(qtVersion)
  304. {
  305. this->AutogenTarget.GlobalTarget = globalAutogenTarget;
  306. this->Moc.Enabled = mocEnabled;
  307. this->Uic.Enabled = uicEnabled;
  308. this->Rcc.Enabled = rccEnabled;
  309. this->Rcc.GlobalTarget = globalAutoRccTarget;
  310. this->CrossConfig =
  311. !this->Makefile->GetSafeDefinition("CMAKE_CROSS_CONFIGS").empty();
  312. this->UseBetterGraph =
  313. this->GenTarget->GetProperty("AUTOGEN_BETTER_GRAPH_MULTI_CONFIG").IsSet()
  314. ? this->GenTarget->GetProperty("AUTOGEN_BETTER_GRAPH_MULTI_CONFIG").IsOn()
  315. : (this->QtVersion >= IntegerVersion(6, 8));
  316. // AUTOGEN_BETTER_GRAPH_MULTI_CONFIG is set explicitly because it is read by
  317. // the qt library
  318. this->GenTarget->Target->SetProperty("AUTOGEN_BETTER_GRAPH_MULTI_CONFIG",
  319. this->UseBetterGraph ? "ON" : "OFF");
  320. }
  321. void cmQtAutoGenInitializer::AddAutogenExecutableToDependencies(
  322. cmQtAutoGenInitializer::GenVarsT const& genVars,
  323. std::vector<std::string>& dependencies) const
  324. {
  325. if (genVars.ExecutableTarget) {
  326. dependencies.push_back(genVars.ExecutableTarget->Target->GetName());
  327. } else if (this->MultiConfig && this->UseBetterGraph) {
  328. cm::string_view const configGenexWithCommandConfig =
  329. "$<COMMAND_CONFIG:$<$<CONFIG:";
  330. cm::string_view const configGenex = "$<$<CONFIG:";
  331. cm::string_view const configGenexEnd = ">";
  332. cm::string_view const configGenexEndWithCommandConfig = ">>";
  333. auto genexBegin =
  334. this->CrossConfig ? configGenexWithCommandConfig : configGenex;
  335. auto genexEnd =
  336. this->CrossConfig ? configGenexEndWithCommandConfig : configGenexEnd;
  337. for (auto const& config : genVars.Executable.Config) {
  338. auto executableWithConfig =
  339. cmStrCat(genexBegin, config.first, ">:", config.second, genexEnd);
  340. dependencies.emplace_back(std::move(executableWithConfig));
  341. }
  342. } else {
  343. if (!genVars.Executable.Default.empty()) {
  344. dependencies.push_back(genVars.Executable.Default);
  345. }
  346. }
  347. }
  348. bool cmQtAutoGenInitializer::InitCustomTargets()
  349. {
  350. // Configurations
  351. this->MultiConfig = this->GlobalGen->IsMultiConfig();
  352. this->ConfigDefault = this->Makefile->GetDefaultConfiguration();
  353. this->ConfigsList =
  354. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  355. // Verbosity
  356. {
  357. std::string const def =
  358. this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
  359. if (!def.empty()) {
  360. unsigned long iVerb = 0;
  361. if (cmStrToULong(def, &iVerb)) {
  362. // Numeric verbosity
  363. this->Verbosity = static_cast<unsigned int>(iVerb);
  364. } else {
  365. // Non numeric verbosity
  366. if (cmIsOn(def)) {
  367. this->Verbosity = 1;
  368. }
  369. }
  370. }
  371. }
  372. // Targets FOLDER
  373. {
  374. cmValue folder =
  375. this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  376. if (!folder) {
  377. folder = this->Makefile->GetState()->GetGlobalProperty(
  378. "AUTOGEN_TARGETS_FOLDER");
  379. }
  380. // Inherit FOLDER property from target (#13688)
  381. if (!folder) {
  382. folder = this->GenTarget->GetProperty("FOLDER");
  383. }
  384. if (folder) {
  385. this->TargetsFolder = *folder;
  386. }
  387. }
  388. // Check status of policy CMP0071 regarding handling of GENERATED files
  389. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
  390. case cmPolicies::WARN:
  391. // Ignore GENERATED files but warn
  392. this->CMP0071Warn = true;
  393. CM_FALLTHROUGH;
  394. case cmPolicies::OLD:
  395. // Ignore GENERATED files
  396. break;
  397. case cmPolicies::NEW:
  398. // Process GENERATED files
  399. this->CMP0071Accept = true;
  400. break;
  401. }
  402. // Check status of policy CMP0100 regarding handling of .hh headers
  403. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
  404. case cmPolicies::WARN:
  405. // Ignore but .hh files but warn
  406. this->CMP0100Warn = true;
  407. CM_FALLTHROUGH;
  408. case cmPolicies::OLD:
  409. // Ignore .hh files
  410. break;
  411. case cmPolicies::NEW:
  412. // Process .hh file
  413. this->CMP0100Accept = true;
  414. break;
  415. }
  416. // Common directories
  417. std::string relativeBuildDir;
  418. {
  419. // Collapsed current binary directory
  420. std::string const cbd = cmSystemTools::CollapseFullPath(
  421. std::string(), this->Makefile->GetCurrentBinaryDirectory());
  422. std::string infoDir;
  423. std::string buildDir;
  424. auto idirkind = cmStateEnums::IntermediateDirKind::QtAutogenMetadata;
  425. if (this->GenTarget->GetUseShortObjectNames(idirkind)) {
  426. infoDir = cmSystemTools::CollapseFullPath(
  427. std::string(),
  428. cmStrCat(this->GenTarget->GetSupportDirectory(idirkind),
  429. "/autogen_info"));
  430. buildDir = cmSystemTools::CollapseFullPath(
  431. std::string(),
  432. cmStrCat(this->GenTarget->GetSupportDirectory(idirkind), "/autogen"));
  433. } else {
  434. infoDir = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
  435. "_autogen.dir");
  436. buildDir = cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
  437. }
  438. // Info directory
  439. this->Dir.Info = infoDir;
  440. cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
  441. // Build directory
  442. this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
  443. if (this->Dir.Build.empty()) {
  444. this->Dir.Build = buildDir;
  445. }
  446. cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
  447. this->Dir.RelativeBuild =
  448. cmSystemTools::RelativePath(cbd, this->Dir.Build);
  449. // Cleanup build directory
  450. this->AddCleanFile(this->Dir.Build);
  451. // Working directory
  452. this->Dir.Work = cbd;
  453. cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
  454. // Include directory
  455. this->ConfigFileNamesAndGenex(this->Dir.Include, this->Dir.IncludeGenExp,
  456. cmStrCat(this->Dir.Build, "/include"), "");
  457. }
  458. // Moc, Uic and _autogen target settings
  459. if (this->MocOrUicEnabled()) {
  460. // Init moc specific settings
  461. if (this->Moc.Enabled && !this->InitMoc()) {
  462. return false;
  463. }
  464. // Init uic specific settings
  465. if (this->Uic.Enabled && !this->InitUic()) {
  466. return false;
  467. }
  468. // Autogen target name
  469. this->AutogenTarget.Name =
  470. cmStrCat(this->GenTarget->GetName(), "_autogen");
  471. // Autogen target parallel processing
  472. {
  473. using ParallelType = decltype(this->AutogenTarget.Parallel);
  474. unsigned long propInt = 0;
  475. std::string const& prop =
  476. this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
  477. if (prop.empty() || (prop == "AUTO")) {
  478. // Autodetect number of CPUs
  479. this->AutogenTarget.Parallel = GetParallelCPUCount();
  480. } else if (cmStrToULong(prop, &propInt) && propInt > 0 &&
  481. propInt <= std::numeric_limits<ParallelType>::max()) {
  482. this->AutogenTarget.Parallel = static_cast<ParallelType>(propInt);
  483. } else {
  484. // Warn the project author that AUTOGEN_PARALLEL is not valid.
  485. this->Makefile->IssueMessage(
  486. MessageType::AUTHOR_WARNING,
  487. cmStrCat("AUTOGEN_PARALLEL=\"", prop, "\" for target \"",
  488. this->GenTarget->GetName(),
  489. "\" is not valid. Using AUTOGEN_PARALLEL=1"));
  490. this->AutogenTarget.Parallel = 1;
  491. }
  492. }
  493. #ifdef _WIN32
  494. {
  495. auto const& value =
  496. this->GenTarget->GetProperty("AUTOGEN_COMMAND_LINE_LENGTH_MAX");
  497. if (value.IsSet()) {
  498. using maxCommandLineLengthType =
  499. decltype(this->AutogenTarget.MaxCommandLineLength);
  500. unsigned long propInt = 0;
  501. if (cmStrToULong(value, &propInt) && propInt > 0 &&
  502. propInt <= std::numeric_limits<maxCommandLineLengthType>::max()) {
  503. this->AutogenTarget.MaxCommandLineLength =
  504. static_cast<maxCommandLineLengthType>(propInt);
  505. } else {
  506. // Warn the project author that AUTOGEN_PARALLEL is not valid.
  507. this->Makefile->IssueMessage(
  508. MessageType::AUTHOR_WARNING,
  509. cmStrCat("AUTOGEN_COMMAND_LINE_LENGTH_MAX=\"", *value,
  510. "\" for target \"", this->GenTarget->GetName(),
  511. "\" is not valid. Using no limit for "
  512. "AUTOGEN_COMMAND_LINE_LENGTH_MAX"));
  513. this->AutogenTarget.MaxCommandLineLength =
  514. std::numeric_limits<maxCommandLineLengthType>::max();
  515. }
  516. } else {
  517. // Actually 32767 (see
  518. // https://devblogs.microsoft.com/oldnewthing/20031210-00/?p=41553) but
  519. // we allow for a small margin
  520. this->AutogenTarget.MaxCommandLineLength = 32000;
  521. }
  522. }
  523. #endif
  524. // Autogen target info and settings files
  525. {
  526. // Info file
  527. this->AutogenTarget.InfoFile =
  528. cmStrCat(this->Dir.Info, "/AutogenInfo.json");
  529. // Used settings file
  530. this->ConfigFileNames(this->AutogenTarget.SettingsFile,
  531. cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
  532. this->ConfigFileClean(this->AutogenTarget.SettingsFile);
  533. // Parse cache file
  534. this->ConfigFileNames(this->AutogenTarget.ParseCacheFile,
  535. cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
  536. this->ConfigFileClean(this->AutogenTarget.ParseCacheFile);
  537. }
  538. // Autogen target: Compute user defined dependencies
  539. {
  540. this->AutogenTarget.DependOrigin =
  541. this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  542. std::string const& deps =
  543. this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  544. if (!deps.empty()) {
  545. for (auto const& depName : cmList{ deps }) {
  546. // Allow target and file dependencies
  547. auto* depTarget = this->Makefile->FindTargetToUse(depName);
  548. if (depTarget) {
  549. this->AutogenTarget.DependTargets.insert(depTarget);
  550. } else {
  551. this->AutogenTarget.DependFiles.insert(depName);
  552. }
  553. }
  554. }
  555. }
  556. if (this->Moc.Enabled) {
  557. // Path prefix
  558. if (this->GenTarget->GetProperty("AUTOMOC_PATH_PREFIX").IsOn()) {
  559. this->Moc.PathPrefix = true;
  560. }
  561. // CMAKE_AUTOMOC_RELAXED_MODE
  562. if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
  563. this->Moc.RelaxedMode = true;
  564. this->Makefile->IssueMessage(
  565. MessageType::AUTHOR_WARNING,
  566. cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
  567. "deprecated an will be removed in the future. Consider "
  568. "disabling it and converting the target ",
  569. this->GenTarget->GetName(), " to regular mode."));
  570. }
  571. // Options
  572. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
  573. this->Moc.Options);
  574. // Filters
  575. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
  576. this->Moc.MacroNames);
  577. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  578. this->Moc.MacroNames.end());
  579. {
  580. cmList const filterList = { this->GenTarget->GetSafeProperty(
  581. "AUTOMOC_DEPEND_FILTERS") };
  582. if ((filterList.size() % 2) != 0) {
  583. cmSystemTools::Error(
  584. cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
  585. filterList.size(), " is not a multiple of 2."));
  586. return false;
  587. }
  588. this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
  589. this->Moc.DependFilters.emplace_back(
  590. "Q_PLUGIN_METADATA",
  591. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  592. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  593. for (cmList::size_type ii = 0; ii != filterList.size(); ii += 2) {
  594. this->Moc.DependFilters.emplace_back(filterList[ii],
  595. filterList[ii + 1]);
  596. }
  597. }
  598. }
  599. }
  600. // Init rcc specific settings
  601. if (this->Rcc.Enabled && !this->InitRcc()) {
  602. return false;
  603. }
  604. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  605. if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
  606. auto addBefore = false;
  607. auto const& value =
  608. this->GenTarget->GetProperty("AUTOGEN_USE_SYSTEM_INCLUDE");
  609. if (value.IsSet()) {
  610. if (value.IsOn()) {
  611. this->GenTarget->AddSystemIncludeDirectory(this->Dir.IncludeGenExp,
  612. "CXX");
  613. } else {
  614. addBefore = true;
  615. }
  616. } else {
  617. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0151)) {
  618. case cmPolicies::WARN:
  619. case cmPolicies::OLD:
  620. addBefore = true;
  621. break;
  622. case cmPolicies::NEW:
  623. this->GenTarget->AddSystemIncludeDirectory(this->Dir.IncludeGenExp,
  624. "CXX");
  625. break;
  626. }
  627. }
  628. this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, addBefore);
  629. }
  630. // Scan files
  631. if (!this->InitScanFiles()) {
  632. return false;
  633. }
  634. // Create autogen target
  635. if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
  636. return false;
  637. }
  638. // Create rcc targets
  639. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  640. return false;
  641. }
  642. return true;
  643. }
  644. bool cmQtAutoGenInitializer::InitMoc()
  645. {
  646. // Mocs compilation file
  647. if (this->GlobalGen->IsXcode()) {
  648. // XXX(xcode-per-cfg-src): Drop this Xcode-specific code path
  649. // when the Xcode generator supports per-config sources.
  650. this->Moc.CompilationFile.Default =
  651. cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
  652. this->Moc.CompilationFileGenex = this->Moc.CompilationFile.Default;
  653. } else {
  654. this->ConfigFileNamesAndGenex(
  655. this->Moc.CompilationFile, this->Moc.CompilationFileGenex,
  656. cmStrCat(this->Dir.Build, "/mocs_compilation"_s), ".cpp"_s);
  657. }
  658. // Moc predefs
  659. if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  660. (this->QtVersion >= IntegerVersion(5, 8))) {
  661. // Command
  662. cmList::assign(
  663. this->Moc.PredefsCmd,
  664. this->Makefile->GetDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
  665. // Header
  666. if (!this->Moc.PredefsCmd.empty()) {
  667. this->ConfigFileNames(this->Moc.PredefsFile,
  668. cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
  669. }
  670. }
  671. // Moc includes
  672. {
  673. // If the property AUTOMOC_INCLUDE_DIRECTORIES is set on the target,
  674. // use its value for moc include paths instead of gathering all
  675. // include directories from the target.
  676. cmValue autoIncDirs =
  677. this->GenTarget->GetProperty("AUTOMOC_INCLUDE_DIRECTORIES");
  678. if (autoIncDirs) {
  679. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  680. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  681. auto cge = ge.Parse(*autoIncDirs);
  682. // Build a single list of configs to iterate, whether single or multi
  683. std::vector<std::string> configs = this->MultiConfig
  684. ? this->ConfigsList
  685. : std::vector<std::string>{ this->ConfigDefault };
  686. for (auto const& cfg : configs) {
  687. std::string eval = cge->Evaluate(this->LocalGen, cfg);
  688. std::vector<std::string> incList = cmList(eval);
  689. // Validate absolute paths
  690. for (auto const& path : incList) {
  691. if (!cmGeneratorExpression::StartsWithGeneratorExpression(path) &&
  692. !cmSystemTools::FileIsFullPath(path)) {
  693. this->Makefile->IssueMessage(
  694. MessageType::FATAL_ERROR,
  695. cmStrCat("AUTOMOC_INCLUDE_DIRECTORIES: path '", path,
  696. "' is not absolute."));
  697. return false;
  698. }
  699. }
  700. if (this->MultiConfig) {
  701. this->Moc.Includes.Config[cfg] = std::move(incList);
  702. } else {
  703. this->Moc.Includes.Default = std::move(incList);
  704. }
  705. }
  706. } else {
  707. // Otherwise, discover include directories from the target for moc.
  708. SearchPathSanitizer const sanitizer(this->Makefile);
  709. auto getDirs = [this, &sanitizer](
  710. std::string const& cfg) -> std::vector<std::string> {
  711. // Get the include dirs for this target, without stripping the implicit
  712. // include dirs off, see issue #13667.
  713. std::vector<std::string> dirs;
  714. bool const appendImplicit = (this->QtVersion.Major >= 5);
  715. this->LocalGen->GetIncludeDirectoriesImplicit(
  716. dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
  717. return sanitizer(dirs);
  718. };
  719. // Other configuration settings
  720. if (this->MultiConfig) {
  721. for (std::string const& cfg : this->ConfigsList) {
  722. std::vector<std::string> dirs = getDirs(cfg);
  723. if (dirs == this->Moc.Includes.Default) {
  724. continue;
  725. }
  726. this->Moc.Includes.Config[cfg] = std::move(dirs);
  727. }
  728. } else {
  729. // Default configuration include directories
  730. this->Moc.Includes.Default = getDirs(this->ConfigDefault);
  731. }
  732. }
  733. }
  734. // Moc compile definitions
  735. {
  736. auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
  737. std::set<std::string> defines;
  738. this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
  739. if (this->Moc.PredefsCmd.empty() &&
  740. this->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME") ==
  741. "Windows") {
  742. // Add WIN32 definition if we don't have a moc_predefs.h
  743. defines.insert("WIN32");
  744. }
  745. return defines;
  746. };
  747. // Other configuration defines
  748. if (this->MultiConfig) {
  749. for (std::string const& cfg : this->ConfigsList) {
  750. std::set<std::string> defines = getDefs(cfg);
  751. if (defines == this->Moc.Defines.Default) {
  752. continue;
  753. }
  754. this->Moc.Defines.Config[cfg] = std::move(defines);
  755. }
  756. } else {
  757. // Default configuration defines
  758. this->Moc.Defines.Default = getDefs(this->ConfigDefault);
  759. }
  760. }
  761. // Moc executable
  762. {
  763. if (!this->GetQtExecutable(this->Moc, "moc", false)) {
  764. return false;
  765. }
  766. // Let the _autogen target depend on the moc executable
  767. if (this->Moc.ExecutableTarget) {
  768. this->AutogenTarget.DependTargets.insert(
  769. this->Moc.ExecutableTarget->Target);
  770. }
  771. }
  772. return true;
  773. }
  774. bool cmQtAutoGenInitializer::InitUic()
  775. {
  776. // Uic search paths
  777. {
  778. std::string const& usp =
  779. this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
  780. if (!usp.empty()) {
  781. this->Uic.SearchPaths =
  782. SearchPathSanitizer(this->Makefile)(cmList{ usp });
  783. }
  784. }
  785. // Uic target options
  786. {
  787. auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
  788. std::vector<std::string> opts;
  789. this->GenTarget->GetAutoUicOptions(opts, cfg);
  790. return opts;
  791. };
  792. // Default options
  793. this->Uic.Options.Default = getOpts(this->ConfigDefault);
  794. // Configuration specific options
  795. if (this->MultiConfig) {
  796. for (std::string const& cfg : this->ConfigsList) {
  797. std::vector<std::string> options = getOpts(cfg);
  798. if (options == this->Uic.Options.Default) {
  799. continue;
  800. }
  801. this->Uic.Options.Config[cfg] = std::move(options);
  802. }
  803. }
  804. }
  805. // Uic executable
  806. {
  807. if (!this->GetQtExecutable(this->Uic, "uic", true)) {
  808. return false;
  809. }
  810. // Let the _autogen target depend on the uic executable
  811. if (this->Uic.ExecutableTarget) {
  812. this->AutogenTarget.DependTargets.insert(
  813. this->Uic.ExecutableTarget->Target);
  814. }
  815. }
  816. return true;
  817. }
  818. bool cmQtAutoGenInitializer::InitRcc()
  819. {
  820. // Rcc executable
  821. {
  822. if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
  823. return false;
  824. }
  825. // Evaluate test output on demand
  826. auto& features = this->Rcc.ExecutableFeatures;
  827. auto checkAndAddOptions = [this](CompilerFeaturesHandle& feature) {
  828. if (!feature->Evaluated) {
  829. // Look for list options
  830. if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
  831. static std::array<std::string, 2> const listOptions{ { "--list",
  832. "-list" } };
  833. for (std::string const& opt : listOptions) {
  834. if (feature->HelpOutput.find(opt) != std::string::npos) {
  835. feature->ListOptions.emplace_back(opt);
  836. break;
  837. }
  838. }
  839. }
  840. // Evaluation finished
  841. feature->Evaluated = true;
  842. }
  843. };
  844. if (this->MultiConfig && this->UseBetterGraph) {
  845. for (auto const& config : this->ConfigsList) {
  846. checkAndAddOptions(features.Config[config]);
  847. }
  848. } else {
  849. checkAndAddOptions(features.Default);
  850. }
  851. }
  852. // Disable zstd if it is not supported
  853. {
  854. if (this->QtVersion.Major >= 6) {
  855. std::string const qtFeatureZSTD = "QT_FEATURE_zstd";
  856. if (this->GenTarget->Target->GetMakefile()->IsDefinitionSet(
  857. qtFeatureZSTD)) {
  858. auto const zstdDef =
  859. this->GenTarget->Target->GetMakefile()->GetSafeDefinition(
  860. qtFeatureZSTD);
  861. auto const zstdVal = cmValue(zstdDef);
  862. if (zstdVal.IsOff()) {
  863. auto const& kw = this->GlobalInitializer->kw();
  864. auto rccOptions =
  865. this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS);
  866. std::string const nozstd = "--no-zstd";
  867. if (rccOptions.find(nozstd) == std::string::npos) {
  868. rccOptions.append(";" + nozstd + ";");
  869. }
  870. this->GenTarget->Target->SetProperty(kw.AUTORCC_OPTIONS, rccOptions);
  871. }
  872. }
  873. }
  874. }
  875. return true;
  876. }
  877. bool cmQtAutoGenInitializer::InitScanFiles()
  878. {
  879. cmake const* cm = this->Makefile->GetCMakeInstance();
  880. auto const& kw = this->GlobalInitializer->kw();
  881. auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
  882. std::vector<size_t> const& configs,
  883. bool muIt) -> MUFileHandle {
  884. MUFileHandle muf = cm::make_unique<MUFile>();
  885. muf->FullPath = fullPath;
  886. muf->SF = sf;
  887. if (!configs.empty() && configs.size() != this->ConfigsList.size()) {
  888. muf->Configs = configs;
  889. }
  890. muf->Generated = sf->GetIsGenerated();
  891. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  892. muf->SkipMoc = this->Moc.Enabled &&
  893. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
  894. muf->SkipUic = this->Uic.Enabled &&
  895. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  896. if (muIt) {
  897. muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
  898. muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
  899. }
  900. return muf;
  901. };
  902. auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
  903. cmSourceFile* sf = muf->SF;
  904. bool const muIt = (muf->MocIt || muf->UicIt);
  905. if (this->CMP0100Accept || (extension != "hh")) {
  906. // Accept
  907. if (muIt && muf->Generated) {
  908. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  909. }
  910. this->AutogenTarget.Headers.emplace(sf, std::move(muf));
  911. } else if (muIt && this->CMP0100Warn) {
  912. // Store file for warning message
  913. this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
  914. }
  915. };
  916. auto addMUSource = [this](MUFileHandle&& muf) {
  917. if ((muf->MocIt || muf->UicIt) && muf->Generated) {
  918. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  919. }
  920. this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
  921. };
  922. // Scan through target files
  923. {
  924. // Scan through target files
  925. for (cmGeneratorTarget::AllConfigSource const& acs :
  926. this->GenTarget->GetAllConfigSources()) {
  927. std::string const& fullPath = acs.Source->GetFullPath();
  928. std::string const& extLower =
  929. cmSystemTools::LowerCase(acs.Source->GetExtension());
  930. // Register files that will be scanned by moc or uic
  931. if (this->MocOrUicEnabled()) {
  932. if (cm->IsAHeaderExtension(extLower)) {
  933. addMUHeader(makeMUFile(acs.Source, fullPath, acs.Configs, true),
  934. extLower);
  935. } else if (cm->IsACLikeSourceExtension(extLower)) {
  936. addMUSource(makeMUFile(acs.Source, fullPath, acs.Configs, true));
  937. }
  938. }
  939. // Register rcc enabled files
  940. if (this->Rcc.Enabled) {
  941. if ((extLower == kw.qrc) &&
  942. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
  943. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
  944. // Register qrc file
  945. Qrc qrc;
  946. qrc.QrcFile = fullPath;
  947. qrc.QrcName =
  948. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  949. qrc.Generated = acs.Source->GetIsGenerated();
  950. // RCC options
  951. {
  952. std::string const& opts =
  953. acs.Source->GetSafeProperty(kw.AUTORCC_OPTIONS);
  954. if (!opts.empty()) {
  955. cmExpandList(opts, qrc.Options);
  956. }
  957. }
  958. this->Rcc.Qrcs.push_back(std::move(qrc));
  959. }
  960. }
  961. }
  962. }
  963. // cmGeneratorTarget::GetAllConfigSources computes the target's
  964. // sources meta data cache. Clear it so that OBJECT library targets that
  965. // are AUTOGEN initialized after this target get their added
  966. // mocs_compilation.cpp source acknowledged by this target.
  967. this->GenTarget->ClearSourcesCache();
  968. // For source files find additional headers and private headers
  969. if (this->MocOrUicEnabled()) {
  970. // Header search suffixes and extensions
  971. static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
  972. auto const& exts = cm->GetHeaderExtensions();
  973. // Scan through sources
  974. for (auto const& pair : this->AutogenTarget.Sources) {
  975. MUFile const& muf = *pair.second;
  976. if (muf.MocIt || muf.UicIt) {
  977. // Search for the default header file and a private header
  978. std::string const& srcFullPath = muf.SF->ResolveFullPath();
  979. std::string const basePath = cmStrCat(
  980. cmQtAutoGen::SubDirPrefix(srcFullPath),
  981. cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
  982. for (auto const& suffix : suffixes) {
  983. std::string const suffixedPath = cmStrCat(basePath, suffix);
  984. for (auto const& ext : exts) {
  985. std::string const fullPath = cmStrCat(suffixedPath, '.', ext);
  986. auto constexpr locationKind = cmSourceFileLocationKind::Known;
  987. cmSourceFile* sf =
  988. this->Makefile->GetSource(fullPath, locationKind);
  989. if (sf) {
  990. // Check if we know about this header already
  991. if (cm::contains(this->AutogenTarget.Headers, sf)) {
  992. continue;
  993. }
  994. // We only accept not-GENERATED files that do exist.
  995. if (!sf->GetIsGenerated() &&
  996. !cmSystemTools::FileExists(fullPath)) {
  997. continue;
  998. }
  999. } else if (cmSystemTools::FileExists(fullPath)) {
  1000. // Create a new source file for the existing file
  1001. sf = this->Makefile->CreateSource(fullPath, false, locationKind);
  1002. }
  1003. if (sf) {
  1004. auto eMuf = makeMUFile(sf, fullPath, muf.Configs, true);
  1005. // Only process moc/uic when the parent is processed as well
  1006. if (!muf.MocIt) {
  1007. eMuf->MocIt = false;
  1008. }
  1009. if (!muf.UicIt) {
  1010. eMuf->UicIt = false;
  1011. }
  1012. addMUHeader(std::move(eMuf), ext);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. }
  1018. }
  1019. // Scan through all source files in the makefile to extract moc and uic
  1020. // parameters. Historically we support non target source file parameters.
  1021. // The reason is that their file names might be discovered from source files
  1022. // at generation time.
  1023. if (this->MocOrUicEnabled()) {
  1024. for (auto const& sf : this->Makefile->GetSourceFiles()) {
  1025. // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
  1026. // Since we're iterating over source files that might be not in the
  1027. // target we need to check for path errors (not existing files).
  1028. std::string pathError;
  1029. std::string const& fullPath = sf->ResolveFullPath(&pathError);
  1030. if (!pathError.empty() || fullPath.empty()) {
  1031. continue;
  1032. }
  1033. std::string const& extLower =
  1034. cmSystemTools::LowerCase(sf->GetExtension());
  1035. if (cm->IsAHeaderExtension(extLower)) {
  1036. if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
  1037. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  1038. if (muf->SkipMoc || muf->SkipUic) {
  1039. addMUHeader(std::move(muf), extLower);
  1040. }
  1041. }
  1042. } else if (cm->IsACLikeSourceExtension(extLower)) {
  1043. if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
  1044. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  1045. if (muf->SkipMoc || muf->SkipUic) {
  1046. addMUSource(std::move(muf));
  1047. }
  1048. }
  1049. } else if (this->Uic.Enabled && (extLower == kw.ui)) {
  1050. // .ui file
  1051. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  1052. bool const skipUic =
  1053. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  1054. if (!skipUic) {
  1055. // Check if the .ui file has uic options
  1056. std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
  1057. if (uicOpts.empty()) {
  1058. this->Uic.UiFilesNoOptions.emplace_back(fullPath);
  1059. } else {
  1060. this->Uic.UiFilesWithOptions.emplace_back(
  1061. fullPath, std::move(cmList{ uicOpts }.data()));
  1062. }
  1063. auto uiHeaderRelativePath = cmSystemTools::RelativePath(
  1064. this->LocalGen->GetCurrentSourceDirectory(),
  1065. cmSystemTools::GetFilenamePath(fullPath));
  1066. // Avoid creating a path containing adjacent slashes
  1067. if (!uiHeaderRelativePath.empty() &&
  1068. uiHeaderRelativePath.back() != '/') {
  1069. uiHeaderRelativePath += '/';
  1070. }
  1071. auto uiHeaderFilePath = cmStrCat(
  1072. '/', uiHeaderRelativePath, "ui_"_s,
  1073. cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
  1074. ConfigString uiHeader;
  1075. std::string uiHeaderGenex;
  1076. this->ConfigFileNamesAndGenex(
  1077. uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
  1078. uiHeaderFilePath);
  1079. this->Uic.UiHeaders.emplace_back(uiHeader, uiHeaderGenex);
  1080. } else {
  1081. // Register skipped .ui file
  1082. this->Uic.SkipUi.insert(fullPath);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. // Process GENERATED sources and headers
  1088. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  1089. if (this->CMP0071Accept) {
  1090. // Let the autogen target depend on the GENERATED files
  1091. if (this->MultiConfig && !this->CrossConfig) {
  1092. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1093. if (muf->Configs.empty()) {
  1094. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  1095. } else {
  1096. for (size_t ci : muf->Configs) {
  1097. std::string const& config = this->ConfigsList[ci];
  1098. std::string const& pathWithConfig =
  1099. cmStrCat("$<$<CONFIG:", config, ">:", muf->FullPath, '>');
  1100. this->AutogenTarget.DependFiles.insert(pathWithConfig);
  1101. }
  1102. }
  1103. }
  1104. } else {
  1105. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1106. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  1107. }
  1108. }
  1109. } else if (this->CMP0071Warn) {
  1110. cm::string_view property;
  1111. if (this->Moc.Enabled && this->Uic.Enabled) {
  1112. property = "SKIP_AUTOGEN";
  1113. } else if (this->Moc.Enabled) {
  1114. property = "SKIP_AUTOMOC";
  1115. } else if (this->Uic.Enabled) {
  1116. property = "SKIP_AUTOUIC";
  1117. }
  1118. std::string files;
  1119. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1120. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  1121. }
  1122. this->Makefile->IssueMessage(
  1123. MessageType::AUTHOR_WARNING,
  1124. cmStrCat(
  1125. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071),
  1126. "\n"
  1127. "For compatibility, CMake is excluding the GENERATED source "
  1128. "file(s):\n",
  1129. files, "from processing by ",
  1130. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1131. ". If any of the files should be processed, set CMP0071 to NEW. "
  1132. "If any of the files should not be processed, "
  1133. "explicitly exclude them by setting the source file property ",
  1134. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  1135. " ON)\n"));
  1136. }
  1137. }
  1138. // Generate CMP0100 warning
  1139. if (this->MocOrUicEnabled() &&
  1140. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  1141. cm::string_view property;
  1142. if (this->Moc.Enabled && this->Uic.Enabled) {
  1143. property = "SKIP_AUTOGEN";
  1144. } else if (this->Moc.Enabled) {
  1145. property = "SKIP_AUTOMOC";
  1146. } else if (this->Uic.Enabled) {
  1147. property = "SKIP_AUTOUIC";
  1148. }
  1149. std::string files;
  1150. for (cmSourceFile const* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  1151. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  1152. }
  1153. this->Makefile->IssueMessage(
  1154. MessageType::AUTHOR_WARNING,
  1155. cmStrCat(
  1156. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100),
  1157. "\n"
  1158. "For compatibility, CMake is excluding the header file(s):\n",
  1159. files, "from processing by ",
  1160. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1161. ". If any of the files should be processed, set CMP0100 to NEW. "
  1162. "If any of the files should not be processed, "
  1163. "explicitly exclude them by setting the source file property ",
  1164. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  1165. " ON)\n"));
  1166. }
  1167. // Process qrc files
  1168. if (!this->Rcc.Qrcs.empty()) {
  1169. bool const modernQt = (this->QtVersion.Major >= 5);
  1170. // Target rcc options
  1171. cmList const optionsTarget{ this->GenTarget->GetSafeProperty(
  1172. kw.AUTORCC_OPTIONS) };
  1173. // Check if file name is unique
  1174. for (Qrc& qrc : this->Rcc.Qrcs) {
  1175. qrc.Unique = true;
  1176. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  1177. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  1178. qrc.Unique = false;
  1179. break;
  1180. }
  1181. }
  1182. }
  1183. // Path checksum and file names
  1184. for (Qrc& qrc : this->Rcc.Qrcs) {
  1185. // Path checksum
  1186. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  1187. // Output file name
  1188. if (this->MultiConfig && !this->GlobalGen->IsXcode() &&
  1189. this->UseBetterGraph) {
  1190. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1191. "_$<CONFIG>/qrc_", qrc.QrcName, ".cpp");
  1192. } else {
  1193. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1194. "/qrc_", qrc.QrcName, ".cpp");
  1195. }
  1196. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  1197. qrc.QrcName, '_', qrc.QrcPathChecksum);
  1198. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  1199. qrc.InfoFile = cmStrCat(base, "_Info.json");
  1200. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  1201. }
  1202. // rcc options
  1203. for (Qrc& qrc : this->Rcc.Qrcs) {
  1204. // Target options
  1205. std::vector<std::string> opts = optionsTarget;
  1206. // Merge computed "-name XYZ" option
  1207. {
  1208. std::string name = qrc.QrcName;
  1209. // Replace '-' with '_'. The former is not valid for symbol names.
  1210. std::replace(name.begin(), name.end(), '-', '_');
  1211. if (!qrc.Unique) {
  1212. name += cmStrCat('_', qrc.QrcPathChecksum);
  1213. }
  1214. std::vector<std::string> nameOpts;
  1215. nameOpts.emplace_back("-name");
  1216. nameOpts.emplace_back(std::move(name));
  1217. RccMergeOptions(opts, nameOpts, modernQt);
  1218. }
  1219. // Merge file option
  1220. RccMergeOptions(opts, qrc.Options, modernQt);
  1221. qrc.Options = std::move(opts);
  1222. }
  1223. // rcc resources
  1224. for (Qrc& qrc : this->Rcc.Qrcs) {
  1225. if (!qrc.Generated) {
  1226. std::string error;
  1227. if (this->MultiConfig && this->UseBetterGraph) {
  1228. for (auto const& config : this->ConfigsList) {
  1229. RccLister const lister(
  1230. this->Rcc.Executable.Config[config],
  1231. this->Rcc.ExecutableFeatures.Config[config]->ListOptions);
  1232. if (!lister.list(qrc.QrcFile, qrc.Resources.Config[config],
  1233. error)) {
  1234. cmSystemTools::Error(error);
  1235. return false;
  1236. }
  1237. }
  1238. } else {
  1239. RccLister const lister(
  1240. this->Rcc.Executable.Default,
  1241. this->Rcc.ExecutableFeatures.Default->ListOptions);
  1242. if (!lister.list(qrc.QrcFile, qrc.Resources.Default, error)) {
  1243. cmSystemTools::Error(error);
  1244. return false;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. }
  1250. return true;
  1251. }
  1252. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1253. {
  1254. // Register info file as generated by CMake
  1255. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1256. // Determine whether to use a depfile for the AUTOGEN target.
  1257. bool const useDepfile = [this]() -> bool {
  1258. auto const& gen = this->GlobalGen->GetName();
  1259. return this->QtVersion >= IntegerVersion(5, 15) &&
  1260. (gen.find("Ninja") != std::string::npos ||
  1261. gen.find("Make") != std::string::npos);
  1262. }();
  1263. // Files provided by the autogen target
  1264. std::vector<std::string> autogenByproducts;
  1265. std::vector<std::string> timestampByproducts;
  1266. if (this->Moc.Enabled) {
  1267. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1268. if (useDepfile) {
  1269. if (this->CrossConfig &&
  1270. this->GlobalGen->GetName().find("Ninja") != std::string::npos &&
  1271. !this->UseBetterGraph) {
  1272. // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
  1273. // ${target}_autogen/timestamp custom command.
  1274. // We cannot just use Moc.CompilationFileGenex here, because that
  1275. // custom command runs cmake_autogen for each configuration.
  1276. for (auto const& p : this->Moc.CompilationFile.Config) {
  1277. timestampByproducts.push_back(p.second);
  1278. }
  1279. } else {
  1280. timestampByproducts.push_back(this->Moc.CompilationFileGenex);
  1281. }
  1282. } else {
  1283. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1284. }
  1285. }
  1286. if (this->Uic.Enabled) {
  1287. for (auto const& file : this->Uic.UiHeaders) {
  1288. this->AddGeneratedSource(file.first, this->Uic);
  1289. autogenByproducts.push_back(file.second);
  1290. }
  1291. }
  1292. // Compose target comment
  1293. std::string autogenComment;
  1294. {
  1295. std::string tools;
  1296. if (this->Moc.Enabled) {
  1297. tools += "MOC";
  1298. }
  1299. if (this->Uic.Enabled) {
  1300. if (!tools.empty()) {
  1301. tools += " and ";
  1302. }
  1303. tools += "UIC";
  1304. }
  1305. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1306. this->GenTarget->GetName());
  1307. }
  1308. // Compose command lines
  1309. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1310. // instead of fiddling with the include directories
  1311. bool constexpr stdPipesUTF8 = true;
  1312. cmCustomCommandLines commandLines;
  1313. AddCMakeProcessToCommandLines(this->AutogenTarget.InfoFile, "cmake_autogen",
  1314. commandLines);
  1315. // Use PRE_BUILD on demand
  1316. bool usePRE_BUILD = false;
  1317. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1318. // Under VS use a PRE_BUILD event instead of a separate target to
  1319. // reduce the number of targets loaded into the IDE.
  1320. // This also works around a VS 11 bug that may skip updating the target:
  1321. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1322. usePRE_BUILD = true;
  1323. }
  1324. // Disable PRE_BUILD in some cases
  1325. if (usePRE_BUILD) {
  1326. // Cannot use PRE_BUILD with file depends
  1327. if (!this->AutogenTarget.DependFiles.empty()) {
  1328. usePRE_BUILD = false;
  1329. }
  1330. // Cannot use PRE_BUILD when a global autogen target is in place
  1331. if (this->AutogenTarget.GlobalTarget) {
  1332. usePRE_BUILD = false;
  1333. }
  1334. }
  1335. // Create the autogen target/command
  1336. if (usePRE_BUILD) {
  1337. // Add additional autogen target dependencies to origin target
  1338. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1339. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1340. this->Makefile);
  1341. }
  1342. if (!this->Uic.UiFilesNoOptions.empty() ||
  1343. !this->Uic.UiFilesWithOptions.empty()) {
  1344. // Add a generated timestamp file
  1345. ConfigString timestampFile;
  1346. std::string timestampFileGenex;
  1347. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1348. cmStrCat(this->Dir.Build, "/autouic"_s),
  1349. ".stamp"_s);
  1350. this->AddGeneratedSource(timestampFile, this->Uic);
  1351. // Add a step in the pre-build command to touch the timestamp file
  1352. commandLines.push_back(
  1353. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1354. timestampFileGenex }));
  1355. // UIC needs to be re-run if any of the known UI files change or the
  1356. // executable itself has been updated
  1357. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1358. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1359. uicDependencies.push_back(uiFile.first);
  1360. }
  1361. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1362. // Add a rule file to cause the target to build if a dependency has
  1363. // changed, which will trigger the pre-build command to run autogen
  1364. auto cc = cm::make_unique<cmCustomCommand>();
  1365. cc->SetOutputs(timestampFileGenex);
  1366. cc->SetDepends(uicDependencies);
  1367. cc->SetComment("");
  1368. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1369. cc->SetEscapeOldStyle(false);
  1370. cc->SetStdPipesUTF8(stdPipesUTF8);
  1371. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1372. }
  1373. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1374. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1375. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1376. //
  1377. // PRE_BUILD does not support file dependencies!
  1378. cmCustomCommand cc;
  1379. cc.SetByproducts(autogenByproducts);
  1380. cc.SetCommandLines(commandLines);
  1381. cc.SetComment(autogenComment.c_str());
  1382. cc.SetBacktrace(this->Makefile->GetBacktrace());
  1383. cc.SetWorkingDirectory(this->Dir.Work.c_str());
  1384. cc.SetStdPipesUTF8(stdPipesUTF8);
  1385. cc.SetEscapeOldStyle(false);
  1386. cc.SetEscapeAllowMakeVars(true);
  1387. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1388. } else {
  1389. // Add link library target dependencies to the autogen target
  1390. // dependencies
  1391. if (this->AutogenTarget.DependOrigin) {
  1392. // add_dependencies/addUtility do not support generator expressions.
  1393. // We depend only on the libraries found in all configs therefore.
  1394. std::map<cmGeneratorTarget const*, std::size_t> targetsPartOfAllConfigs;
  1395. for (std::string const& config : this->ConfigsList) {
  1396. // The same target might appear multiple times in a config, but we
  1397. // should only count it once.
  1398. std::set<cmGeneratorTarget const*> seenTargets;
  1399. cmLinkImplementationLibraries const* libs =
  1400. this->GenTarget->GetLinkImplementationLibraries(
  1401. config, cmGeneratorTarget::UseTo::Link);
  1402. if (libs) {
  1403. for (cmLinkItem const& item : libs->Libraries) {
  1404. cmGeneratorTarget const* libTarget = item.Target;
  1405. if (libTarget &&
  1406. !StaticLibraryCycle(this->GenTarget, libTarget, config) &&
  1407. seenTargets.insert(libTarget).second) {
  1408. // Increment target config count
  1409. targetsPartOfAllConfigs[libTarget]++;
  1410. }
  1411. }
  1412. }
  1413. }
  1414. for (auto const& item : targetsPartOfAllConfigs) {
  1415. if (item.second == this->ConfigsList.size()) {
  1416. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1417. }
  1418. }
  1419. }
  1420. cmTarget* timestampTarget = nullptr;
  1421. std::vector<std::string> dependencies(
  1422. this->AutogenTarget.DependFiles.begin(),
  1423. this->AutogenTarget.DependFiles.end());
  1424. if (useDepfile) {
  1425. // Create a custom command that generates a timestamp file and
  1426. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1427. //
  1428. // Also create an additional '_autogen_timestamp_deps' that the custom
  1429. // command will depend on. It will have no sources or commands to
  1430. // execute, but it will have dependencies that would originally be
  1431. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1432. // serve as a list of order-only dependencies for the custom command,
  1433. // without forcing the custom command to re-execute.
  1434. //
  1435. // The dependency tree would then look like
  1436. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1437. // '_autogen' target.
  1438. auto const timestampTargetName =
  1439. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1440. auto cc = cm::make_unique<cmCustomCommand>();
  1441. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1442. cc->SetDepends(dependencies);
  1443. cc->SetEscapeOldStyle(false);
  1444. timestampTarget = this->LocalGen->AddUtilityCommand(timestampTargetName,
  1445. true, std::move(cc));
  1446. this->LocalGen->AddGeneratorTarget(
  1447. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1448. // Set FOLDER property on the timestamp target, so it appears in the
  1449. // appropriate folder in an IDE or in the file api.
  1450. if (!this->TargetsFolder.empty()) {
  1451. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1452. }
  1453. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1454. // moc and uic executables (whichever are enabled).
  1455. dependencies.clear();
  1456. dependencies.push_back(timestampTargetName);
  1457. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1458. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1459. std::string outputFile;
  1460. std::string depFile;
  1461. // Create the custom command that outputs the timestamp file.
  1462. if (this->MultiConfig && this->UseBetterGraph) {
  1463. // create timestamp file with $<CONFIG> in the name so that
  1464. // every cmake_autogen target has its own timestamp file
  1465. std::string const configView = "$<CONFIG>";
  1466. std::string const timestampFileWithoutConfig = "timestamp_";
  1467. std::string const depFileWithoutConfig =
  1468. cmStrCat(this->Dir.Build, "/deps_");
  1469. std::string const timestampFileName =
  1470. timestampFileWithoutConfig + configView;
  1471. outputFile = cmStrCat(this->Dir.Build, '/', timestampFileName);
  1472. auto const depFileWithConfig =
  1473. cmStrCat(depFileWithoutConfig, configView);
  1474. depFile = depFileWithConfig;
  1475. commandLines.push_back(cmMakeCommandLine(
  1476. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1477. ConfigString outputFileWithConfig;
  1478. for (std::string const& config : this->ConfigsList) {
  1479. auto tempTimestampFileName = timestampFileWithoutConfig + config;
  1480. auto tempDepFile = depFileWithoutConfig + config;
  1481. outputFileWithConfig.Config[config] = tempTimestampFileName;
  1482. this->AutogenTarget.DepFileRuleName.Config[config] =
  1483. cmStrCat(this->Dir.RelativeBuild, '/', tempTimestampFileName);
  1484. this->AutogenTarget.DepFile.Config[config] = tempDepFile;
  1485. }
  1486. this->AddGeneratedSource(outputFileWithConfig, this->Moc);
  1487. } else {
  1488. cm::string_view const timestampFileName = "timestamp";
  1489. outputFile = cmStrCat(this->Dir.Build, '/', timestampFileName);
  1490. this->AutogenTarget.DepFile.Default =
  1491. cmStrCat(this->Dir.Build, "/deps");
  1492. depFile = this->AutogenTarget.DepFile.Default;
  1493. this->AutogenTarget.DepFileRuleName.Default =
  1494. cmStrCat(this->Dir.RelativeBuild, '/', timestampFileName);
  1495. commandLines.push_back(cmMakeCommandLine(
  1496. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1497. this->AddGeneratedSource(outputFile, this->Moc);
  1498. }
  1499. cc = cm::make_unique<cmCustomCommand>();
  1500. cc->SetOutputs(outputFile);
  1501. cc->SetByproducts(timestampByproducts);
  1502. cc->SetDepends(dependencies);
  1503. cc->SetCommandLines(commandLines);
  1504. cc->SetComment(autogenComment.c_str());
  1505. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1506. cc->SetEscapeOldStyle(false);
  1507. cc->SetDepfile(depFile);
  1508. cc->SetStdPipesUTF8(stdPipesUTF8);
  1509. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1510. dependencies.clear();
  1511. dependencies.emplace_back(std::move(outputFile));
  1512. commandLines.clear();
  1513. autogenComment.clear();
  1514. }
  1515. // Create autogen target
  1516. auto cc = cm::make_unique<cmCustomCommand>();
  1517. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1518. cc->SetByproducts(autogenByproducts);
  1519. cc->SetDepends(dependencies);
  1520. cc->SetCommandLines(commandLines);
  1521. cc->SetEscapeOldStyle(false);
  1522. cc->SetComment(autogenComment.c_str());
  1523. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1524. this->AutogenTarget.Name, true, std::move(cc));
  1525. // Create autogen generator target
  1526. this->LocalGen->AddGeneratorTarget(
  1527. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1528. // Order the autogen target(s) just before the original target.
  1529. cmTarget* orderTarget = timestampTarget ? timestampTarget : autogenTarget;
  1530. // Forward origin utilities to autogen target
  1531. if (this->AutogenTarget.DependOrigin) {
  1532. for (BT<std::pair<std::string, bool>> const& depName :
  1533. this->GenTarget->GetUtilities()) {
  1534. orderTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1535. }
  1536. }
  1537. // Add additional autogen target dependencies to autogen target
  1538. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1539. orderTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1540. }
  1541. // Set FOLDER property in autogen target
  1542. if (!this->TargetsFolder.empty()) {
  1543. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1544. }
  1545. // Add autogen target to the origin target dependencies
  1546. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1547. this->Makefile);
  1548. // Add autogen target to the global autogen target dependencies
  1549. if (this->AutogenTarget.GlobalTarget) {
  1550. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1551. this->AutogenTarget.Name);
  1552. }
  1553. }
  1554. return true;
  1555. }
  1556. void cmQtAutoGenInitializer::AddCMakeProcessToCommandLines(
  1557. std::string const& infoFile, std::string const& processName,
  1558. cmCustomCommandLines& commandLines)
  1559. {
  1560. std::vector<std::string> autogenConfigs;
  1561. this->GlobalGen->GetQtAutoGenConfigs(autogenConfigs);
  1562. if (this->CrossConfig && this->UseBetterGraph) {
  1563. commandLines.push_back(cmMakeCommandLine(
  1564. { cmSystemTools::GetCMakeCommand(), "-E", processName, infoFile,
  1565. "$<CONFIG>", "$<COMMAND_CONFIG:$<CONFIG>>" }));
  1566. } else if ((this->MultiConfig && this->GlobalGen->IsXcode()) ||
  1567. this->CrossConfig) {
  1568. auto const& configs =
  1569. processName == "cmake_autorcc" ? this->ConfigsList : autogenConfigs;
  1570. for (std::string const& config : configs) {
  1571. commandLines.push_back(
  1572. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1573. processName, infoFile, config }));
  1574. }
  1575. } else {
  1576. std::string autoInfoFileConfig;
  1577. if (this->MultiConfig) {
  1578. autoInfoFileConfig = "$<CONFIG>";
  1579. } else {
  1580. autoInfoFileConfig = autogenConfigs[0];
  1581. }
  1582. commandLines.push_back(
  1583. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", processName,
  1584. infoFile, autoInfoFileConfig }));
  1585. }
  1586. }
  1587. bool cmQtAutoGenInitializer::InitRccTargets()
  1588. {
  1589. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1590. // Register info file as generated by CMake
  1591. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1592. // Register file at target
  1593. {
  1594. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1595. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1596. }
  1597. std::vector<std::string> ccOutput{ qrc.OutputFile };
  1598. // Add the .qrc and info file to the custom command dependencies
  1599. std::vector<std::string> ccDepends{ qrc.QrcFile, qrc.InfoFile };
  1600. cmCustomCommandLines commandLines;
  1601. AddCMakeProcessToCommandLines(qrc.InfoFile, "cmake_autorcc", commandLines);
  1602. std::string const ccComment =
  1603. cmStrCat("Automatic RCC for ",
  1604. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1605. auto cc = cm::make_unique<cmCustomCommand>();
  1606. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1607. cc->SetCommandLines(commandLines);
  1608. cc->SetComment(ccComment.c_str());
  1609. cc->SetStdPipesUTF8(true);
  1610. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1611. // Create custom rcc target
  1612. std::string ccName;
  1613. {
  1614. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1615. if (!qrc.Unique) {
  1616. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1617. }
  1618. cc->SetByproducts(ccOutput);
  1619. cc->SetDepends(ccDepends);
  1620. cc->SetEscapeOldStyle(false);
  1621. cmTarget* autoRccTarget =
  1622. this->LocalGen->AddUtilityCommand(ccName, true, std::move(cc));
  1623. // Create autogen generator target
  1624. this->LocalGen->AddGeneratorTarget(
  1625. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1626. // Set FOLDER property in autogen target
  1627. if (!this->TargetsFolder.empty()) {
  1628. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1629. }
  1630. if (!this->Rcc.ExecutableTargetName.empty()) {
  1631. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1632. this->Makefile);
  1633. }
  1634. }
  1635. // Add autogen target to the origin target dependencies
  1636. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1637. // Add autogen target to the global autogen target dependencies
  1638. if (this->Rcc.GlobalTarget) {
  1639. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1640. }
  1641. } else {
  1642. // Create custom rcc command
  1643. {
  1644. // Add the resource files to the dependencies
  1645. if (this->MultiConfig && this->UseBetterGraph) {
  1646. for (auto const& config : this->ConfigsList) {
  1647. // Add resource file to the custom command dependencies
  1648. auto resourceFilesWithConfig = cmStrCat(
  1649. "$<$<CONFIG:", config,
  1650. ">:", cmList{ qrc.Resources.Config.at(config) }.to_string(),
  1651. '>');
  1652. ccDepends.emplace_back(std::move(resourceFilesWithConfig));
  1653. }
  1654. } else {
  1655. for (std::string const& fileName : qrc.Resources.Default) {
  1656. // Add resource file to the custom command dependencies
  1657. ccDepends.push_back(fileName);
  1658. }
  1659. }
  1660. if (!this->Rcc.ExecutableTargetName.empty()) {
  1661. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1662. }
  1663. AddAutogenExecutableToDependencies(this->Rcc, ccDepends);
  1664. cc->SetOutputs(ccOutput);
  1665. cc->SetDepends(ccDepends);
  1666. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1667. }
  1668. // Reconfigure when .qrc file changes
  1669. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1670. }
  1671. }
  1672. return true;
  1673. }
  1674. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1675. {
  1676. // Create info directory on demand
  1677. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1678. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1679. Quoted(this->Dir.Info)));
  1680. return false;
  1681. }
  1682. // Generate autogen target info file
  1683. if (this->MocOrUicEnabled()) {
  1684. // Write autogen target info files
  1685. if (!this->SetupWriteAutogenInfo()) {
  1686. return false;
  1687. }
  1688. }
  1689. // Write AUTORCC info files
  1690. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1691. }
  1692. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1693. {
  1694. // Utility lambdas
  1695. auto MfDef = [this](std::string const& key) {
  1696. return this->Makefile->GetSafeDefinition(key);
  1697. };
  1698. // Filtered headers and sources
  1699. std::set<std::string> moc_skip;
  1700. std::set<std::string> uic_skip;
  1701. std::vector<MUFile const*> headers;
  1702. std::vector<MUFile const*> sources;
  1703. // Filter headers
  1704. {
  1705. headers.reserve(this->AutogenTarget.Headers.size());
  1706. for (auto const& pair : this->AutogenTarget.Headers) {
  1707. MUFile const* const muf = pair.second.get();
  1708. if (muf->SkipMoc) {
  1709. moc_skip.insert(muf->FullPath);
  1710. }
  1711. if (muf->SkipUic) {
  1712. uic_skip.insert(muf->FullPath);
  1713. }
  1714. if (muf->Generated && !this->CMP0071Accept) {
  1715. continue;
  1716. }
  1717. if (muf->MocIt || muf->UicIt) {
  1718. headers.emplace_back(muf);
  1719. }
  1720. }
  1721. std::sort(headers.begin(), headers.end(),
  1722. [](MUFile const* a, MUFile const* b) {
  1723. return (a->FullPath < b->FullPath);
  1724. });
  1725. }
  1726. // Filter sources
  1727. {
  1728. sources.reserve(this->AutogenTarget.Sources.size());
  1729. for (auto const& pair : this->AutogenTarget.Sources) {
  1730. MUFile const* const muf = pair.second.get();
  1731. if (muf->Generated && !this->CMP0071Accept) {
  1732. continue;
  1733. }
  1734. if (muf->SkipMoc) {
  1735. moc_skip.insert(muf->FullPath);
  1736. }
  1737. if (muf->SkipUic) {
  1738. uic_skip.insert(muf->FullPath);
  1739. }
  1740. if (muf->MocIt || muf->UicIt) {
  1741. sources.emplace_back(muf);
  1742. }
  1743. }
  1744. std::sort(sources.begin(), sources.end(),
  1745. [](MUFile const* a, MUFile const* b) {
  1746. return (a->FullPath < b->FullPath);
  1747. });
  1748. }
  1749. // Info writer
  1750. InfoWriter info;
  1751. // General
  1752. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1753. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1754. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1755. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1756. #ifdef _WIN32
  1757. info.SetUInt("AUTOGEN_COMMAND_LINE_LENGTH_MAX",
  1758. this->AutogenTarget.MaxCommandLineLength);
  1759. #endif
  1760. info.SetUInt("VERBOSITY", this->Verbosity);
  1761. // Directories
  1762. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1763. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1764. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1765. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1766. info.Set("BUILD_DIR", this->Dir.Build);
  1767. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1768. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1769. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1770. info.SetConfig("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1771. info.SetConfig("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1772. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1773. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1774. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1775. info.SetConfig("DEP_FILE", this->AutogenTarget.DepFile);
  1776. info.SetConfig("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1777. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1778. info.SetArray("HEADER_EXTENSIONS",
  1779. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1780. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1781. Json::Value value;
  1782. if (!configs.empty()) {
  1783. value = Json::arrayValue;
  1784. for (size_t ci : configs) {
  1785. value.append(this->ConfigsList[ci]);
  1786. }
  1787. }
  1788. return value;
  1789. };
  1790. info.SetArrayArray("HEADERS", headers,
  1791. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1792. jval.resize(4u);
  1793. jval[0u] = muf->FullPath;
  1794. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1795. muf->UicIt ? 'U' : 'u');
  1796. jval[2u] = this->GetMocBuildPath(*muf);
  1797. jval[3u] = cfgArray(muf->Configs);
  1798. });
  1799. info.SetArrayArray(
  1800. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1801. jval.resize(3u);
  1802. jval[0u] = muf->FullPath;
  1803. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1804. jval[2u] = cfgArray(muf->Configs);
  1805. });
  1806. // Write moc settings
  1807. if (this->Moc.Enabled) {
  1808. info.SetArray("MOC_SKIP", moc_skip);
  1809. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1810. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1811. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1812. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1813. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1814. EvaluatedTargetPropertyEntries InterfaceAutoMocMacroNamesEntries;
  1815. if (this->MultiConfig) {
  1816. for (auto const& cfg : this->ConfigsList) {
  1817. if (!cfg.empty()) {
  1818. cmGeneratorExpressionDAGChecker dagChecker{
  1819. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr,
  1820. nullptr, this->LocalGen, cfg,
  1821. };
  1822. AddInterfaceEntries(this->GenTarget, cfg,
  1823. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX",
  1824. &dagChecker, InterfaceAutoMocMacroNamesEntries,
  1825. IncludeRuntimeInterface::Yes);
  1826. }
  1827. }
  1828. } else {
  1829. cmGeneratorExpressionDAGChecker dagChecker{
  1830. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr,
  1831. nullptr, this->LocalGen, this->ConfigDefault,
  1832. };
  1833. AddInterfaceEntries(this->GenTarget, this->ConfigDefault,
  1834. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX", &dagChecker,
  1835. InterfaceAutoMocMacroNamesEntries,
  1836. IncludeRuntimeInterface::Yes);
  1837. }
  1838. for (auto const& entry : InterfaceAutoMocMacroNamesEntries.Entries) {
  1839. this->Moc.MacroNames.insert(this->Moc.MacroNames.end(),
  1840. entry.Values.begin(), entry.Values.end());
  1841. }
  1842. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  1843. this->Moc.MacroNames.end());
  1844. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1845. info.SetArrayArray(
  1846. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1847. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1848. jval.resize(2u);
  1849. jval[0u] = pair.first;
  1850. jval[1u] = pair.second;
  1851. });
  1852. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1853. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1854. cmStandardLevelResolver const resolver{ this->Makefile };
  1855. auto const CompileOptionFlag =
  1856. resolver.GetCompileOptionDef(this->GenTarget, "CXX", "");
  1857. auto const CompileOptionValue =
  1858. this->GenTarget->Makefile->GetSafeDefinition(CompileOptionFlag);
  1859. if (!CompileOptionValue.empty()) {
  1860. if (this->Moc.PredefsCmd.size() >= 3) {
  1861. this->Moc.PredefsCmd.insert(this->Moc.PredefsCmd.begin() + 1,
  1862. CompileOptionValue);
  1863. }
  1864. }
  1865. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1866. }
  1867. // Write uic settings
  1868. if (this->Uic.Enabled) {
  1869. // Add skipped .ui files
  1870. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1871. info.SetArray("UIC_SKIP", uic_skip);
  1872. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1873. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1874. jval.resize(2u);
  1875. jval[0u] = uiFile.first;
  1876. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1877. });
  1878. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1879. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1880. }
  1881. info.Save(this->AutogenTarget.InfoFile);
  1882. return true;
  1883. }
  1884. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1885. {
  1886. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1887. // Utility lambdas
  1888. auto MfDef = [this](std::string const& key) {
  1889. return this->Makefile->GetSafeDefinition(key);
  1890. };
  1891. InfoWriter info;
  1892. // General
  1893. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1894. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1895. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1896. info.SetUInt("VERBOSITY", this->Verbosity);
  1897. info.Set("GENERATOR", this->GlobalGen->GetName());
  1898. // Files
  1899. info.Set("LOCK_FILE", qrc.LockFile);
  1900. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1901. // Directories
  1902. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1903. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1904. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1905. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1906. info.Set("BUILD_DIR", this->Dir.Build);
  1907. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1908. // rcc executable
  1909. info.SetConfig("RCC_EXECUTABLE", this->Rcc.Executable);
  1910. info.SetConfigArray(
  1911. "RCC_LIST_OPTIONS",
  1912. generateListOptions(this->Rcc.ExecutableFeatures, this->MultiConfig));
  1913. // qrc file
  1914. info.Set("SOURCE", qrc.QrcFile);
  1915. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1916. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1917. info.SetArray("OPTIONS", qrc.Options);
  1918. info.SetConfigArray("INPUTS", qrc.Resources);
  1919. info.Save(qrc.InfoFile);
  1920. }
  1921. return true;
  1922. }
  1923. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1924. std::string const& filename)
  1925. {
  1926. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1927. gFile->SetSpecialSourceType(
  1928. cmSourceFile::SpecialSourceType::QtAutogenSource);
  1929. gFile->MarkAsGenerated();
  1930. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1931. gFile->SetProperty("SKIP_LINTING", "ON");
  1932. gFile->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1933. return gFile;
  1934. }
  1935. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1936. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1937. {
  1938. // Register source at makefile
  1939. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1940. // Add source file to target
  1941. this->GenTarget->AddSource(filename, prepend);
  1942. // Add source file to source group
  1943. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1944. return gFile;
  1945. }
  1946. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1947. GenVarsT const& genVars,
  1948. bool prepend)
  1949. {
  1950. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1951. // when the Xcode generator supports per-config sources.
  1952. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1953. cmSourceFile* sf =
  1954. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1955. handleSkipPch(sf);
  1956. return;
  1957. }
  1958. for (auto const& cfg : this->ConfigsList) {
  1959. std::string const& filenameCfg = filename.Config.at(cfg);
  1960. // Register source at makefile
  1961. cmSourceFile* sf = this->RegisterGeneratedSource(filenameCfg);
  1962. handleSkipPch(sf);
  1963. // Add source file to target for this configuration.
  1964. this->GenTarget->AddSource(
  1965. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1966. // Add source file to source group
  1967. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1968. }
  1969. }
  1970. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1971. cm::string_view genNameUpper)
  1972. {
  1973. cmSourceGroup* sourceGroup = nullptr;
  1974. // Acquire source group
  1975. {
  1976. std::string property;
  1977. std::string groupName;
  1978. {
  1979. // Prefer generator specific source group name
  1980. std::initializer_list<std::string> const props{
  1981. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1982. };
  1983. for (std::string const& prop : props) {
  1984. cmValue propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1985. if (cmNonempty(propName)) {
  1986. groupName = *propName;
  1987. property = prop;
  1988. break;
  1989. }
  1990. }
  1991. }
  1992. // Generate a source group on demand
  1993. if (!groupName.empty()) {
  1994. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1995. if (!sourceGroup) {
  1996. cmSystemTools::Error(
  1997. cmStrCat(genNameUpper, " error in ", property,
  1998. ": Could not find or create the source group ",
  1999. cmQtAutoGen::Quoted(groupName)));
  2000. }
  2001. }
  2002. }
  2003. if (sourceGroup) {
  2004. sourceGroup->AddGroupFile(fileName);
  2005. }
  2006. }
  2007. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  2008. {
  2009. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName);
  2010. }
  2011. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  2012. cm::string_view prefix,
  2013. cm::string_view suffix)
  2014. {
  2015. configString.Default = cmStrCat(prefix, suffix);
  2016. if (this->MultiConfig) {
  2017. for (auto const& cfg : this->ConfigsList) {
  2018. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  2019. }
  2020. }
  2021. }
  2022. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  2023. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  2024. cm::string_view const suffix)
  2025. {
  2026. this->ConfigFileNames(configString, prefix, suffix);
  2027. if (this->MultiConfig) {
  2028. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  2029. } else {
  2030. genex = configString.Default;
  2031. }
  2032. }
  2033. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  2034. {
  2035. this->AddCleanFile(configString.Default);
  2036. if (this->MultiConfig) {
  2037. for (auto const& pair : configString.Config) {
  2038. this->AddCleanFile(pair.second);
  2039. }
  2040. }
  2041. }
  2042. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  2043. {
  2044. cmQtAutoGen::IntegerVersion result;
  2045. static std::string const prelude = "moc ";
  2046. size_t const pos = str.find(prelude);
  2047. if (pos == std::string::npos) {
  2048. return result;
  2049. }
  2050. str.erase(0, prelude.size() + pos);
  2051. std::istringstream iss(str);
  2052. std::string major;
  2053. std::string minor;
  2054. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  2055. return result;
  2056. }
  2057. result.Major = static_cast<unsigned int>(std::stoi(major));
  2058. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  2059. return result;
  2060. }
  2061. static cmQtAutoGen::IntegerVersion GetMocVersion(
  2062. std::string const& mocExecutablePath)
  2063. {
  2064. std::string capturedStdOut;
  2065. int exitCode;
  2066. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  2067. &capturedStdOut, nullptr, &exitCode,
  2068. nullptr, cmSystemTools::OUTPUT_NONE)) {
  2069. return {};
  2070. }
  2071. if (exitCode != 0) {
  2072. return {};
  2073. }
  2074. return parseMocVersion(capturedStdOut);
  2075. }
  2076. static std::string FindMocExecutableFromMocTarget(cmMakefile const* makefile,
  2077. unsigned int qtMajorVersion)
  2078. {
  2079. std::string result;
  2080. std::string const mocTargetName = cmStrCat("Qt", qtMajorVersion, "::moc");
  2081. cmTarget const* mocTarget = makefile->FindTargetToUse(mocTargetName);
  2082. if (mocTarget) {
  2083. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  2084. }
  2085. return result;
  2086. }
  2087. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  2088. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  2089. std::string mocExecutable)
  2090. {
  2091. // Converts a char ptr to an unsigned int value
  2092. auto toUInt = [](char const* const input) -> unsigned int {
  2093. unsigned long tmp = 0;
  2094. if (input && cmStrToULong(input, &tmp)) {
  2095. return static_cast<unsigned int>(tmp);
  2096. }
  2097. return 0u;
  2098. };
  2099. auto toUInt2 = [](cmValue input) -> unsigned int {
  2100. unsigned long tmp = 0;
  2101. if (input && cmStrToULong(*input, &tmp)) {
  2102. return static_cast<unsigned int>(tmp);
  2103. }
  2104. return 0u;
  2105. };
  2106. // Initialize return value to a default
  2107. std::pair<IntegerVersion, unsigned int> res(
  2108. IntegerVersion(),
  2109. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  2110. "")));
  2111. // Acquire known Qt versions
  2112. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  2113. {
  2114. // Qt version variable prefixes
  2115. static std::initializer_list<
  2116. std::pair<cm::string_view, cm::string_view>> const keys{
  2117. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  2118. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  2119. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  2120. };
  2121. knownQtVersions.reserve(keys.size() * 2);
  2122. // Adds a version to the result (nullptr safe)
  2123. auto addVersion = [&knownQtVersions, &toUInt2](cmValue major,
  2124. cmValue minor) {
  2125. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  2126. if (ver.Major != 0) {
  2127. knownQtVersions.emplace_back(ver);
  2128. }
  2129. };
  2130. // Read versions from variables
  2131. for (auto const& keyPair : keys) {
  2132. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  2133. target->Makefile->GetDefinition(std::string(keyPair.second)));
  2134. }
  2135. // Read versions from directory properties
  2136. for (auto const& keyPair : keys) {
  2137. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  2138. target->Makefile->GetProperty(std::string(keyPair.second)));
  2139. }
  2140. }
  2141. // Evaluate known Qt versions
  2142. if (!knownQtVersions.empty()) {
  2143. if (res.second == 0) {
  2144. // No specific version was requested by the target:
  2145. // Use highest known Qt version.
  2146. res.first = knownQtVersions.at(0);
  2147. } else {
  2148. // Pick a version from the known versions:
  2149. for (auto const& it : knownQtVersions) {
  2150. if (it.Major == res.second) {
  2151. res.first = it;
  2152. break;
  2153. }
  2154. }
  2155. }
  2156. }
  2157. if (res.first.Major == 0) {
  2158. // We could not get the version number from variables or directory
  2159. // properties. This might happen if the find_package call for Qt is wrapped
  2160. // in a function. Try to find the moc executable path from the available
  2161. // targets and call "moc --version" to get the Qt version.
  2162. if (mocExecutable.empty()) {
  2163. mocExecutable =
  2164. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  2165. }
  2166. if (!mocExecutable.empty()) {
  2167. res.first = GetMocVersion(mocExecutable);
  2168. }
  2169. }
  2170. return res;
  2171. }
  2172. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  2173. {
  2174. std::string res;
  2175. if (!muf.MocIt) {
  2176. return res;
  2177. }
  2178. std::string basePath =
  2179. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  2180. FileNameWithoutLastExtension(muf.FullPath));
  2181. res = cmStrCat(basePath, ".cpp");
  2182. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2183. return res;
  2184. }
  2185. // File name already emitted.
  2186. // Try appending the header suffix to the base path.
  2187. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  2188. res = cmStrCat(basePath, ".cpp");
  2189. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2190. return res;
  2191. }
  2192. // File name with header extension already emitted.
  2193. // Try adding a number to the base path.
  2194. constexpr std::size_t number_begin = 2;
  2195. constexpr std::size_t number_end = 256;
  2196. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  2197. res = cmStrCat(basePath, '_', ii, ".cpp");
  2198. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2199. return res;
  2200. }
  2201. }
  2202. // Output file name conflict (unlikely, but still...)
  2203. cmSystemTools::Error(
  2204. cmStrCat("moc output file name conflict for ", muf.FullPath));
  2205. return res;
  2206. }
  2207. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  2208. std::string const& executable,
  2209. bool ignoreMissingTarget) const
  2210. {
  2211. auto print_err = [this, &genVars](std::string const& err) {
  2212. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  2213. this->GenTarget->GetName(), ": ", err));
  2214. };
  2215. // Custom executable
  2216. {
  2217. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  2218. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  2219. if (!val.empty()) {
  2220. // Evaluate generator expression
  2221. {
  2222. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2223. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  2224. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  2225. if (this->MultiConfig && this->UseBetterGraph) {
  2226. for (auto const& config : this->ConfigsList) {
  2227. genVars.Executable.Config[config] =
  2228. cge->Evaluate(this->LocalGen, config);
  2229. }
  2230. } else {
  2231. genVars.Executable.Default = cge->Evaluate(this->LocalGen, "");
  2232. }
  2233. }
  2234. if (genVars.Executable.Default.empty() &&
  2235. genVars.Executable.Config.empty() && !ignoreMissingTarget) {
  2236. print_err(prop + " evaluates to an empty value");
  2237. return false;
  2238. }
  2239. // Create empty compiler features.
  2240. if (this->MultiConfig && this->UseBetterGraph) {
  2241. for (auto const& config : this->ConfigsList) {
  2242. genVars.ExecutableFeatures.Config[config] =
  2243. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2244. }
  2245. } else {
  2246. genVars.ExecutableFeatures.Default =
  2247. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2248. }
  2249. return true;
  2250. }
  2251. }
  2252. // Find executable target
  2253. {
  2254. // Find executable target name
  2255. cm::string_view prefix;
  2256. if (this->QtVersion.Major == 4) {
  2257. prefix = "Qt4::";
  2258. } else if (this->QtVersion.Major == 5) {
  2259. prefix = "Qt5::";
  2260. } else if (this->QtVersion.Major == 6) {
  2261. prefix = "Qt6::";
  2262. }
  2263. std::string const targetName = cmStrCat(prefix, executable);
  2264. // Find target
  2265. cmGeneratorTarget* genTarget =
  2266. this->LocalGen->FindGeneratorTargetToUse(targetName);
  2267. if (genTarget) {
  2268. genVars.ExecutableTargetName = targetName;
  2269. genVars.ExecutableTarget = genTarget;
  2270. if (genTarget->IsImported()) {
  2271. if (this->MultiConfig && this->UseBetterGraph) {
  2272. for (auto const& config : this->ConfigsList) {
  2273. genVars.Executable.Config[config] =
  2274. genTarget->ImportedGetLocation(config);
  2275. }
  2276. } else {
  2277. genVars.Executable.Default =
  2278. genTarget->ImportedGetLocation(this->ConfigDefault);
  2279. }
  2280. } else {
  2281. if (this->MultiConfig && this->UseBetterGraph) {
  2282. for (auto const& config : this->ConfigsList) {
  2283. genVars.Executable.Config[config] = genTarget->GetLocation(config);
  2284. }
  2285. } else {
  2286. genVars.Executable.Default =
  2287. genTarget->GetLocation(this->ConfigDefault);
  2288. }
  2289. }
  2290. } else {
  2291. if (ignoreMissingTarget) {
  2292. // Create empty compiler features.
  2293. if (this->MultiConfig && this->UseBetterGraph) {
  2294. for (auto const& config : this->ConfigsList) {
  2295. genVars.ExecutableFeatures.Config[config] =
  2296. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2297. }
  2298. } else {
  2299. genVars.ExecutableFeatures.Default =
  2300. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2301. }
  2302. return true;
  2303. }
  2304. print_err(cmStrCat("Could not find ", executable, " executable target ",
  2305. targetName));
  2306. return false;
  2307. }
  2308. }
  2309. // Get executable features
  2310. {
  2311. std::string err;
  2312. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  2313. executable, genVars.Executable, err, this->MultiConfig,
  2314. this->UseBetterGraph);
  2315. if (this->MultiConfig && this->UseBetterGraph) {
  2316. for (auto const& config : this->ConfigsList) {
  2317. if (!genVars.ExecutableFeatures.Config[config]) {
  2318. if (!genVars.ExecutableFeatures.Config[config]) {
  2319. print_err(err);
  2320. return false;
  2321. }
  2322. }
  2323. }
  2324. } else {
  2325. if (!genVars.ExecutableFeatures.Default) {
  2326. print_err(err);
  2327. return false;
  2328. }
  2329. }
  2330. }
  2331. return true;
  2332. }
  2333. void cmQtAutoGenInitializer::handleSkipPch(cmSourceFile* sf)
  2334. {
  2335. bool skipPch = true;
  2336. for (auto const& pair : this->AutogenTarget.Sources) {
  2337. if (!pair.first->GetIsGenerated() &&
  2338. !pair.first->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2339. skipPch = false;
  2340. }
  2341. }
  2342. if (skipPch) {
  2343. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2344. }
  2345. }