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