cmQtAutoGenInitializer.cxx 88 KB

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