cmQtAutoGenInitializer.cxx 85 KB

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