cmQtAutoGenInitializer.cxx 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  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. SearchPathSanitizer const sanitizer(this->Makefile);
  660. auto getDirs =
  661. [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
  662. // Get the include dirs for this target, without stripping the implicit
  663. // include dirs off, see issue #13667.
  664. std::vector<std::string> dirs;
  665. bool const appendImplicit = (this->QtVersion.Major >= 5);
  666. this->LocalGen->GetIncludeDirectoriesImplicit(
  667. dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
  668. return sanitizer(dirs);
  669. };
  670. // Other configuration settings
  671. if (this->MultiConfig) {
  672. for (std::string const& cfg : this->ConfigsList) {
  673. std::vector<std::string> dirs = getDirs(cfg);
  674. if (dirs == this->Moc.Includes.Default) {
  675. continue;
  676. }
  677. this->Moc.Includes.Config[cfg] = std::move(dirs);
  678. }
  679. } else {
  680. // Default configuration include directories
  681. this->Moc.Includes.Default = getDirs(this->ConfigDefault);
  682. }
  683. }
  684. // Moc compile definitions
  685. {
  686. auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
  687. std::set<std::string> defines;
  688. this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
  689. if (this->Moc.PredefsCmd.empty() &&
  690. this->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME") ==
  691. "Windows") {
  692. // Add WIN32 definition if we don't have a moc_predefs.h
  693. defines.insert("WIN32");
  694. }
  695. return defines;
  696. };
  697. // Other configuration defines
  698. if (this->MultiConfig) {
  699. for (std::string const& cfg : this->ConfigsList) {
  700. std::set<std::string> defines = getDefs(cfg);
  701. if (defines == this->Moc.Defines.Default) {
  702. continue;
  703. }
  704. this->Moc.Defines.Config[cfg] = std::move(defines);
  705. }
  706. } else {
  707. // Default configuration defines
  708. this->Moc.Defines.Default = getDefs(this->ConfigDefault);
  709. }
  710. }
  711. // Moc executable
  712. {
  713. if (!this->GetQtExecutable(this->Moc, "moc", false)) {
  714. return false;
  715. }
  716. // Let the _autogen target depend on the moc executable
  717. if (this->Moc.ExecutableTarget) {
  718. this->AutogenTarget.DependTargets.insert(
  719. this->Moc.ExecutableTarget->Target);
  720. }
  721. }
  722. return true;
  723. }
  724. bool cmQtAutoGenInitializer::InitUic()
  725. {
  726. // Uic search paths
  727. {
  728. std::string const& usp =
  729. this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
  730. if (!usp.empty()) {
  731. this->Uic.SearchPaths =
  732. SearchPathSanitizer(this->Makefile)(cmList{ usp });
  733. }
  734. }
  735. // Uic target options
  736. {
  737. auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
  738. std::vector<std::string> opts;
  739. this->GenTarget->GetAutoUicOptions(opts, cfg);
  740. return opts;
  741. };
  742. // Default options
  743. this->Uic.Options.Default = getOpts(this->ConfigDefault);
  744. // Configuration specific options
  745. if (this->MultiConfig) {
  746. for (std::string const& cfg : this->ConfigsList) {
  747. std::vector<std::string> options = getOpts(cfg);
  748. if (options == this->Uic.Options.Default) {
  749. continue;
  750. }
  751. this->Uic.Options.Config[cfg] = std::move(options);
  752. }
  753. }
  754. }
  755. // Uic executable
  756. {
  757. if (!this->GetQtExecutable(this->Uic, "uic", true)) {
  758. return false;
  759. }
  760. // Let the _autogen target depend on the uic executable
  761. if (this->Uic.ExecutableTarget) {
  762. this->AutogenTarget.DependTargets.insert(
  763. this->Uic.ExecutableTarget->Target);
  764. }
  765. }
  766. return true;
  767. }
  768. bool cmQtAutoGenInitializer::InitRcc()
  769. {
  770. // Rcc executable
  771. {
  772. if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
  773. return false;
  774. }
  775. // Evaluate test output on demand
  776. auto& features = this->Rcc.ExecutableFeatures;
  777. auto checkAndAddOptions = [this](CompilerFeaturesHandle& feature) {
  778. if (!feature->Evaluated) {
  779. // Look for list options
  780. if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
  781. static std::array<std::string, 2> const listOptions{ { "--list",
  782. "-list" } };
  783. for (std::string const& opt : listOptions) {
  784. if (feature->HelpOutput.find(opt) != std::string::npos) {
  785. feature->ListOptions.emplace_back(opt);
  786. break;
  787. }
  788. }
  789. }
  790. // Evaluation finished
  791. feature->Evaluated = true;
  792. }
  793. };
  794. if (this->MultiConfig && this->UseBetterGraph) {
  795. for (auto const& config : this->ConfigsList) {
  796. checkAndAddOptions(features.Config[config]);
  797. }
  798. } else {
  799. checkAndAddOptions(features.Default);
  800. }
  801. }
  802. // Disable zstd if it is not supported
  803. {
  804. std::string const qtFeatureZSTD = "QT_FEATURE_zstd";
  805. if (this->GenTarget->Target->GetMakefile()->IsDefinitionSet(
  806. qtFeatureZSTD)) {
  807. auto const zstdDef =
  808. this->GenTarget->Target->GetMakefile()->GetSafeDefinition(
  809. qtFeatureZSTD);
  810. auto const zstdVal = cmValue(zstdDef);
  811. if (zstdVal.IsOff()) {
  812. auto const& kw = this->GlobalInitializer->kw();
  813. auto rccOptions = this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS);
  814. std::string const nozstd = "--no-zstd";
  815. if (rccOptions.find(nozstd) == std::string::npos) {
  816. rccOptions.append(";" + nozstd + ";");
  817. }
  818. this->GenTarget->Target->SetProperty(kw.AUTORCC_OPTIONS, rccOptions);
  819. }
  820. }
  821. }
  822. return true;
  823. }
  824. bool cmQtAutoGenInitializer::InitScanFiles()
  825. {
  826. cmake const* cm = this->Makefile->GetCMakeInstance();
  827. auto const& kw = this->GlobalInitializer->kw();
  828. auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
  829. std::vector<size_t> const& configs,
  830. bool muIt) -> MUFileHandle {
  831. MUFileHandle muf = cm::make_unique<MUFile>();
  832. muf->FullPath = fullPath;
  833. muf->SF = sf;
  834. if (!configs.empty() && configs.size() != this->ConfigsList.size()) {
  835. muf->Configs = configs;
  836. }
  837. muf->Generated = sf->GetIsGenerated();
  838. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  839. muf->SkipMoc = this->Moc.Enabled &&
  840. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
  841. muf->SkipUic = this->Uic.Enabled &&
  842. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  843. if (muIt) {
  844. muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
  845. muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
  846. }
  847. return muf;
  848. };
  849. auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
  850. cmSourceFile* sf = muf->SF;
  851. bool const muIt = (muf->MocIt || muf->UicIt);
  852. if (this->CMP0100Accept || (extension != "hh")) {
  853. // Accept
  854. if (muIt && muf->Generated) {
  855. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  856. }
  857. this->AutogenTarget.Headers.emplace(sf, std::move(muf));
  858. } else if (muIt && this->CMP0100Warn) {
  859. // Store file for warning message
  860. this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
  861. }
  862. };
  863. auto addMUSource = [this](MUFileHandle&& muf) {
  864. if ((muf->MocIt || muf->UicIt) && muf->Generated) {
  865. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  866. }
  867. this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
  868. };
  869. // Scan through target files
  870. {
  871. // Scan through target files
  872. for (cmGeneratorTarget::AllConfigSource const& acs :
  873. this->GenTarget->GetAllConfigSources()) {
  874. std::string const& fullPath = acs.Source->GetFullPath();
  875. std::string const& extLower =
  876. cmSystemTools::LowerCase(acs.Source->GetExtension());
  877. // Register files that will be scanned by moc or uic
  878. if (this->MocOrUicEnabled()) {
  879. if (cm->IsAHeaderExtension(extLower)) {
  880. addMUHeader(makeMUFile(acs.Source, fullPath, acs.Configs, true),
  881. extLower);
  882. } else if (cm->IsACLikeSourceExtension(extLower)) {
  883. addMUSource(makeMUFile(acs.Source, fullPath, acs.Configs, true));
  884. }
  885. }
  886. // Register rcc enabled files
  887. if (this->Rcc.Enabled) {
  888. if ((extLower == kw.qrc) &&
  889. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
  890. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
  891. // Register qrc file
  892. Qrc qrc;
  893. qrc.QrcFile = fullPath;
  894. qrc.QrcName =
  895. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  896. qrc.Generated = acs.Source->GetIsGenerated();
  897. // RCC options
  898. {
  899. std::string const& opts =
  900. acs.Source->GetSafeProperty(kw.AUTORCC_OPTIONS);
  901. if (!opts.empty()) {
  902. cmExpandList(opts, qrc.Options);
  903. }
  904. }
  905. this->Rcc.Qrcs.push_back(std::move(qrc));
  906. }
  907. }
  908. }
  909. }
  910. // cmGeneratorTarget::GetAllConfigSources computes the target's
  911. // sources meta data cache. Clear it so that OBJECT library targets that
  912. // are AUTOGEN initialized after this target get their added
  913. // mocs_compilation.cpp source acknowledged by this target.
  914. this->GenTarget->ClearSourcesCache();
  915. // For source files find additional headers and private headers
  916. if (this->MocOrUicEnabled()) {
  917. // Header search suffixes and extensions
  918. static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
  919. auto const& exts = cm->GetHeaderExtensions();
  920. // Scan through sources
  921. for (auto const& pair : this->AutogenTarget.Sources) {
  922. MUFile const& muf = *pair.second;
  923. if (muf.MocIt || muf.UicIt) {
  924. // Search for the default header file and a private header
  925. std::string const& srcFullPath = muf.SF->ResolveFullPath();
  926. std::string const basePath = cmStrCat(
  927. cmQtAutoGen::SubDirPrefix(srcFullPath),
  928. cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
  929. for (auto const& suffix : suffixes) {
  930. std::string const suffixedPath = cmStrCat(basePath, suffix);
  931. for (auto const& ext : exts) {
  932. std::string const fullPath = cmStrCat(suffixedPath, '.', ext);
  933. auto constexpr locationKind = cmSourceFileLocationKind::Known;
  934. cmSourceFile* sf =
  935. this->Makefile->GetSource(fullPath, locationKind);
  936. if (sf) {
  937. // Check if we know about this header already
  938. if (cm::contains(this->AutogenTarget.Headers, sf)) {
  939. continue;
  940. }
  941. // We only accept not-GENERATED files that do exist.
  942. if (!sf->GetIsGenerated() &&
  943. !cmSystemTools::FileExists(fullPath)) {
  944. continue;
  945. }
  946. } else if (cmSystemTools::FileExists(fullPath)) {
  947. // Create a new source file for the existing file
  948. sf = this->Makefile->CreateSource(fullPath, false, locationKind);
  949. }
  950. if (sf) {
  951. auto eMuf = makeMUFile(sf, fullPath, muf.Configs, true);
  952. // Only process moc/uic when the parent is processed as well
  953. if (!muf.MocIt) {
  954. eMuf->MocIt = false;
  955. }
  956. if (!muf.UicIt) {
  957. eMuf->UicIt = false;
  958. }
  959. addMUHeader(std::move(eMuf), ext);
  960. }
  961. }
  962. }
  963. }
  964. }
  965. }
  966. // Scan through all source files in the makefile to extract moc and uic
  967. // parameters. Historically we support non target source file parameters.
  968. // The reason is that their file names might be discovered from source files
  969. // at generation time.
  970. if (this->MocOrUicEnabled()) {
  971. for (auto const& sf : this->Makefile->GetSourceFiles()) {
  972. // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
  973. // Since we're iterating over source files that might be not in the
  974. // target we need to check for path errors (not existing files).
  975. std::string pathError;
  976. std::string const& fullPath = sf->ResolveFullPath(&pathError);
  977. if (!pathError.empty() || fullPath.empty()) {
  978. continue;
  979. }
  980. std::string const& extLower =
  981. cmSystemTools::LowerCase(sf->GetExtension());
  982. if (cm->IsAHeaderExtension(extLower)) {
  983. if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
  984. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  985. if (muf->SkipMoc || muf->SkipUic) {
  986. addMUHeader(std::move(muf), extLower);
  987. }
  988. }
  989. } else if (cm->IsACLikeSourceExtension(extLower)) {
  990. if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
  991. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  992. if (muf->SkipMoc || muf->SkipUic) {
  993. addMUSource(std::move(muf));
  994. }
  995. }
  996. } else if (this->Uic.Enabled && (extLower == kw.ui)) {
  997. // .ui file
  998. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  999. bool const skipUic =
  1000. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  1001. if (!skipUic) {
  1002. // Check if the .ui file has uic options
  1003. std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
  1004. if (uicOpts.empty()) {
  1005. this->Uic.UiFilesNoOptions.emplace_back(fullPath);
  1006. } else {
  1007. this->Uic.UiFilesWithOptions.emplace_back(
  1008. fullPath, std::move(cmList{ uicOpts }.data()));
  1009. }
  1010. auto uiHeaderRelativePath = cmSystemTools::RelativePath(
  1011. this->LocalGen->GetCurrentSourceDirectory(),
  1012. cmSystemTools::GetFilenamePath(fullPath));
  1013. // Avoid creating a path containing adjacent slashes
  1014. if (!uiHeaderRelativePath.empty() &&
  1015. uiHeaderRelativePath.back() != '/') {
  1016. uiHeaderRelativePath += '/';
  1017. }
  1018. auto uiHeaderFilePath = cmStrCat(
  1019. '/', uiHeaderRelativePath, "ui_"_s,
  1020. cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
  1021. ConfigString uiHeader;
  1022. std::string uiHeaderGenex;
  1023. this->ConfigFileNamesAndGenex(
  1024. uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
  1025. uiHeaderFilePath);
  1026. this->Uic.UiHeaders.emplace_back(uiHeader, uiHeaderGenex);
  1027. } else {
  1028. // Register skipped .ui file
  1029. this->Uic.SkipUi.insert(fullPath);
  1030. }
  1031. }
  1032. }
  1033. }
  1034. // Process GENERATED sources and headers
  1035. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  1036. if (this->CMP0071Accept) {
  1037. // Let the autogen target depend on the GENERATED files
  1038. if (this->MultiConfig && !this->CrossConfig) {
  1039. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1040. if (muf->Configs.empty()) {
  1041. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  1042. } else {
  1043. for (size_t ci : muf->Configs) {
  1044. std::string const& config = this->ConfigsList[ci];
  1045. std::string const& pathWithConfig =
  1046. cmStrCat("$<$<CONFIG:", config, ">:", muf->FullPath, '>');
  1047. this->AutogenTarget.DependFiles.insert(pathWithConfig);
  1048. }
  1049. }
  1050. }
  1051. } else {
  1052. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1053. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  1054. }
  1055. }
  1056. } else if (this->CMP0071Warn) {
  1057. cm::string_view property;
  1058. if (this->Moc.Enabled && this->Uic.Enabled) {
  1059. property = "SKIP_AUTOGEN";
  1060. } else if (this->Moc.Enabled) {
  1061. property = "SKIP_AUTOMOC";
  1062. } else if (this->Uic.Enabled) {
  1063. property = "SKIP_AUTOUIC";
  1064. }
  1065. std::string files;
  1066. for (MUFile const* muf : this->AutogenTarget.FilesGenerated) {
  1067. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  1068. }
  1069. this->Makefile->IssueMessage(
  1070. MessageType::AUTHOR_WARNING,
  1071. cmStrCat(
  1072. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071),
  1073. "\n"
  1074. "For compatibility, CMake is excluding the GENERATED source "
  1075. "file(s):\n",
  1076. files, "from processing by ",
  1077. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1078. ". If any of the files should be processed, set CMP0071 to NEW. "
  1079. "If any of the files should not be processed, "
  1080. "explicitly exclude them by setting the source file property ",
  1081. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  1082. " ON)\n"));
  1083. }
  1084. }
  1085. // Generate CMP0100 warning
  1086. if (this->MocOrUicEnabled() &&
  1087. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  1088. cm::string_view property;
  1089. if (this->Moc.Enabled && this->Uic.Enabled) {
  1090. property = "SKIP_AUTOGEN";
  1091. } else if (this->Moc.Enabled) {
  1092. property = "SKIP_AUTOMOC";
  1093. } else if (this->Uic.Enabled) {
  1094. property = "SKIP_AUTOUIC";
  1095. }
  1096. std::string files;
  1097. for (cmSourceFile const* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  1098. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  1099. }
  1100. this->Makefile->IssueMessage(
  1101. MessageType::AUTHOR_WARNING,
  1102. cmStrCat(
  1103. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100),
  1104. "\n"
  1105. "For compatibility, CMake is excluding the header file(s):\n",
  1106. files, "from processing by ",
  1107. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1108. ". If any of the files should be processed, set CMP0100 to NEW. "
  1109. "If any of the files should not be processed, "
  1110. "explicitly exclude them by setting the source file property ",
  1111. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  1112. " ON)\n"));
  1113. }
  1114. // Process qrc files
  1115. if (!this->Rcc.Qrcs.empty()) {
  1116. bool const modernQt = (this->QtVersion.Major >= 5);
  1117. // Target rcc options
  1118. cmList const optionsTarget{ this->GenTarget->GetSafeProperty(
  1119. kw.AUTORCC_OPTIONS) };
  1120. // Check if file name is unique
  1121. for (Qrc& qrc : this->Rcc.Qrcs) {
  1122. qrc.Unique = true;
  1123. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  1124. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  1125. qrc.Unique = false;
  1126. break;
  1127. }
  1128. }
  1129. }
  1130. // Path checksum and file names
  1131. for (Qrc& qrc : this->Rcc.Qrcs) {
  1132. // Path checksum
  1133. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  1134. // Output file name
  1135. if (this->MultiConfig && !this->GlobalGen->IsXcode() &&
  1136. this->UseBetterGraph) {
  1137. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1138. "_$<CONFIG>/qrc_", qrc.QrcName, ".cpp");
  1139. } else {
  1140. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1141. "/qrc_", qrc.QrcName, ".cpp");
  1142. }
  1143. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  1144. qrc.QrcName, '_', qrc.QrcPathChecksum);
  1145. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  1146. qrc.InfoFile = cmStrCat(base, "_Info.json");
  1147. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  1148. }
  1149. // rcc options
  1150. for (Qrc& qrc : this->Rcc.Qrcs) {
  1151. // Target options
  1152. std::vector<std::string> opts = optionsTarget;
  1153. // Merge computed "-name XYZ" option
  1154. {
  1155. std::string name = qrc.QrcName;
  1156. // Replace '-' with '_'. The former is not valid for symbol names.
  1157. std::replace(name.begin(), name.end(), '-', '_');
  1158. if (!qrc.Unique) {
  1159. name += cmStrCat('_', qrc.QrcPathChecksum);
  1160. }
  1161. std::vector<std::string> nameOpts;
  1162. nameOpts.emplace_back("-name");
  1163. nameOpts.emplace_back(std::move(name));
  1164. RccMergeOptions(opts, nameOpts, modernQt);
  1165. }
  1166. // Merge file option
  1167. RccMergeOptions(opts, qrc.Options, modernQt);
  1168. qrc.Options = std::move(opts);
  1169. }
  1170. // rcc resources
  1171. for (Qrc& qrc : this->Rcc.Qrcs) {
  1172. if (!qrc.Generated) {
  1173. std::string error;
  1174. if (this->MultiConfig && this->UseBetterGraph) {
  1175. for (auto const& config : this->ConfigsList) {
  1176. RccLister const lister(
  1177. this->Rcc.Executable.Config[config],
  1178. this->Rcc.ExecutableFeatures.Config[config]->ListOptions);
  1179. if (!lister.list(qrc.QrcFile, qrc.Resources.Config[config],
  1180. error)) {
  1181. cmSystemTools::Error(error);
  1182. return false;
  1183. }
  1184. }
  1185. } else {
  1186. RccLister const lister(
  1187. this->Rcc.Executable.Default,
  1188. this->Rcc.ExecutableFeatures.Default->ListOptions);
  1189. if (!lister.list(qrc.QrcFile, qrc.Resources.Default, error)) {
  1190. cmSystemTools::Error(error);
  1191. return false;
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. return true;
  1198. }
  1199. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1200. {
  1201. // Register info file as generated by CMake
  1202. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1203. // Determine whether to use a depfile for the AUTOGEN target.
  1204. bool const useDepfile = [this]() -> bool {
  1205. auto const& gen = this->GlobalGen->GetName();
  1206. return this->QtVersion >= IntegerVersion(5, 15) &&
  1207. (gen.find("Ninja") != std::string::npos ||
  1208. gen.find("Make") != std::string::npos);
  1209. }();
  1210. // Files provided by the autogen target
  1211. std::vector<std::string> autogenByproducts;
  1212. std::vector<std::string> timestampByproducts;
  1213. if (this->Moc.Enabled) {
  1214. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1215. if (useDepfile) {
  1216. if (this->CrossConfig &&
  1217. this->GlobalGen->GetName().find("Ninja") != std::string::npos &&
  1218. !this->UseBetterGraph) {
  1219. // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
  1220. // ${target}_autogen/timestamp custom command.
  1221. // We cannot just use Moc.CompilationFileGenex here, because that
  1222. // custom command runs cmake_autogen for each configuration.
  1223. for (auto const& p : this->Moc.CompilationFile.Config) {
  1224. timestampByproducts.push_back(p.second);
  1225. }
  1226. } else {
  1227. timestampByproducts.push_back(this->Moc.CompilationFileGenex);
  1228. }
  1229. } else {
  1230. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1231. }
  1232. }
  1233. if (this->Uic.Enabled) {
  1234. for (auto const& file : this->Uic.UiHeaders) {
  1235. this->AddGeneratedSource(file.first, this->Uic);
  1236. autogenByproducts.push_back(file.second);
  1237. }
  1238. }
  1239. // Compose target comment
  1240. std::string autogenComment;
  1241. {
  1242. std::string tools;
  1243. if (this->Moc.Enabled) {
  1244. tools += "MOC";
  1245. }
  1246. if (this->Uic.Enabled) {
  1247. if (!tools.empty()) {
  1248. tools += " and ";
  1249. }
  1250. tools += "UIC";
  1251. }
  1252. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1253. this->GenTarget->GetName());
  1254. }
  1255. // Compose command lines
  1256. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1257. // instead of fiddling with the include directories
  1258. bool constexpr stdPipesUTF8 = true;
  1259. cmCustomCommandLines commandLines;
  1260. AddCMakeProcessToCommandLines(this->AutogenTarget.InfoFile, "cmake_autogen",
  1261. commandLines);
  1262. // Use PRE_BUILD on demand
  1263. bool usePRE_BUILD = false;
  1264. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1265. // Under VS use a PRE_BUILD event instead of a separate target to
  1266. // reduce the number of targets loaded into the IDE.
  1267. // This also works around a VS 11 bug that may skip updating the target:
  1268. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1269. usePRE_BUILD = true;
  1270. }
  1271. // Disable PRE_BUILD in some cases
  1272. if (usePRE_BUILD) {
  1273. // Cannot use PRE_BUILD with file depends
  1274. if (!this->AutogenTarget.DependFiles.empty()) {
  1275. usePRE_BUILD = false;
  1276. }
  1277. // Cannot use PRE_BUILD when a global autogen target is in place
  1278. if (this->AutogenTarget.GlobalTarget) {
  1279. usePRE_BUILD = false;
  1280. }
  1281. }
  1282. // Create the autogen target/command
  1283. if (usePRE_BUILD) {
  1284. // Add additional autogen target dependencies to origin target
  1285. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1286. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1287. this->Makefile);
  1288. }
  1289. if (!this->Uic.UiFilesNoOptions.empty() ||
  1290. !this->Uic.UiFilesWithOptions.empty()) {
  1291. // Add a generated timestamp file
  1292. ConfigString timestampFile;
  1293. std::string timestampFileGenex;
  1294. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1295. cmStrCat(this->Dir.Build, "/autouic"_s),
  1296. ".stamp"_s);
  1297. this->AddGeneratedSource(timestampFile, this->Uic);
  1298. // Add a step in the pre-build command to touch the timestamp file
  1299. commandLines.push_back(
  1300. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1301. timestampFileGenex }));
  1302. // UIC needs to be re-run if any of the known UI files change or the
  1303. // executable itself has been updated
  1304. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1305. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1306. uicDependencies.push_back(uiFile.first);
  1307. }
  1308. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1309. // Add a rule file to cause the target to build if a dependency has
  1310. // changed, which will trigger the pre-build command to run autogen
  1311. auto cc = cm::make_unique<cmCustomCommand>();
  1312. cc->SetOutputs(timestampFileGenex);
  1313. cc->SetDepends(uicDependencies);
  1314. cc->SetComment("");
  1315. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1316. cc->SetEscapeOldStyle(false);
  1317. cc->SetStdPipesUTF8(stdPipesUTF8);
  1318. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1319. }
  1320. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1321. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1322. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1323. //
  1324. // PRE_BUILD does not support file dependencies!
  1325. cmCustomCommand cc;
  1326. cc.SetByproducts(autogenByproducts);
  1327. cc.SetCommandLines(commandLines);
  1328. cc.SetComment(autogenComment.c_str());
  1329. cc.SetBacktrace(this->Makefile->GetBacktrace());
  1330. cc.SetWorkingDirectory(this->Dir.Work.c_str());
  1331. cc.SetStdPipesUTF8(stdPipesUTF8);
  1332. cc.SetEscapeOldStyle(false);
  1333. cc.SetEscapeAllowMakeVars(true);
  1334. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1335. } else {
  1336. // Add link library target dependencies to the autogen target
  1337. // dependencies
  1338. if (this->AutogenTarget.DependOrigin) {
  1339. // add_dependencies/addUtility do not support generator expressions.
  1340. // We depend only on the libraries found in all configs therefore.
  1341. std::map<cmGeneratorTarget const*, std::size_t> targetsPartOfAllConfigs;
  1342. for (std::string const& config : this->ConfigsList) {
  1343. // The same target might appear multiple times in a config, but we
  1344. // should only count it once.
  1345. std::set<cmGeneratorTarget const*> seenTargets;
  1346. cmLinkImplementationLibraries const* libs =
  1347. this->GenTarget->GetLinkImplementationLibraries(
  1348. config, cmGeneratorTarget::UseTo::Link);
  1349. if (libs) {
  1350. for (cmLinkItem const& item : libs->Libraries) {
  1351. cmGeneratorTarget const* libTarget = item.Target;
  1352. if (libTarget &&
  1353. !StaticLibraryCycle(this->GenTarget, libTarget, config) &&
  1354. seenTargets.insert(libTarget).second) {
  1355. // Increment target config count
  1356. targetsPartOfAllConfigs[libTarget]++;
  1357. }
  1358. }
  1359. }
  1360. }
  1361. for (auto const& item : targetsPartOfAllConfigs) {
  1362. if (item.second == this->ConfigsList.size()) {
  1363. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1364. }
  1365. }
  1366. }
  1367. cmTarget* timestampTarget = nullptr;
  1368. std::vector<std::string> dependencies(
  1369. this->AutogenTarget.DependFiles.begin(),
  1370. this->AutogenTarget.DependFiles.end());
  1371. if (useDepfile) {
  1372. // Create a custom command that generates a timestamp file and
  1373. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1374. //
  1375. // Also create an additional '_autogen_timestamp_deps' that the custom
  1376. // command will depend on. It will have no sources or commands to
  1377. // execute, but it will have dependencies that would originally be
  1378. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1379. // serve as a list of order-only dependencies for the custom command,
  1380. // without forcing the custom command to re-execute.
  1381. //
  1382. // The dependency tree would then look like
  1383. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1384. // '_autogen' target.
  1385. auto const timestampTargetName =
  1386. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1387. auto cc = cm::make_unique<cmCustomCommand>();
  1388. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1389. cc->SetDepends(dependencies);
  1390. cc->SetEscapeOldStyle(false);
  1391. timestampTarget = this->LocalGen->AddUtilityCommand(timestampTargetName,
  1392. true, std::move(cc));
  1393. this->LocalGen->AddGeneratorTarget(
  1394. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1395. // Set FOLDER property on the timestamp target, so it appears in the
  1396. // appropriate folder in an IDE or in the file api.
  1397. if (!this->TargetsFolder.empty()) {
  1398. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1399. }
  1400. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1401. // moc and uic executables (whichever are enabled).
  1402. dependencies.clear();
  1403. dependencies.push_back(timestampTargetName);
  1404. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1405. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1406. std::string outputFile;
  1407. std::string depFile;
  1408. // Create the custom command that outputs the timestamp file.
  1409. if (this->MultiConfig && this->UseBetterGraph) {
  1410. // create timestamp file with $<CONFIG> in the name so that
  1411. // every cmake_autogen target has its own timestamp file
  1412. std::string const configView = "$<CONFIG>";
  1413. std::string const timestampFileWithoutConfig = "timestamp_";
  1414. std::string const depFileWithoutConfig =
  1415. cmStrCat(this->Dir.Build, "/deps_");
  1416. std::string const timestampFileName =
  1417. timestampFileWithoutConfig + configView;
  1418. outputFile = cmStrCat(this->Dir.Build, '/', timestampFileName);
  1419. auto const depFileWithConfig =
  1420. cmStrCat(depFileWithoutConfig, configView);
  1421. depFile = depFileWithConfig;
  1422. commandLines.push_back(cmMakeCommandLine(
  1423. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1424. ConfigString outputFileWithConfig;
  1425. for (std::string const& config : this->ConfigsList) {
  1426. auto tempTimestampFileName = timestampFileWithoutConfig + config;
  1427. auto tempDepFile = depFileWithoutConfig + config;
  1428. outputFileWithConfig.Config[config] = tempTimestampFileName;
  1429. this->AutogenTarget.DepFileRuleName.Config[config] =
  1430. cmStrCat(this->Dir.RelativeBuild, '/', tempTimestampFileName);
  1431. this->AutogenTarget.DepFile.Config[config] = tempDepFile;
  1432. }
  1433. this->AddGeneratedSource(outputFileWithConfig, this->Moc);
  1434. } else {
  1435. cm::string_view const timestampFileName = "timestamp";
  1436. outputFile = cmStrCat(this->Dir.Build, '/', timestampFileName);
  1437. this->AutogenTarget.DepFile.Default =
  1438. cmStrCat(this->Dir.Build, "/deps");
  1439. depFile = this->AutogenTarget.DepFile.Default;
  1440. this->AutogenTarget.DepFileRuleName.Default =
  1441. cmStrCat(this->Dir.RelativeBuild, '/', timestampFileName);
  1442. commandLines.push_back(cmMakeCommandLine(
  1443. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1444. this->AddGeneratedSource(outputFile, this->Moc);
  1445. }
  1446. cc = cm::make_unique<cmCustomCommand>();
  1447. cc->SetOutputs(outputFile);
  1448. cc->SetByproducts(timestampByproducts);
  1449. cc->SetDepends(dependencies);
  1450. cc->SetCommandLines(commandLines);
  1451. cc->SetComment(autogenComment.c_str());
  1452. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1453. cc->SetEscapeOldStyle(false);
  1454. cc->SetDepfile(depFile);
  1455. cc->SetStdPipesUTF8(stdPipesUTF8);
  1456. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1457. dependencies.clear();
  1458. dependencies.emplace_back(std::move(outputFile));
  1459. commandLines.clear();
  1460. autogenComment.clear();
  1461. }
  1462. // Create autogen target
  1463. auto cc = cm::make_unique<cmCustomCommand>();
  1464. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1465. cc->SetByproducts(autogenByproducts);
  1466. cc->SetDepends(dependencies);
  1467. cc->SetCommandLines(commandLines);
  1468. cc->SetEscapeOldStyle(false);
  1469. cc->SetComment(autogenComment.c_str());
  1470. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1471. this->AutogenTarget.Name, true, std::move(cc));
  1472. // Create autogen generator target
  1473. this->LocalGen->AddGeneratorTarget(
  1474. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1475. // Order the autogen target(s) just before the original target.
  1476. cmTarget* orderTarget = timestampTarget ? timestampTarget : autogenTarget;
  1477. // Forward origin utilities to autogen target
  1478. if (this->AutogenTarget.DependOrigin) {
  1479. for (BT<std::pair<std::string, bool>> const& depName :
  1480. this->GenTarget->GetUtilities()) {
  1481. orderTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1482. }
  1483. }
  1484. // Add additional autogen target dependencies to autogen target
  1485. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1486. orderTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1487. }
  1488. // Set FOLDER property in autogen target
  1489. if (!this->TargetsFolder.empty()) {
  1490. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1491. }
  1492. // Add autogen target to the origin target dependencies
  1493. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1494. this->Makefile);
  1495. // Add autogen target to the global autogen target dependencies
  1496. if (this->AutogenTarget.GlobalTarget) {
  1497. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1498. this->AutogenTarget.Name);
  1499. }
  1500. }
  1501. return true;
  1502. }
  1503. void cmQtAutoGenInitializer::AddCMakeProcessToCommandLines(
  1504. std::string const& infoFile, std::string const& processName,
  1505. cmCustomCommandLines& commandLines)
  1506. {
  1507. std::vector<std::string> autogenConfigs;
  1508. this->GlobalGen->GetQtAutoGenConfigs(autogenConfigs);
  1509. if (this->CrossConfig && this->UseBetterGraph) {
  1510. commandLines.push_back(cmMakeCommandLine(
  1511. { cmSystemTools::GetCMakeCommand(), "-E", processName, infoFile,
  1512. "$<CONFIG>", "$<COMMAND_CONFIG:$<CONFIG>>" }));
  1513. } else if ((this->MultiConfig && this->GlobalGen->IsXcode()) ||
  1514. this->CrossConfig) {
  1515. auto const& configs =
  1516. processName == "cmake_autorcc" ? this->ConfigsList : autogenConfigs;
  1517. for (std::string const& config : configs) {
  1518. commandLines.push_back(
  1519. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1520. processName, infoFile, config }));
  1521. }
  1522. } else {
  1523. std::string autoInfoFileConfig;
  1524. if (this->MultiConfig) {
  1525. autoInfoFileConfig = "$<CONFIG>";
  1526. } else {
  1527. autoInfoFileConfig = autogenConfigs[0];
  1528. }
  1529. commandLines.push_back(
  1530. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", processName,
  1531. infoFile, autoInfoFileConfig }));
  1532. }
  1533. }
  1534. bool cmQtAutoGenInitializer::InitRccTargets()
  1535. {
  1536. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1537. // Register info file as generated by CMake
  1538. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1539. // Register file at target
  1540. {
  1541. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1542. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1543. }
  1544. std::vector<std::string> ccOutput{ qrc.OutputFile };
  1545. // Add the .qrc and info file to the custom command dependencies
  1546. std::vector<std::string> ccDepends{ qrc.QrcFile, qrc.InfoFile };
  1547. cmCustomCommandLines commandLines;
  1548. AddCMakeProcessToCommandLines(qrc.InfoFile, "cmake_autorcc", commandLines);
  1549. std::string const ccComment =
  1550. cmStrCat("Automatic RCC for ",
  1551. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1552. auto cc = cm::make_unique<cmCustomCommand>();
  1553. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1554. cc->SetCommandLines(commandLines);
  1555. cc->SetComment(ccComment.c_str());
  1556. cc->SetStdPipesUTF8(true);
  1557. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1558. // Create custom rcc target
  1559. std::string ccName;
  1560. {
  1561. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1562. if (!qrc.Unique) {
  1563. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1564. }
  1565. cc->SetByproducts(ccOutput);
  1566. cc->SetDepends(ccDepends);
  1567. cc->SetEscapeOldStyle(false);
  1568. cmTarget* autoRccTarget =
  1569. this->LocalGen->AddUtilityCommand(ccName, true, std::move(cc));
  1570. // Create autogen generator target
  1571. this->LocalGen->AddGeneratorTarget(
  1572. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1573. // Set FOLDER property in autogen target
  1574. if (!this->TargetsFolder.empty()) {
  1575. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1576. }
  1577. if (!this->Rcc.ExecutableTargetName.empty()) {
  1578. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1579. this->Makefile);
  1580. }
  1581. }
  1582. // Add autogen target to the origin target dependencies
  1583. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1584. // Add autogen target to the global autogen target dependencies
  1585. if (this->Rcc.GlobalTarget) {
  1586. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1587. }
  1588. } else {
  1589. // Create custom rcc command
  1590. {
  1591. // Add the resource files to the dependencies
  1592. if (this->MultiConfig && this->UseBetterGraph) {
  1593. for (auto const& config : this->ConfigsList) {
  1594. // Add resource file to the custom command dependencies
  1595. auto resourceFilesWithConfig = cmStrCat(
  1596. "$<$<CONFIG:", config,
  1597. ">:", cmList{ qrc.Resources.Config.at(config) }.to_string(),
  1598. '>');
  1599. ccDepends.emplace_back(std::move(resourceFilesWithConfig));
  1600. }
  1601. } else {
  1602. for (std::string const& fileName : qrc.Resources.Default) {
  1603. // Add resource file to the custom command dependencies
  1604. ccDepends.push_back(fileName);
  1605. }
  1606. }
  1607. if (!this->Rcc.ExecutableTargetName.empty()) {
  1608. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1609. }
  1610. AddAutogenExecutableToDependencies(this->Rcc, ccDepends);
  1611. cc->SetOutputs(ccOutput);
  1612. cc->SetDepends(ccDepends);
  1613. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1614. }
  1615. // Reconfigure when .qrc file changes
  1616. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1617. }
  1618. }
  1619. return true;
  1620. }
  1621. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1622. {
  1623. // Create info directory on demand
  1624. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1625. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1626. Quoted(this->Dir.Info)));
  1627. return false;
  1628. }
  1629. // Generate autogen target info file
  1630. if (this->MocOrUicEnabled()) {
  1631. // Write autogen target info files
  1632. if (!this->SetupWriteAutogenInfo()) {
  1633. return false;
  1634. }
  1635. }
  1636. // Write AUTORCC info files
  1637. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1638. }
  1639. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1640. {
  1641. // Utility lambdas
  1642. auto MfDef = [this](std::string const& key) {
  1643. return this->Makefile->GetSafeDefinition(key);
  1644. };
  1645. // Filtered headers and sources
  1646. std::set<std::string> moc_skip;
  1647. std::set<std::string> uic_skip;
  1648. std::vector<MUFile const*> headers;
  1649. std::vector<MUFile const*> sources;
  1650. // Filter headers
  1651. {
  1652. headers.reserve(this->AutogenTarget.Headers.size());
  1653. for (auto const& pair : this->AutogenTarget.Headers) {
  1654. MUFile const* const muf = pair.second.get();
  1655. if (muf->SkipMoc) {
  1656. moc_skip.insert(muf->FullPath);
  1657. }
  1658. if (muf->SkipUic) {
  1659. uic_skip.insert(muf->FullPath);
  1660. }
  1661. if (muf->Generated && !this->CMP0071Accept) {
  1662. continue;
  1663. }
  1664. if (muf->MocIt || muf->UicIt) {
  1665. headers.emplace_back(muf);
  1666. }
  1667. }
  1668. std::sort(headers.begin(), headers.end(),
  1669. [](MUFile const* a, MUFile const* b) {
  1670. return (a->FullPath < b->FullPath);
  1671. });
  1672. }
  1673. // Filter sources
  1674. {
  1675. sources.reserve(this->AutogenTarget.Sources.size());
  1676. for (auto const& pair : this->AutogenTarget.Sources) {
  1677. MUFile const* const muf = pair.second.get();
  1678. if (muf->Generated && !this->CMP0071Accept) {
  1679. continue;
  1680. }
  1681. if (muf->SkipMoc) {
  1682. moc_skip.insert(muf->FullPath);
  1683. }
  1684. if (muf->SkipUic) {
  1685. uic_skip.insert(muf->FullPath);
  1686. }
  1687. if (muf->MocIt || muf->UicIt) {
  1688. sources.emplace_back(muf);
  1689. }
  1690. }
  1691. std::sort(sources.begin(), sources.end(),
  1692. [](MUFile const* a, MUFile const* b) {
  1693. return (a->FullPath < b->FullPath);
  1694. });
  1695. }
  1696. // Info writer
  1697. InfoWriter info;
  1698. // General
  1699. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1700. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1701. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1702. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1703. #ifdef _WIN32
  1704. info.SetUInt("AUTOGEN_COMMAND_LINE_LENGTH_MAX",
  1705. this->AutogenTarget.MaxCommandLineLength);
  1706. #endif
  1707. info.SetUInt("VERBOSITY", this->Verbosity);
  1708. // Directories
  1709. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1710. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1711. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1712. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1713. info.Set("BUILD_DIR", this->Dir.Build);
  1714. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1715. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1716. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1717. info.SetConfig("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1718. info.SetConfig("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1719. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1720. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1721. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1722. info.SetConfig("DEP_FILE", this->AutogenTarget.DepFile);
  1723. info.SetConfig("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1724. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1725. info.SetArray("HEADER_EXTENSIONS",
  1726. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1727. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1728. Json::Value value;
  1729. if (!configs.empty()) {
  1730. value = Json::arrayValue;
  1731. for (size_t ci : configs) {
  1732. value.append(this->ConfigsList[ci]);
  1733. }
  1734. }
  1735. return value;
  1736. };
  1737. info.SetArrayArray("HEADERS", headers,
  1738. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1739. jval.resize(4u);
  1740. jval[0u] = muf->FullPath;
  1741. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1742. muf->UicIt ? 'U' : 'u');
  1743. jval[2u] = this->GetMocBuildPath(*muf);
  1744. jval[3u] = cfgArray(muf->Configs);
  1745. });
  1746. info.SetArrayArray(
  1747. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1748. jval.resize(3u);
  1749. jval[0u] = muf->FullPath;
  1750. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1751. jval[2u] = cfgArray(muf->Configs);
  1752. });
  1753. // Write moc settings
  1754. if (this->Moc.Enabled) {
  1755. info.SetArray("MOC_SKIP", moc_skip);
  1756. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1757. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1758. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1759. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1760. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1761. EvaluatedTargetPropertyEntries InterfaceAutoMocMacroNamesEntries;
  1762. if (this->MultiConfig) {
  1763. for (auto const& cfg : this->ConfigsList) {
  1764. if (!cfg.empty()) {
  1765. cmGeneratorExpressionDAGChecker dagChecker{
  1766. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr,
  1767. nullptr, this->LocalGen, cfg,
  1768. };
  1769. AddInterfaceEntries(this->GenTarget, cfg,
  1770. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX",
  1771. &dagChecker, InterfaceAutoMocMacroNamesEntries,
  1772. IncludeRuntimeInterface::Yes);
  1773. }
  1774. }
  1775. } else {
  1776. cmGeneratorExpressionDAGChecker dagChecker{
  1777. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr,
  1778. nullptr, this->LocalGen, this->ConfigDefault,
  1779. };
  1780. AddInterfaceEntries(this->GenTarget, this->ConfigDefault,
  1781. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX", &dagChecker,
  1782. InterfaceAutoMocMacroNamesEntries,
  1783. IncludeRuntimeInterface::Yes);
  1784. }
  1785. for (auto const& entry : InterfaceAutoMocMacroNamesEntries.Entries) {
  1786. this->Moc.MacroNames.insert(this->Moc.MacroNames.end(),
  1787. entry.Values.begin(), entry.Values.end());
  1788. }
  1789. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  1790. this->Moc.MacroNames.end());
  1791. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1792. info.SetArrayArray(
  1793. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1794. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1795. jval.resize(2u);
  1796. jval[0u] = pair.first;
  1797. jval[1u] = pair.second;
  1798. });
  1799. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1800. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1801. cmStandardLevelResolver const resolver{ this->Makefile };
  1802. auto const CompileOptionFlag =
  1803. resolver.GetCompileOptionDef(this->GenTarget, "CXX", "");
  1804. auto const CompileOptionValue =
  1805. this->GenTarget->Makefile->GetSafeDefinition(CompileOptionFlag);
  1806. if (!CompileOptionValue.empty()) {
  1807. if (this->Moc.PredefsCmd.size() >= 3) {
  1808. this->Moc.PredefsCmd.insert(this->Moc.PredefsCmd.begin() + 1,
  1809. CompileOptionValue);
  1810. }
  1811. }
  1812. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1813. }
  1814. // Write uic settings
  1815. if (this->Uic.Enabled) {
  1816. // Add skipped .ui files
  1817. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1818. info.SetArray("UIC_SKIP", uic_skip);
  1819. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1820. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1821. jval.resize(2u);
  1822. jval[0u] = uiFile.first;
  1823. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1824. });
  1825. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1826. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1827. }
  1828. info.Save(this->AutogenTarget.InfoFile);
  1829. return true;
  1830. }
  1831. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1832. {
  1833. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1834. // Utility lambdas
  1835. auto MfDef = [this](std::string const& key) {
  1836. return this->Makefile->GetSafeDefinition(key);
  1837. };
  1838. InfoWriter info;
  1839. // General
  1840. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1841. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1842. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1843. info.SetUInt("VERBOSITY", this->Verbosity);
  1844. info.Set("GENERATOR", this->GlobalGen->GetName());
  1845. // Files
  1846. info.Set("LOCK_FILE", qrc.LockFile);
  1847. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1848. // Directories
  1849. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1850. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1851. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1852. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1853. info.Set("BUILD_DIR", this->Dir.Build);
  1854. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1855. // rcc executable
  1856. info.SetConfig("RCC_EXECUTABLE", this->Rcc.Executable);
  1857. info.SetConfigArray(
  1858. "RCC_LIST_OPTIONS",
  1859. generateListOptions(this->Rcc.ExecutableFeatures, this->MultiConfig));
  1860. // qrc file
  1861. info.Set("SOURCE", qrc.QrcFile);
  1862. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1863. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1864. info.SetArray("OPTIONS", qrc.Options);
  1865. info.SetConfigArray("INPUTS", qrc.Resources);
  1866. info.Save(qrc.InfoFile);
  1867. }
  1868. return true;
  1869. }
  1870. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1871. std::string const& filename)
  1872. {
  1873. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1874. gFile->MarkAsGenerated();
  1875. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1876. gFile->SetProperty("SKIP_LINTING", "ON");
  1877. gFile->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1878. return gFile;
  1879. }
  1880. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1881. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1882. {
  1883. // Register source at makefile
  1884. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1885. // Add source file to target
  1886. this->GenTarget->AddSource(filename, prepend);
  1887. // Add source file to source group
  1888. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1889. return gFile;
  1890. }
  1891. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1892. GenVarsT const& genVars,
  1893. bool prepend)
  1894. {
  1895. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1896. // when the Xcode generator supports per-config sources.
  1897. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1898. cmSourceFile* sf =
  1899. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1900. handleSkipPch(sf);
  1901. return;
  1902. }
  1903. for (auto const& cfg : this->ConfigsList) {
  1904. std::string const& filenameCfg = filename.Config.at(cfg);
  1905. // Register source at makefile
  1906. cmSourceFile* sf = this->RegisterGeneratedSource(filenameCfg);
  1907. handleSkipPch(sf);
  1908. // Add source file to target for this configuration.
  1909. this->GenTarget->AddSource(
  1910. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1911. // Add source file to source group
  1912. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1913. }
  1914. }
  1915. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1916. cm::string_view genNameUpper)
  1917. {
  1918. cmSourceGroup* sourceGroup = nullptr;
  1919. // Acquire source group
  1920. {
  1921. std::string property;
  1922. std::string groupName;
  1923. {
  1924. // Prefer generator specific source group name
  1925. std::initializer_list<std::string> const props{
  1926. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1927. };
  1928. for (std::string const& prop : props) {
  1929. cmValue propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1930. if (cmNonempty(propName)) {
  1931. groupName = *propName;
  1932. property = prop;
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. // Generate a source group on demand
  1938. if (!groupName.empty()) {
  1939. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1940. if (!sourceGroup) {
  1941. cmSystemTools::Error(
  1942. cmStrCat(genNameUpper, " error in ", property,
  1943. ": Could not find or create the source group ",
  1944. cmQtAutoGen::Quoted(groupName)));
  1945. }
  1946. }
  1947. }
  1948. if (sourceGroup) {
  1949. sourceGroup->AddGroupFile(fileName);
  1950. }
  1951. }
  1952. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1953. {
  1954. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName);
  1955. }
  1956. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1957. cm::string_view prefix,
  1958. cm::string_view suffix)
  1959. {
  1960. configString.Default = cmStrCat(prefix, suffix);
  1961. if (this->MultiConfig) {
  1962. for (auto const& cfg : this->ConfigsList) {
  1963. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1964. }
  1965. }
  1966. }
  1967. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1968. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1969. cm::string_view const suffix)
  1970. {
  1971. this->ConfigFileNames(configString, prefix, suffix);
  1972. if (this->MultiConfig) {
  1973. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1974. } else {
  1975. genex = configString.Default;
  1976. }
  1977. }
  1978. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1979. {
  1980. this->AddCleanFile(configString.Default);
  1981. if (this->MultiConfig) {
  1982. for (auto const& pair : configString.Config) {
  1983. this->AddCleanFile(pair.second);
  1984. }
  1985. }
  1986. }
  1987. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  1988. {
  1989. cmQtAutoGen::IntegerVersion result;
  1990. static std::string const prelude = "moc ";
  1991. size_t const pos = str.find(prelude);
  1992. if (pos == std::string::npos) {
  1993. return result;
  1994. }
  1995. str.erase(0, prelude.size() + pos);
  1996. std::istringstream iss(str);
  1997. std::string major;
  1998. std::string minor;
  1999. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  2000. return result;
  2001. }
  2002. result.Major = static_cast<unsigned int>(std::stoi(major));
  2003. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  2004. return result;
  2005. }
  2006. static cmQtAutoGen::IntegerVersion GetMocVersion(
  2007. std::string const& mocExecutablePath)
  2008. {
  2009. std::string capturedStdOut;
  2010. int exitCode;
  2011. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  2012. &capturedStdOut, nullptr, &exitCode,
  2013. nullptr, cmSystemTools::OUTPUT_NONE)) {
  2014. return {};
  2015. }
  2016. if (exitCode != 0) {
  2017. return {};
  2018. }
  2019. return parseMocVersion(capturedStdOut);
  2020. }
  2021. static std::string FindMocExecutableFromMocTarget(cmMakefile const* makefile,
  2022. unsigned int qtMajorVersion)
  2023. {
  2024. std::string result;
  2025. std::string const mocTargetName = cmStrCat("Qt", qtMajorVersion, "::moc");
  2026. cmTarget const* mocTarget = makefile->FindTargetToUse(mocTargetName);
  2027. if (mocTarget) {
  2028. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  2029. }
  2030. return result;
  2031. }
  2032. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  2033. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  2034. std::string mocExecutable)
  2035. {
  2036. // Converts a char ptr to an unsigned int value
  2037. auto toUInt = [](char const* const input) -> unsigned int {
  2038. unsigned long tmp = 0;
  2039. if (input && cmStrToULong(input, &tmp)) {
  2040. return static_cast<unsigned int>(tmp);
  2041. }
  2042. return 0u;
  2043. };
  2044. auto toUInt2 = [](cmValue input) -> unsigned int {
  2045. unsigned long tmp = 0;
  2046. if (input && cmStrToULong(*input, &tmp)) {
  2047. return static_cast<unsigned int>(tmp);
  2048. }
  2049. return 0u;
  2050. };
  2051. // Initialize return value to a default
  2052. std::pair<IntegerVersion, unsigned int> res(
  2053. IntegerVersion(),
  2054. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  2055. "")));
  2056. // Acquire known Qt versions
  2057. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  2058. {
  2059. // Qt version variable prefixes
  2060. static std::initializer_list<
  2061. std::pair<cm::string_view, cm::string_view>> const keys{
  2062. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  2063. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  2064. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  2065. };
  2066. knownQtVersions.reserve(keys.size() * 2);
  2067. // Adds a version to the result (nullptr safe)
  2068. auto addVersion = [&knownQtVersions, &toUInt2](cmValue major,
  2069. cmValue minor) {
  2070. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  2071. if (ver.Major != 0) {
  2072. knownQtVersions.emplace_back(ver);
  2073. }
  2074. };
  2075. // Read versions from variables
  2076. for (auto const& keyPair : keys) {
  2077. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  2078. target->Makefile->GetDefinition(std::string(keyPair.second)));
  2079. }
  2080. // Read versions from directory properties
  2081. for (auto const& keyPair : keys) {
  2082. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  2083. target->Makefile->GetProperty(std::string(keyPair.second)));
  2084. }
  2085. }
  2086. // Evaluate known Qt versions
  2087. if (!knownQtVersions.empty()) {
  2088. if (res.second == 0) {
  2089. // No specific version was requested by the target:
  2090. // Use highest known Qt version.
  2091. res.first = knownQtVersions.at(0);
  2092. } else {
  2093. // Pick a version from the known versions:
  2094. for (auto const& it : knownQtVersions) {
  2095. if (it.Major == res.second) {
  2096. res.first = it;
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. }
  2102. if (res.first.Major == 0) {
  2103. // We could not get the version number from variables or directory
  2104. // properties. This might happen if the find_package call for Qt is wrapped
  2105. // in a function. Try to find the moc executable path from the available
  2106. // targets and call "moc --version" to get the Qt version.
  2107. if (mocExecutable.empty()) {
  2108. mocExecutable =
  2109. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  2110. }
  2111. if (!mocExecutable.empty()) {
  2112. res.first = GetMocVersion(mocExecutable);
  2113. }
  2114. }
  2115. return res;
  2116. }
  2117. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  2118. {
  2119. std::string res;
  2120. if (!muf.MocIt) {
  2121. return res;
  2122. }
  2123. std::string basePath =
  2124. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  2125. FileNameWithoutLastExtension(muf.FullPath));
  2126. res = cmStrCat(basePath, ".cpp");
  2127. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2128. return res;
  2129. }
  2130. // File name already emitted.
  2131. // Try appending the header suffix to the base path.
  2132. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  2133. res = cmStrCat(basePath, ".cpp");
  2134. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2135. return res;
  2136. }
  2137. // File name with header extension already emitted.
  2138. // Try adding a number to the base path.
  2139. constexpr std::size_t number_begin = 2;
  2140. constexpr std::size_t number_end = 256;
  2141. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  2142. res = cmStrCat(basePath, '_', ii, ".cpp");
  2143. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2144. return res;
  2145. }
  2146. }
  2147. // Output file name conflict (unlikely, but still...)
  2148. cmSystemTools::Error(
  2149. cmStrCat("moc output file name conflict for ", muf.FullPath));
  2150. return res;
  2151. }
  2152. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  2153. std::string const& executable,
  2154. bool ignoreMissingTarget) const
  2155. {
  2156. auto print_err = [this, &genVars](std::string const& err) {
  2157. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  2158. this->GenTarget->GetName(), ": ", err));
  2159. };
  2160. // Custom executable
  2161. {
  2162. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  2163. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  2164. if (!val.empty()) {
  2165. // Evaluate generator expression
  2166. {
  2167. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2168. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  2169. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  2170. if (this->MultiConfig && this->UseBetterGraph) {
  2171. for (auto const& config : this->ConfigsList) {
  2172. genVars.Executable.Config[config] =
  2173. cge->Evaluate(this->LocalGen, config);
  2174. }
  2175. } else {
  2176. genVars.Executable.Default = cge->Evaluate(this->LocalGen, "");
  2177. }
  2178. }
  2179. if (genVars.Executable.Default.empty() &&
  2180. genVars.Executable.Config.empty() && !ignoreMissingTarget) {
  2181. print_err(prop + " evaluates to an empty value");
  2182. return false;
  2183. }
  2184. // Create empty compiler features.
  2185. if (this->MultiConfig && this->UseBetterGraph) {
  2186. for (auto const& config : this->ConfigsList) {
  2187. genVars.ExecutableFeatures.Config[config] =
  2188. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2189. }
  2190. } else {
  2191. genVars.ExecutableFeatures.Default =
  2192. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2193. }
  2194. return true;
  2195. }
  2196. }
  2197. // Find executable target
  2198. {
  2199. // Find executable target name
  2200. cm::string_view prefix;
  2201. if (this->QtVersion.Major == 4) {
  2202. prefix = "Qt4::";
  2203. } else if (this->QtVersion.Major == 5) {
  2204. prefix = "Qt5::";
  2205. } else if (this->QtVersion.Major == 6) {
  2206. prefix = "Qt6::";
  2207. }
  2208. std::string const targetName = cmStrCat(prefix, executable);
  2209. // Find target
  2210. cmGeneratorTarget* genTarget =
  2211. this->LocalGen->FindGeneratorTargetToUse(targetName);
  2212. if (genTarget) {
  2213. genVars.ExecutableTargetName = targetName;
  2214. genVars.ExecutableTarget = genTarget;
  2215. if (genTarget->IsImported()) {
  2216. if (this->MultiConfig && this->UseBetterGraph) {
  2217. for (auto const& config : this->ConfigsList) {
  2218. genVars.Executable.Config[config] =
  2219. genTarget->ImportedGetLocation(config);
  2220. }
  2221. } else {
  2222. genVars.Executable.Default =
  2223. genTarget->ImportedGetLocation(this->ConfigDefault);
  2224. }
  2225. } else {
  2226. if (this->MultiConfig && this->UseBetterGraph) {
  2227. for (auto const& config : this->ConfigsList) {
  2228. genVars.Executable.Config[config] = genTarget->GetLocation(config);
  2229. }
  2230. } else {
  2231. genVars.Executable.Default =
  2232. genTarget->GetLocation(this->ConfigDefault);
  2233. }
  2234. }
  2235. } else {
  2236. if (ignoreMissingTarget) {
  2237. // Create empty compiler features.
  2238. if (this->MultiConfig && this->UseBetterGraph) {
  2239. for (auto const& config : this->ConfigsList) {
  2240. genVars.ExecutableFeatures.Config[config] =
  2241. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2242. }
  2243. } else {
  2244. genVars.ExecutableFeatures.Default =
  2245. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2246. }
  2247. return true;
  2248. }
  2249. print_err(cmStrCat("Could not find ", executable, " executable target ",
  2250. targetName));
  2251. return false;
  2252. }
  2253. }
  2254. // Get executable features
  2255. {
  2256. std::string err;
  2257. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  2258. executable, genVars.Executable, err, this->MultiConfig,
  2259. this->UseBetterGraph);
  2260. if (this->MultiConfig && this->UseBetterGraph) {
  2261. for (auto const& config : this->ConfigsList) {
  2262. if (!genVars.ExecutableFeatures.Config[config]) {
  2263. if (!genVars.ExecutableFeatures.Config[config]) {
  2264. print_err(err);
  2265. return false;
  2266. }
  2267. }
  2268. }
  2269. } else {
  2270. if (!genVars.ExecutableFeatures.Default) {
  2271. print_err(err);
  2272. return false;
  2273. }
  2274. }
  2275. }
  2276. return true;
  2277. }
  2278. void cmQtAutoGenInitializer::handleSkipPch(cmSourceFile* sf)
  2279. {
  2280. bool skipPch = true;
  2281. for (auto const& pair : this->AutogenTarget.Sources) {
  2282. if (!pair.first->GetIsGenerated() &&
  2283. !pair.first->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2284. skipPch = false;
  2285. }
  2286. }
  2287. if (skipPch) {
  2288. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2289. }
  2290. }