cmQtAutoGenInitializer.cxx 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt 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), '\n',
  1073. "For compatibility, CMake is excluding the GENERATED source "
  1074. "file(s):\n",
  1075. files, "from processing by ",
  1076. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1077. ". If any of the files should be processed, set CMP0071 to NEW. "
  1078. "If any of the files should not be processed, "
  1079. "explicitly exclude them by setting the source file property ",
  1080. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  1081. " ON)\n"));
  1082. }
  1083. }
  1084. // Generate CMP0100 warning
  1085. if (this->MocOrUicEnabled() &&
  1086. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  1087. cm::string_view property;
  1088. if (this->Moc.Enabled && this->Uic.Enabled) {
  1089. property = "SKIP_AUTOGEN";
  1090. } else if (this->Moc.Enabled) {
  1091. property = "SKIP_AUTOMOC";
  1092. } else if (this->Uic.Enabled) {
  1093. property = "SKIP_AUTOUIC";
  1094. }
  1095. std::string files;
  1096. for (cmSourceFile const* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  1097. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  1098. }
  1099. this->Makefile->IssueMessage(
  1100. MessageType::AUTHOR_WARNING,
  1101. cmStrCat(
  1102. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
  1103. "For compatibility, CMake is excluding the header file(s):\n", files,
  1104. "from processing by ",
  1105. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  1106. ". If any of the files should be processed, set CMP0100 to NEW. "
  1107. "If any of the files should not be processed, "
  1108. "explicitly exclude them by setting the source file property ",
  1109. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  1110. " ON)\n"));
  1111. }
  1112. // Process qrc files
  1113. if (!this->Rcc.Qrcs.empty()) {
  1114. bool const modernQt = (this->QtVersion.Major >= 5);
  1115. // Target rcc options
  1116. cmList const optionsTarget{ this->GenTarget->GetSafeProperty(
  1117. kw.AUTORCC_OPTIONS) };
  1118. // Check if file name is unique
  1119. for (Qrc& qrc : this->Rcc.Qrcs) {
  1120. qrc.Unique = true;
  1121. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  1122. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  1123. qrc.Unique = false;
  1124. break;
  1125. }
  1126. }
  1127. }
  1128. // Path checksum and file names
  1129. for (Qrc& qrc : this->Rcc.Qrcs) {
  1130. // Path checksum
  1131. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  1132. // Output file name
  1133. if (this->MultiConfig && !this->GlobalGen->IsXcode() &&
  1134. this->UseBetterGraph) {
  1135. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1136. "_$<CONFIG>", "/qrc_", qrc.QrcName, ".cpp");
  1137. } else {
  1138. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  1139. "/qrc_", qrc.QrcName, ".cpp");
  1140. }
  1141. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  1142. qrc.QrcName, '_', qrc.QrcPathChecksum);
  1143. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  1144. qrc.InfoFile = cmStrCat(base, "_Info.json");
  1145. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  1146. }
  1147. // rcc options
  1148. for (Qrc& qrc : this->Rcc.Qrcs) {
  1149. // Target options
  1150. std::vector<std::string> opts = optionsTarget;
  1151. // Merge computed "-name XYZ" option
  1152. {
  1153. std::string name = qrc.QrcName;
  1154. // Replace '-' with '_'. The former is not valid for symbol names.
  1155. std::replace(name.begin(), name.end(), '-', '_');
  1156. if (!qrc.Unique) {
  1157. name += cmStrCat('_', qrc.QrcPathChecksum);
  1158. }
  1159. std::vector<std::string> nameOpts;
  1160. nameOpts.emplace_back("-name");
  1161. nameOpts.emplace_back(std::move(name));
  1162. RccMergeOptions(opts, nameOpts, modernQt);
  1163. }
  1164. // Merge file option
  1165. RccMergeOptions(opts, qrc.Options, modernQt);
  1166. qrc.Options = std::move(opts);
  1167. }
  1168. // rcc resources
  1169. for (Qrc& qrc : this->Rcc.Qrcs) {
  1170. if (!qrc.Generated) {
  1171. std::string error;
  1172. if (this->MultiConfig && this->UseBetterGraph) {
  1173. for (auto const& config : this->ConfigsList) {
  1174. RccLister const lister(
  1175. this->Rcc.Executable.Config[config],
  1176. this->Rcc.ExecutableFeatures.Config[config]->ListOptions);
  1177. if (!lister.list(qrc.QrcFile, qrc.Resources.Config[config],
  1178. error)) {
  1179. cmSystemTools::Error(error);
  1180. return false;
  1181. }
  1182. }
  1183. } else {
  1184. RccLister const lister(
  1185. this->Rcc.Executable.Default,
  1186. this->Rcc.ExecutableFeatures.Default->ListOptions);
  1187. if (!lister.list(qrc.QrcFile, qrc.Resources.Default, error)) {
  1188. cmSystemTools::Error(error);
  1189. return false;
  1190. }
  1191. }
  1192. }
  1193. }
  1194. }
  1195. return true;
  1196. }
  1197. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1198. {
  1199. // Register info file as generated by CMake
  1200. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1201. // Determine whether to use a depfile for the AUTOGEN target.
  1202. bool const useDepfile = [this]() -> bool {
  1203. auto const& gen = this->GlobalGen->GetName();
  1204. return this->QtVersion >= IntegerVersion(5, 15) &&
  1205. (gen.find("Ninja") != std::string::npos ||
  1206. gen.find("Make") != std::string::npos);
  1207. }();
  1208. // Files provided by the autogen target
  1209. std::vector<std::string> autogenByproducts;
  1210. std::vector<std::string> timestampByproducts;
  1211. if (this->Moc.Enabled) {
  1212. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1213. if (useDepfile) {
  1214. if (this->CrossConfig &&
  1215. this->GlobalGen->GetName().find("Ninja") != std::string::npos &&
  1216. !this->UseBetterGraph) {
  1217. // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
  1218. // ${target}_autogen/timestamp custom command.
  1219. // We cannot just use Moc.CompilationFileGenex here, because that
  1220. // custom command runs cmake_autogen for each configuration.
  1221. for (auto const& p : this->Moc.CompilationFile.Config) {
  1222. timestampByproducts.push_back(p.second);
  1223. }
  1224. } else {
  1225. timestampByproducts.push_back(this->Moc.CompilationFileGenex);
  1226. }
  1227. } else {
  1228. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1229. }
  1230. }
  1231. if (this->Uic.Enabled) {
  1232. for (auto const& file : this->Uic.UiHeaders) {
  1233. this->AddGeneratedSource(file.first, this->Uic);
  1234. autogenByproducts.push_back(file.second);
  1235. }
  1236. }
  1237. // Compose target comment
  1238. std::string autogenComment;
  1239. {
  1240. std::string tools;
  1241. if (this->Moc.Enabled) {
  1242. tools += "MOC";
  1243. }
  1244. if (this->Uic.Enabled) {
  1245. if (!tools.empty()) {
  1246. tools += " and ";
  1247. }
  1248. tools += "UIC";
  1249. }
  1250. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1251. this->GenTarget->GetName());
  1252. }
  1253. // Compose command lines
  1254. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1255. // instead of fiddling with the include directories
  1256. bool constexpr stdPipesUTF8 = true;
  1257. cmCustomCommandLines commandLines;
  1258. AddCMakeProcessToCommandLines(this->AutogenTarget.InfoFile, "cmake_autogen",
  1259. commandLines);
  1260. // Use PRE_BUILD on demand
  1261. bool usePRE_BUILD = false;
  1262. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1263. // Under VS use a PRE_BUILD event instead of a separate target to
  1264. // reduce the number of targets loaded into the IDE.
  1265. // This also works around a VS 11 bug that may skip updating the target:
  1266. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1267. usePRE_BUILD = true;
  1268. }
  1269. // Disable PRE_BUILD in some cases
  1270. if (usePRE_BUILD) {
  1271. // Cannot use PRE_BUILD with file depends
  1272. if (!this->AutogenTarget.DependFiles.empty()) {
  1273. usePRE_BUILD = false;
  1274. }
  1275. // Cannot use PRE_BUILD when a global autogen target is in place
  1276. if (this->AutogenTarget.GlobalTarget) {
  1277. usePRE_BUILD = false;
  1278. }
  1279. }
  1280. // Create the autogen target/command
  1281. if (usePRE_BUILD) {
  1282. // Add additional autogen target dependencies to origin target
  1283. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1284. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1285. this->Makefile);
  1286. }
  1287. if (!this->Uic.UiFilesNoOptions.empty() ||
  1288. !this->Uic.UiFilesWithOptions.empty()) {
  1289. // Add a generated timestamp file
  1290. ConfigString timestampFile;
  1291. std::string timestampFileGenex;
  1292. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1293. cmStrCat(this->Dir.Build, "/autouic"_s),
  1294. ".stamp"_s);
  1295. this->AddGeneratedSource(timestampFile, this->Uic);
  1296. // Add a step in the pre-build command to touch the timestamp file
  1297. commandLines.push_back(
  1298. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1299. timestampFileGenex }));
  1300. // UIC needs to be re-run if any of the known UI files change or the
  1301. // executable itself has been updated
  1302. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1303. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1304. uicDependencies.push_back(uiFile.first);
  1305. }
  1306. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1307. // Add a rule file to cause the target to build if a dependency has
  1308. // changed, which will trigger the pre-build command to run autogen
  1309. auto cc = cm::make_unique<cmCustomCommand>();
  1310. cc->SetOutputs(timestampFileGenex);
  1311. cc->SetDepends(uicDependencies);
  1312. cc->SetComment("");
  1313. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1314. cc->SetEscapeOldStyle(false);
  1315. cc->SetStdPipesUTF8(stdPipesUTF8);
  1316. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1317. }
  1318. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1319. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1320. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1321. //
  1322. // PRE_BUILD does not support file dependencies!
  1323. cmCustomCommand cc;
  1324. cc.SetByproducts(autogenByproducts);
  1325. cc.SetCommandLines(commandLines);
  1326. cc.SetComment(autogenComment.c_str());
  1327. cc.SetBacktrace(this->Makefile->GetBacktrace());
  1328. cc.SetWorkingDirectory(this->Dir.Work.c_str());
  1329. cc.SetStdPipesUTF8(stdPipesUTF8);
  1330. cc.SetEscapeOldStyle(false);
  1331. cc.SetEscapeAllowMakeVars(true);
  1332. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1333. } else {
  1334. // Add link library target dependencies to the autogen target
  1335. // dependencies
  1336. if (this->AutogenTarget.DependOrigin) {
  1337. // add_dependencies/addUtility do not support generator expressions.
  1338. // We depend only on the libraries found in all configs therefore.
  1339. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1340. for (std::string const& config : this->ConfigsList) {
  1341. cmLinkImplementationLibraries const* libs =
  1342. this->GenTarget->GetLinkImplementationLibraries(
  1343. config, cmGeneratorTarget::UseTo::Link);
  1344. if (libs) {
  1345. for (cmLinkItem const& item : libs->Libraries) {
  1346. cmGeneratorTarget const* libTarget = item.Target;
  1347. if (libTarget &&
  1348. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1349. // Increment target config count
  1350. commonTargets[libTarget]++;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. for (auto const& item : commonTargets) {
  1356. if (item.second == this->ConfigsList.size()) {
  1357. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1358. }
  1359. }
  1360. }
  1361. cmTarget* timestampTarget = nullptr;
  1362. std::vector<std::string> dependencies(
  1363. this->AutogenTarget.DependFiles.begin(),
  1364. this->AutogenTarget.DependFiles.end());
  1365. if (useDepfile) {
  1366. // Create a custom command that generates a timestamp file and
  1367. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1368. //
  1369. // Also create an additional '_autogen_timestamp_deps' that the custom
  1370. // command will depend on. It will have no sources or commands to
  1371. // execute, but it will have dependencies that would originally be
  1372. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1373. // serve as a list of order-only dependencies for the custom command,
  1374. // without forcing the custom command to re-execute.
  1375. //
  1376. // The dependency tree would then look like
  1377. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1378. // '_autogen' target.
  1379. auto const timestampTargetName =
  1380. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1381. auto cc = cm::make_unique<cmCustomCommand>();
  1382. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1383. cc->SetDepends(dependencies);
  1384. cc->SetEscapeOldStyle(false);
  1385. timestampTarget = this->LocalGen->AddUtilityCommand(timestampTargetName,
  1386. true, std::move(cc));
  1387. this->LocalGen->AddGeneratorTarget(
  1388. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1389. // Set FOLDER property on the timestamp target, so it appears in the
  1390. // appropriate folder in an IDE or in the file api.
  1391. if (!this->TargetsFolder.empty()) {
  1392. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1393. }
  1394. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1395. // moc and uic executables (whichever are enabled).
  1396. dependencies.clear();
  1397. dependencies.push_back(timestampTargetName);
  1398. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1399. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1400. std::string outputFile;
  1401. std::string depFile;
  1402. // Create the custom command that outputs the timestamp file.
  1403. if (this->MultiConfig && this->UseBetterGraph) {
  1404. // create timestamp file with $<CONFIG> in the name so that
  1405. // every cmake_autogen target has its own timestamp file
  1406. std::string const configView = "$<CONFIG>";
  1407. std::string const timestampFileWithoutConfig = "timestamp_";
  1408. std::string const depFileWithoutConfig =
  1409. cmStrCat(this->Dir.Build, "/deps_");
  1410. std::string const timestampFileName =
  1411. timestampFileWithoutConfig + configView;
  1412. outputFile = cmStrCat(this->Dir.Build, "/", timestampFileName);
  1413. auto const depFileWithConfig =
  1414. cmStrCat(depFileWithoutConfig, configView);
  1415. depFile = depFileWithConfig;
  1416. commandLines.push_back(cmMakeCommandLine(
  1417. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1418. ConfigString outputFileWithConfig;
  1419. for (std::string const& config : this->ConfigsList) {
  1420. auto tempTimestampFileName = timestampFileWithoutConfig + config;
  1421. auto tempDepFile = depFileWithoutConfig + config;
  1422. outputFileWithConfig.Config[config] = tempTimestampFileName;
  1423. this->AutogenTarget.DepFileRuleName.Config[config] =
  1424. cmStrCat(this->Dir.RelativeBuild, "/", tempTimestampFileName);
  1425. this->AutogenTarget.DepFile.Config[config] = tempDepFile;
  1426. }
  1427. this->AddGeneratedSource(outputFileWithConfig, this->Moc);
  1428. } else {
  1429. cm::string_view const timestampFileName = "timestamp";
  1430. outputFile = cmStrCat(this->Dir.Build, "/", timestampFileName);
  1431. this->AutogenTarget.DepFile.Default =
  1432. cmStrCat(this->Dir.Build, "/deps");
  1433. depFile = this->AutogenTarget.DepFile.Default;
  1434. this->AutogenTarget.DepFileRuleName.Default =
  1435. cmStrCat(this->Dir.RelativeBuild, "/", timestampFileName);
  1436. commandLines.push_back(cmMakeCommandLine(
  1437. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1438. this->AddGeneratedSource(outputFile, this->Moc);
  1439. }
  1440. cc = cm::make_unique<cmCustomCommand>();
  1441. cc->SetOutputs(outputFile);
  1442. cc->SetByproducts(timestampByproducts);
  1443. cc->SetDepends(dependencies);
  1444. cc->SetCommandLines(commandLines);
  1445. cc->SetComment(autogenComment.c_str());
  1446. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1447. cc->SetEscapeOldStyle(false);
  1448. cc->SetDepfile(depFile);
  1449. cc->SetStdPipesUTF8(stdPipesUTF8);
  1450. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1451. dependencies.clear();
  1452. dependencies.emplace_back(std::move(outputFile));
  1453. commandLines.clear();
  1454. autogenComment.clear();
  1455. }
  1456. // Create autogen target
  1457. auto cc = cm::make_unique<cmCustomCommand>();
  1458. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1459. cc->SetByproducts(autogenByproducts);
  1460. cc->SetDepends(dependencies);
  1461. cc->SetCommandLines(commandLines);
  1462. cc->SetEscapeOldStyle(false);
  1463. cc->SetComment(autogenComment.c_str());
  1464. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1465. this->AutogenTarget.Name, true, std::move(cc));
  1466. // Create autogen generator target
  1467. this->LocalGen->AddGeneratorTarget(
  1468. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1469. // Order the autogen target(s) just before the original target.
  1470. cmTarget* orderTarget = timestampTarget ? timestampTarget : autogenTarget;
  1471. // Forward origin utilities to autogen target
  1472. if (this->AutogenTarget.DependOrigin) {
  1473. for (BT<std::pair<std::string, bool>> const& depName :
  1474. this->GenTarget->GetUtilities()) {
  1475. orderTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1476. }
  1477. }
  1478. // Add additional autogen target dependencies to autogen target
  1479. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1480. orderTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1481. }
  1482. // Set FOLDER property in autogen target
  1483. if (!this->TargetsFolder.empty()) {
  1484. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1485. }
  1486. // Add autogen target to the origin target dependencies
  1487. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1488. this->Makefile);
  1489. // Add autogen target to the global autogen target dependencies
  1490. if (this->AutogenTarget.GlobalTarget) {
  1491. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1492. this->AutogenTarget.Name);
  1493. }
  1494. }
  1495. return true;
  1496. }
  1497. void cmQtAutoGenInitializer::AddCMakeProcessToCommandLines(
  1498. std::string const& infoFile, std::string const& processName,
  1499. cmCustomCommandLines& commandLines)
  1500. {
  1501. std::vector<std::string> autogenConfigs;
  1502. this->GlobalGen->GetQtAutoGenConfigs(autogenConfigs);
  1503. if (this->CrossConfig && this->UseBetterGraph) {
  1504. commandLines.push_back(cmMakeCommandLine(
  1505. { cmSystemTools::GetCMakeCommand(), "-E", processName, infoFile,
  1506. "$<CONFIG>", "$<COMMAND_CONFIG:$<CONFIG>>" }));
  1507. } else if ((this->MultiConfig && this->GlobalGen->IsXcode()) ||
  1508. this->CrossConfig) {
  1509. auto const& configs =
  1510. processName == "cmake_autorcc" ? this->ConfigsList : autogenConfigs;
  1511. for (std::string const& config : configs) {
  1512. commandLines.push_back(
  1513. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1514. processName, infoFile, config }));
  1515. }
  1516. } else {
  1517. std::string autoInfoFileConfig;
  1518. if (this->MultiConfig) {
  1519. autoInfoFileConfig = "$<CONFIG>";
  1520. } else {
  1521. autoInfoFileConfig = autogenConfigs[0];
  1522. }
  1523. commandLines.push_back(
  1524. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", processName,
  1525. infoFile, autoInfoFileConfig }));
  1526. }
  1527. }
  1528. bool cmQtAutoGenInitializer::InitRccTargets()
  1529. {
  1530. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1531. // Register info file as generated by CMake
  1532. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1533. // Register file at target
  1534. {
  1535. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1536. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1537. }
  1538. std::vector<std::string> ccOutput{ qrc.OutputFile };
  1539. // Add the .qrc and info file to the custom command dependencies
  1540. std::vector<std::string> ccDepends{ qrc.QrcFile, qrc.InfoFile };
  1541. cmCustomCommandLines commandLines;
  1542. AddCMakeProcessToCommandLines(qrc.InfoFile, "cmake_autorcc", commandLines);
  1543. std::string const ccComment =
  1544. cmStrCat("Automatic RCC for ",
  1545. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1546. auto cc = cm::make_unique<cmCustomCommand>();
  1547. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1548. cc->SetCommandLines(commandLines);
  1549. cc->SetComment(ccComment.c_str());
  1550. cc->SetStdPipesUTF8(true);
  1551. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1552. // Create custom rcc target
  1553. std::string ccName;
  1554. {
  1555. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1556. if (!qrc.Unique) {
  1557. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1558. }
  1559. cc->SetByproducts(ccOutput);
  1560. cc->SetDepends(ccDepends);
  1561. cc->SetEscapeOldStyle(false);
  1562. cmTarget* autoRccTarget =
  1563. this->LocalGen->AddUtilityCommand(ccName, true, std::move(cc));
  1564. // Create autogen generator target
  1565. this->LocalGen->AddGeneratorTarget(
  1566. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1567. // Set FOLDER property in autogen target
  1568. if (!this->TargetsFolder.empty()) {
  1569. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1570. }
  1571. if (!this->Rcc.ExecutableTargetName.empty()) {
  1572. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1573. this->Makefile);
  1574. }
  1575. }
  1576. // Add autogen target to the origin target dependencies
  1577. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1578. // Add autogen target to the global autogen target dependencies
  1579. if (this->Rcc.GlobalTarget) {
  1580. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1581. }
  1582. } else {
  1583. // Create custom rcc command
  1584. {
  1585. // Add the resource files to the dependencies
  1586. if (this->MultiConfig && this->UseBetterGraph) {
  1587. for (auto const& config : this->ConfigsList) {
  1588. // Add resource file to the custom command dependencies
  1589. auto resourceFilesWithConfig = cmStrCat(
  1590. "$<$<CONFIG:", config,
  1591. ">:", cmList{ qrc.Resources.Config.at(config) }.to_string(),
  1592. ">");
  1593. ccDepends.emplace_back(std::move(resourceFilesWithConfig));
  1594. }
  1595. } else {
  1596. for (std::string const& fileName : qrc.Resources.Default) {
  1597. // Add resource file to the custom command dependencies
  1598. ccDepends.push_back(fileName);
  1599. }
  1600. }
  1601. if (!this->Rcc.ExecutableTargetName.empty()) {
  1602. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1603. }
  1604. AddAutogenExecutableToDependencies(this->Rcc, ccDepends);
  1605. cc->SetOutputs(ccOutput);
  1606. cc->SetDepends(ccDepends);
  1607. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1608. }
  1609. // Reconfigure when .qrc file changes
  1610. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1611. }
  1612. }
  1613. return true;
  1614. }
  1615. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1616. {
  1617. // Create info directory on demand
  1618. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1619. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1620. Quoted(this->Dir.Info)));
  1621. return false;
  1622. }
  1623. // Generate autogen target info file
  1624. if (this->MocOrUicEnabled()) {
  1625. // Write autogen target info files
  1626. if (!this->SetupWriteAutogenInfo()) {
  1627. return false;
  1628. }
  1629. }
  1630. // Write AUTORCC info files
  1631. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1632. }
  1633. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1634. {
  1635. // Utility lambdas
  1636. auto MfDef = [this](std::string const& key) {
  1637. return this->Makefile->GetSafeDefinition(key);
  1638. };
  1639. // Filtered headers and sources
  1640. std::set<std::string> moc_skip;
  1641. std::set<std::string> uic_skip;
  1642. std::vector<MUFile const*> headers;
  1643. std::vector<MUFile const*> sources;
  1644. // Filter headers
  1645. {
  1646. headers.reserve(this->AutogenTarget.Headers.size());
  1647. for (auto const& pair : this->AutogenTarget.Headers) {
  1648. MUFile const* const muf = pair.second.get();
  1649. if (muf->SkipMoc) {
  1650. moc_skip.insert(muf->FullPath);
  1651. }
  1652. if (muf->SkipUic) {
  1653. uic_skip.insert(muf->FullPath);
  1654. }
  1655. if (muf->Generated && !this->CMP0071Accept) {
  1656. continue;
  1657. }
  1658. if (muf->MocIt || muf->UicIt) {
  1659. headers.emplace_back(muf);
  1660. }
  1661. }
  1662. std::sort(headers.begin(), headers.end(),
  1663. [](MUFile const* a, MUFile const* b) {
  1664. return (a->FullPath < b->FullPath);
  1665. });
  1666. }
  1667. // Filter sources
  1668. {
  1669. sources.reserve(this->AutogenTarget.Sources.size());
  1670. for (auto const& pair : this->AutogenTarget.Sources) {
  1671. MUFile const* const muf = pair.second.get();
  1672. if (muf->Generated && !this->CMP0071Accept) {
  1673. continue;
  1674. }
  1675. if (muf->SkipMoc) {
  1676. moc_skip.insert(muf->FullPath);
  1677. }
  1678. if (muf->SkipUic) {
  1679. uic_skip.insert(muf->FullPath);
  1680. }
  1681. if (muf->MocIt || muf->UicIt) {
  1682. sources.emplace_back(muf);
  1683. }
  1684. }
  1685. std::sort(sources.begin(), sources.end(),
  1686. [](MUFile const* a, MUFile const* b) {
  1687. return (a->FullPath < b->FullPath);
  1688. });
  1689. }
  1690. // Info writer
  1691. InfoWriter info;
  1692. // General
  1693. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1694. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1695. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1696. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1697. #ifdef _WIN32
  1698. info.SetUInt("AUTOGEN_COMMAND_LINE_LENGTH_MAX",
  1699. this->AutogenTarget.MaxCommandLineLength);
  1700. #endif
  1701. info.SetUInt("VERBOSITY", this->Verbosity);
  1702. // Directories
  1703. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1704. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1705. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1706. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1707. info.Set("BUILD_DIR", this->Dir.Build);
  1708. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1709. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1710. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1711. info.SetConfig("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1712. info.SetConfig("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1713. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1714. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1715. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1716. info.SetConfig("DEP_FILE", this->AutogenTarget.DepFile);
  1717. info.SetConfig("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1718. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1719. info.SetArray("HEADER_EXTENSIONS",
  1720. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1721. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1722. Json::Value value;
  1723. if (!configs.empty()) {
  1724. value = Json::arrayValue;
  1725. for (size_t ci : configs) {
  1726. value.append(this->ConfigsList[ci]);
  1727. }
  1728. }
  1729. return value;
  1730. };
  1731. info.SetArrayArray("HEADERS", headers,
  1732. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1733. jval.resize(4u);
  1734. jval[0u] = muf->FullPath;
  1735. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1736. muf->UicIt ? 'U' : 'u');
  1737. jval[2u] = this->GetMocBuildPath(*muf);
  1738. jval[3u] = cfgArray(muf->Configs);
  1739. });
  1740. info.SetArrayArray(
  1741. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1742. jval.resize(3u);
  1743. jval[0u] = muf->FullPath;
  1744. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1745. jval[2u] = cfgArray(muf->Configs);
  1746. });
  1747. // Write moc settings
  1748. if (this->Moc.Enabled) {
  1749. info.SetArray("MOC_SKIP", moc_skip);
  1750. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1751. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1752. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1753. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1754. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1755. EvaluatedTargetPropertyEntries InterfaceAutoMocMacroNamesEntries;
  1756. if (this->MultiConfig) {
  1757. for (auto const& cfg : this->ConfigsList) {
  1758. if (!cfg.empty()) {
  1759. cmGeneratorExpressionDAGChecker dagChecker(
  1760. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr, nullptr,
  1761. this->LocalGen, cfg);
  1762. AddInterfaceEntries(this->GenTarget, cfg,
  1763. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX",
  1764. &dagChecker, InterfaceAutoMocMacroNamesEntries,
  1765. IncludeRuntimeInterface::Yes);
  1766. }
  1767. }
  1768. } else {
  1769. cmGeneratorExpressionDAGChecker dagChecker(
  1770. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr, nullptr,
  1771. this->LocalGen, this->ConfigDefault);
  1772. AddInterfaceEntries(this->GenTarget, this->ConfigDefault,
  1773. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX", &dagChecker,
  1774. InterfaceAutoMocMacroNamesEntries,
  1775. IncludeRuntimeInterface::Yes);
  1776. }
  1777. for (auto const& entry : InterfaceAutoMocMacroNamesEntries.Entries) {
  1778. this->Moc.MacroNames.insert(this->Moc.MacroNames.end(),
  1779. entry.Values.begin(), entry.Values.end());
  1780. }
  1781. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  1782. this->Moc.MacroNames.end());
  1783. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1784. info.SetArrayArray(
  1785. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1786. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1787. jval.resize(2u);
  1788. jval[0u] = pair.first;
  1789. jval[1u] = pair.second;
  1790. });
  1791. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1792. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1793. cmStandardLevelResolver const resolver{ this->Makefile };
  1794. auto const CompileOptionFlag =
  1795. resolver.GetCompileOptionDef(this->GenTarget, "CXX", "");
  1796. auto const CompileOptionValue =
  1797. this->GenTarget->Makefile->GetSafeDefinition(CompileOptionFlag);
  1798. if (!CompileOptionValue.empty()) {
  1799. if (this->Moc.PredefsCmd.size() >= 3) {
  1800. this->Moc.PredefsCmd.insert(this->Moc.PredefsCmd.begin() + 1,
  1801. CompileOptionValue);
  1802. }
  1803. }
  1804. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1805. }
  1806. // Write uic settings
  1807. if (this->Uic.Enabled) {
  1808. // Add skipped .ui files
  1809. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1810. info.SetArray("UIC_SKIP", uic_skip);
  1811. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1812. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1813. jval.resize(2u);
  1814. jval[0u] = uiFile.first;
  1815. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1816. });
  1817. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1818. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1819. }
  1820. info.Save(this->AutogenTarget.InfoFile);
  1821. return true;
  1822. }
  1823. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1824. {
  1825. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1826. // Utility lambdas
  1827. auto MfDef = [this](std::string const& key) {
  1828. return this->Makefile->GetSafeDefinition(key);
  1829. };
  1830. InfoWriter info;
  1831. // General
  1832. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1833. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1834. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1835. info.SetUInt("VERBOSITY", this->Verbosity);
  1836. info.Set("GENERATOR", this->GlobalGen->GetName());
  1837. // Files
  1838. info.Set("LOCK_FILE", qrc.LockFile);
  1839. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1840. // Directories
  1841. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1842. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1843. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1844. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1845. info.Set("BUILD_DIR", this->Dir.Build);
  1846. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1847. // rcc executable
  1848. info.SetConfig("RCC_EXECUTABLE", this->Rcc.Executable);
  1849. info.SetConfigArray(
  1850. "RCC_LIST_OPTIONS",
  1851. generateListOptions(this->Rcc.ExecutableFeatures, this->MultiConfig));
  1852. // qrc file
  1853. info.Set("SOURCE", qrc.QrcFile);
  1854. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1855. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1856. info.SetArray("OPTIONS", qrc.Options);
  1857. info.SetConfigArray("INPUTS", qrc.Resources);
  1858. info.Save(qrc.InfoFile);
  1859. }
  1860. return true;
  1861. }
  1862. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1863. std::string const& filename)
  1864. {
  1865. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1866. gFile->MarkAsGenerated();
  1867. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1868. gFile->SetProperty("SKIP_LINTING", "ON");
  1869. gFile->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1870. return gFile;
  1871. }
  1872. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1873. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1874. {
  1875. // Register source at makefile
  1876. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1877. // Add source file to target
  1878. this->GenTarget->AddSource(filename, prepend);
  1879. // Add source file to source group
  1880. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1881. return gFile;
  1882. }
  1883. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1884. GenVarsT const& genVars,
  1885. bool prepend)
  1886. {
  1887. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1888. // when the Xcode generator supports per-config sources.
  1889. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1890. cmSourceFile* sf =
  1891. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1892. handleSkipPch(sf);
  1893. return;
  1894. }
  1895. for (auto const& cfg : this->ConfigsList) {
  1896. std::string const& filenameCfg = filename.Config.at(cfg);
  1897. // Register source at makefile
  1898. cmSourceFile* sf = this->RegisterGeneratedSource(filenameCfg);
  1899. handleSkipPch(sf);
  1900. // Add source file to target for this configuration.
  1901. this->GenTarget->AddSource(
  1902. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1903. // Add source file to source group
  1904. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1905. }
  1906. }
  1907. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1908. cm::string_view genNameUpper)
  1909. {
  1910. cmSourceGroup* sourceGroup = nullptr;
  1911. // Acquire source group
  1912. {
  1913. std::string property;
  1914. std::string groupName;
  1915. {
  1916. // Prefer generator specific source group name
  1917. std::initializer_list<std::string> const props{
  1918. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1919. };
  1920. for (std::string const& prop : props) {
  1921. cmValue propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1922. if (cmNonempty(propName)) {
  1923. groupName = *propName;
  1924. property = prop;
  1925. break;
  1926. }
  1927. }
  1928. }
  1929. // Generate a source group on demand
  1930. if (!groupName.empty()) {
  1931. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1932. if (!sourceGroup) {
  1933. cmSystemTools::Error(
  1934. cmStrCat(genNameUpper, " error in ", property,
  1935. ": Could not find or create the source group ",
  1936. cmQtAutoGen::Quoted(groupName)));
  1937. }
  1938. }
  1939. }
  1940. if (sourceGroup) {
  1941. sourceGroup->AddGroupFile(fileName);
  1942. }
  1943. }
  1944. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1945. {
  1946. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName);
  1947. }
  1948. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1949. cm::string_view prefix,
  1950. cm::string_view suffix)
  1951. {
  1952. configString.Default = cmStrCat(prefix, suffix);
  1953. if (this->MultiConfig) {
  1954. for (auto const& cfg : this->ConfigsList) {
  1955. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1956. }
  1957. }
  1958. }
  1959. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1960. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1961. cm::string_view const suffix)
  1962. {
  1963. this->ConfigFileNames(configString, prefix, suffix);
  1964. if (this->MultiConfig) {
  1965. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1966. } else {
  1967. genex = configString.Default;
  1968. }
  1969. }
  1970. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1971. {
  1972. this->AddCleanFile(configString.Default);
  1973. if (this->MultiConfig) {
  1974. for (auto const& pair : configString.Config) {
  1975. this->AddCleanFile(pair.second);
  1976. }
  1977. }
  1978. }
  1979. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  1980. {
  1981. cmQtAutoGen::IntegerVersion result;
  1982. static std::string const prelude = "moc ";
  1983. size_t const pos = str.find(prelude);
  1984. if (pos == std::string::npos) {
  1985. return result;
  1986. }
  1987. str.erase(0, prelude.size() + pos);
  1988. std::istringstream iss(str);
  1989. std::string major;
  1990. std::string minor;
  1991. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  1992. return result;
  1993. }
  1994. result.Major = static_cast<unsigned int>(std::stoi(major));
  1995. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  1996. return result;
  1997. }
  1998. static cmQtAutoGen::IntegerVersion GetMocVersion(
  1999. std::string const& mocExecutablePath)
  2000. {
  2001. std::string capturedStdOut;
  2002. int exitCode;
  2003. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  2004. &capturedStdOut, nullptr, &exitCode,
  2005. nullptr, cmSystemTools::OUTPUT_NONE)) {
  2006. return {};
  2007. }
  2008. if (exitCode != 0) {
  2009. return {};
  2010. }
  2011. return parseMocVersion(capturedStdOut);
  2012. }
  2013. static std::string FindMocExecutableFromMocTarget(cmMakefile const* makefile,
  2014. unsigned int qtMajorVersion)
  2015. {
  2016. std::string result;
  2017. std::string const mocTargetName = cmStrCat("Qt", qtMajorVersion, "::moc");
  2018. cmTarget const* mocTarget = makefile->FindTargetToUse(mocTargetName);
  2019. if (mocTarget) {
  2020. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  2021. }
  2022. return result;
  2023. }
  2024. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  2025. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  2026. std::string mocExecutable)
  2027. {
  2028. // Converts a char ptr to an unsigned int value
  2029. auto toUInt = [](char const* const input) -> unsigned int {
  2030. unsigned long tmp = 0;
  2031. if (input && cmStrToULong(input, &tmp)) {
  2032. return static_cast<unsigned int>(tmp);
  2033. }
  2034. return 0u;
  2035. };
  2036. auto toUInt2 = [](cmValue input) -> unsigned int {
  2037. unsigned long tmp = 0;
  2038. if (input && cmStrToULong(*input, &tmp)) {
  2039. return static_cast<unsigned int>(tmp);
  2040. }
  2041. return 0u;
  2042. };
  2043. // Initialize return value to a default
  2044. std::pair<IntegerVersion, unsigned int> res(
  2045. IntegerVersion(),
  2046. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  2047. "")));
  2048. // Acquire known Qt versions
  2049. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  2050. {
  2051. // Qt version variable prefixes
  2052. static std::initializer_list<
  2053. std::pair<cm::string_view, cm::string_view>> const keys{
  2054. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  2055. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  2056. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  2057. };
  2058. knownQtVersions.reserve(keys.size() * 2);
  2059. // Adds a version to the result (nullptr safe)
  2060. auto addVersion = [&knownQtVersions, &toUInt2](cmValue major,
  2061. cmValue minor) {
  2062. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  2063. if (ver.Major != 0) {
  2064. knownQtVersions.emplace_back(ver);
  2065. }
  2066. };
  2067. // Read versions from variables
  2068. for (auto const& keyPair : keys) {
  2069. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  2070. target->Makefile->GetDefinition(std::string(keyPair.second)));
  2071. }
  2072. // Read versions from directory properties
  2073. for (auto const& keyPair : keys) {
  2074. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  2075. target->Makefile->GetProperty(std::string(keyPair.second)));
  2076. }
  2077. }
  2078. // Evaluate known Qt versions
  2079. if (!knownQtVersions.empty()) {
  2080. if (res.second == 0) {
  2081. // No specific version was requested by the target:
  2082. // Use highest known Qt version.
  2083. res.first = knownQtVersions.at(0);
  2084. } else {
  2085. // Pick a version from the known versions:
  2086. for (auto const& it : knownQtVersions) {
  2087. if (it.Major == res.second) {
  2088. res.first = it;
  2089. break;
  2090. }
  2091. }
  2092. }
  2093. }
  2094. if (res.first.Major == 0) {
  2095. // We could not get the version number from variables or directory
  2096. // properties. This might happen if the find_package call for Qt is wrapped
  2097. // in a function. Try to find the moc executable path from the available
  2098. // targets and call "moc --version" to get the Qt version.
  2099. if (mocExecutable.empty()) {
  2100. mocExecutable =
  2101. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  2102. }
  2103. if (!mocExecutable.empty()) {
  2104. res.first = GetMocVersion(mocExecutable);
  2105. }
  2106. }
  2107. return res;
  2108. }
  2109. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  2110. {
  2111. std::string res;
  2112. if (!muf.MocIt) {
  2113. return res;
  2114. }
  2115. std::string basePath =
  2116. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  2117. FileNameWithoutLastExtension(muf.FullPath));
  2118. res = cmStrCat(basePath, ".cpp");
  2119. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2120. return res;
  2121. }
  2122. // File name already emitted.
  2123. // Try appending the header suffix to the base path.
  2124. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  2125. res = cmStrCat(basePath, ".cpp");
  2126. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2127. return res;
  2128. }
  2129. // File name with header extension already emitted.
  2130. // Try adding a number to the base path.
  2131. constexpr std::size_t number_begin = 2;
  2132. constexpr std::size_t number_end = 256;
  2133. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  2134. res = cmStrCat(basePath, '_', ii, ".cpp");
  2135. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2136. return res;
  2137. }
  2138. }
  2139. // Output file name conflict (unlikely, but still...)
  2140. cmSystemTools::Error(
  2141. cmStrCat("moc output file name conflict for ", muf.FullPath));
  2142. return res;
  2143. }
  2144. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  2145. std::string const& executable,
  2146. bool ignoreMissingTarget) const
  2147. {
  2148. auto print_err = [this, &genVars](std::string const& err) {
  2149. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  2150. this->GenTarget->GetName(), ": ", err));
  2151. };
  2152. // Custom executable
  2153. {
  2154. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  2155. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  2156. if (!val.empty()) {
  2157. // Evaluate generator expression
  2158. {
  2159. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2160. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  2161. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  2162. if (this->MultiConfig && this->UseBetterGraph) {
  2163. for (auto const& config : this->ConfigsList) {
  2164. genVars.Executable.Config[config] =
  2165. cge->Evaluate(this->LocalGen, config);
  2166. }
  2167. } else {
  2168. genVars.Executable.Default = cge->Evaluate(this->LocalGen, "");
  2169. }
  2170. }
  2171. if (genVars.Executable.Default.empty() &&
  2172. genVars.Executable.Config.empty() && !ignoreMissingTarget) {
  2173. print_err(prop + " evaluates to an empty value");
  2174. return false;
  2175. }
  2176. // Create empty compiler features.
  2177. if (this->MultiConfig && this->UseBetterGraph) {
  2178. for (auto const& config : this->ConfigsList) {
  2179. genVars.ExecutableFeatures.Config[config] =
  2180. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2181. }
  2182. } else {
  2183. genVars.ExecutableFeatures.Default =
  2184. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2185. }
  2186. return true;
  2187. }
  2188. }
  2189. // Find executable target
  2190. {
  2191. // Find executable target name
  2192. cm::string_view prefix;
  2193. if (this->QtVersion.Major == 4) {
  2194. prefix = "Qt4::";
  2195. } else if (this->QtVersion.Major == 5) {
  2196. prefix = "Qt5::";
  2197. } else if (this->QtVersion.Major == 6) {
  2198. prefix = "Qt6::";
  2199. }
  2200. std::string const targetName = cmStrCat(prefix, executable);
  2201. // Find target
  2202. cmGeneratorTarget* genTarget =
  2203. this->LocalGen->FindGeneratorTargetToUse(targetName);
  2204. if (genTarget) {
  2205. genVars.ExecutableTargetName = targetName;
  2206. genVars.ExecutableTarget = genTarget;
  2207. if (genTarget->IsImported()) {
  2208. if (this->MultiConfig && this->UseBetterGraph) {
  2209. for (auto const& config : this->ConfigsList) {
  2210. genVars.Executable.Config[config] =
  2211. genTarget->ImportedGetLocation(config);
  2212. }
  2213. } else {
  2214. genVars.Executable.Default =
  2215. genTarget->ImportedGetLocation(this->ConfigDefault);
  2216. }
  2217. } else {
  2218. if (this->MultiConfig && this->UseBetterGraph) {
  2219. for (auto const& config : this->ConfigsList) {
  2220. genVars.Executable.Config[config] = genTarget->GetLocation(config);
  2221. }
  2222. } else {
  2223. genVars.Executable.Default =
  2224. genTarget->GetLocation(this->ConfigDefault);
  2225. }
  2226. }
  2227. } else {
  2228. if (ignoreMissingTarget) {
  2229. // Create empty compiler features.
  2230. if (this->MultiConfig && this->UseBetterGraph) {
  2231. for (auto const& config : this->ConfigsList) {
  2232. genVars.ExecutableFeatures.Config[config] =
  2233. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2234. }
  2235. } else {
  2236. genVars.ExecutableFeatures.Default =
  2237. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2238. }
  2239. return true;
  2240. }
  2241. print_err(cmStrCat("Could not find ", executable, " executable target ",
  2242. targetName));
  2243. return false;
  2244. }
  2245. }
  2246. // Get executable features
  2247. {
  2248. std::string err;
  2249. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  2250. executable, genVars.Executable, err, this->MultiConfig,
  2251. this->UseBetterGraph);
  2252. if (this->MultiConfig && this->UseBetterGraph) {
  2253. for (auto const& config : this->ConfigsList) {
  2254. if (!genVars.ExecutableFeatures.Config[config]) {
  2255. if (!genVars.ExecutableFeatures.Config[config]) {
  2256. print_err(err);
  2257. return false;
  2258. }
  2259. }
  2260. }
  2261. } else {
  2262. if (!genVars.ExecutableFeatures.Default) {
  2263. print_err(err);
  2264. return false;
  2265. }
  2266. }
  2267. }
  2268. return true;
  2269. }
  2270. void cmQtAutoGenInitializer::handleSkipPch(cmSourceFile* sf)
  2271. {
  2272. bool skipPch = true;
  2273. for (auto const& pair : this->AutogenTarget.Sources) {
  2274. if (!pair.first->GetIsGenerated() &&
  2275. !pair.first->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2276. skipPch = false;
  2277. }
  2278. }
  2279. if (skipPch) {
  2280. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2281. }
  2282. }