cmQtAutoGenInitializer.cxx 88 KB

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