cmGlobalGenerator.cxx 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573
  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 "cmGlobalGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <chrono>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <functional>
  11. #include <initializer_list>
  12. #include <iomanip>
  13. #include <iterator>
  14. #include <sstream>
  15. #include <utility>
  16. #include <cm/memory>
  17. #include <cm/optional>
  18. #include <cmext/algorithm>
  19. #include <cmext/string_view>
  20. #include "cmsys/Directory.hxx"
  21. #include "cmsys/FStream.hxx"
  22. #include "cmsys/RegularExpression.hxx"
  23. #if defined(_WIN32) && !defined(__CYGWIN__)
  24. # include <windows.h>
  25. #endif
  26. #include "cmAlgorithms.h"
  27. #include "cmCPackPropertiesGenerator.h"
  28. #include "cmComputeTargetDepends.h"
  29. #include "cmCustomCommand.h"
  30. #include "cmCustomCommandLines.h"
  31. #include "cmDuration.h"
  32. #include "cmExportBuildFileGenerator.h"
  33. #include "cmExternalMakefileProjectGenerator.h"
  34. #include "cmGeneratedFileStream.h"
  35. #include "cmGeneratorExpression.h"
  36. #include "cmGeneratorTarget.h"
  37. #include "cmInstallGenerator.h"
  38. #include "cmInstallRuntimeDependencySet.h"
  39. #include "cmLinkLineComputer.h"
  40. #include "cmList.h"
  41. #include "cmLocalGenerator.h"
  42. #include "cmMSVC60LinkLineComputer.h"
  43. #include "cmMakefile.h"
  44. #include "cmMessageType.h"
  45. #include "cmPolicies.h"
  46. #include "cmRange.h"
  47. #include "cmSourceFile.h"
  48. #include "cmState.h"
  49. #include "cmStateDirectory.h"
  50. #include "cmStateTypes.h"
  51. #include "cmStringAlgorithms.h"
  52. #include "cmSystemTools.h"
  53. #include "cmValue.h"
  54. #include "cmVersion.h"
  55. #include "cmWorkingDirectory.h"
  56. #include "cmake.h"
  57. #if !defined(CMAKE_BOOTSTRAP)
  58. # include <cm3p/json/value.h>
  59. # include <cm3p/json/writer.h>
  60. # include "cmCryptoHash.h"
  61. # include "cmQtAutoGenGlobalInitializer.h"
  62. #endif
  63. const std::string kCMAKE_PLATFORM_INFO_INITIALIZED =
  64. "CMAKE_PLATFORM_INFO_INITIALIZED";
  65. class cmInstalledFile;
  66. bool cmTarget::StrictTargetComparison::operator()(cmTarget const* t1,
  67. cmTarget const* t2) const
  68. {
  69. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  70. if (nameResult == 0) {
  71. return strcmp(t1->GetMakefile()->GetCurrentBinaryDirectory().c_str(),
  72. t2->GetMakefile()->GetCurrentBinaryDirectory().c_str()) < 0;
  73. }
  74. return nameResult < 0;
  75. }
  76. cmGlobalGenerator::cmGlobalGenerator(cmake* cm)
  77. : CMakeInstance(cm)
  78. {
  79. // By default the .SYMBOLIC dependency is not needed on symbolic rules.
  80. this->NeedSymbolicMark = false;
  81. // by default use the native paths
  82. this->ForceUnixPaths = false;
  83. // By default do not try to support color.
  84. this->ToolSupportsColor = false;
  85. // By default do not use link scripts.
  86. this->UseLinkScript = false;
  87. // Whether an install target is needed.
  88. this->InstallTargetEnabled = false;
  89. // how long to let try compiles run
  90. this->TryCompileTimeout = cmDuration::zero();
  91. this->CurrentConfigureMakefile = nullptr;
  92. this->TryCompileOuterMakefile = nullptr;
  93. this->ConfigureDoneCMP0026AndCMP0024 = false;
  94. this->FirstTimeProgress = 0.0f;
  95. cm->GetState()->SetIsGeneratorMultiConfig(false);
  96. cm->GetState()->SetMinGWMake(false);
  97. cm->GetState()->SetMSYSShell(false);
  98. cm->GetState()->SetNMake(false);
  99. cm->GetState()->SetWatcomWMake(false);
  100. cm->GetState()->SetWindowsShell(false);
  101. cm->GetState()->SetWindowsVSIDE(false);
  102. }
  103. cmGlobalGenerator::~cmGlobalGenerator()
  104. {
  105. this->ClearGeneratorMembers();
  106. }
  107. #if !defined(CMAKE_BOOTSTRAP)
  108. Json::Value cmGlobalGenerator::GetJson() const
  109. {
  110. Json::Value generator = Json::objectValue;
  111. generator["name"] = this->GetName();
  112. generator["multiConfig"] = this->IsMultiConfig();
  113. return generator;
  114. }
  115. #endif
  116. bool cmGlobalGenerator::SetGeneratorInstance(std::string const& i,
  117. cmMakefile* mf)
  118. {
  119. if (i.empty()) {
  120. return true;
  121. }
  122. std::ostringstream e;
  123. /* clang-format off */
  124. e <<
  125. "Generator\n"
  126. " " << this->GetName() << "\n"
  127. "does not support instance specification, but instance\n"
  128. " " << i << "\n"
  129. "was specified.";
  130. /* clang-format on */
  131. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  132. return false;
  133. }
  134. bool cmGlobalGenerator::SetGeneratorPlatform(std::string const& p,
  135. cmMakefile* mf)
  136. {
  137. if (p.empty()) {
  138. return true;
  139. }
  140. std::ostringstream e;
  141. /* clang-format off */
  142. e <<
  143. "Generator\n"
  144. " " << this->GetName() << "\n"
  145. "does not support platform specification, but platform\n"
  146. " " << p << "\n"
  147. "was specified.";
  148. /* clang-format on */
  149. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  150. return false;
  151. }
  152. bool cmGlobalGenerator::SetGeneratorToolset(std::string const& ts, bool,
  153. cmMakefile* mf)
  154. {
  155. if (ts.empty()) {
  156. return true;
  157. }
  158. std::ostringstream e;
  159. /* clang-format off */
  160. e <<
  161. "Generator\n"
  162. " " << this->GetName() << "\n"
  163. "does not support toolset specification, but toolset\n"
  164. " " << ts << "\n"
  165. "was specified.";
  166. /* clang-format on */
  167. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  168. return false;
  169. }
  170. std::string cmGlobalGenerator::SelectMakeProgram(
  171. const std::string& inMakeProgram, const std::string& makeDefault) const
  172. {
  173. std::string makeProgram = inMakeProgram;
  174. if (cmIsOff(makeProgram)) {
  175. cmValue makeProgramCSTR =
  176. this->CMakeInstance->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
  177. if (cmIsOff(makeProgramCSTR)) {
  178. makeProgram = makeDefault;
  179. } else {
  180. makeProgram = *makeProgramCSTR;
  181. }
  182. if (cmIsOff(makeProgram) && !makeProgram.empty()) {
  183. makeProgram = "CMAKE_MAKE_PROGRAM-NOTFOUND";
  184. }
  185. }
  186. return makeProgram;
  187. }
  188. void cmGlobalGenerator::ResolveLanguageCompiler(const std::string& lang,
  189. cmMakefile* mf,
  190. bool optional) const
  191. {
  192. std::string langComp = cmStrCat("CMAKE_", lang, "_COMPILER");
  193. if (!mf->GetDefinition(langComp)) {
  194. if (!optional) {
  195. cmSystemTools::Error(langComp + " not set, after EnableLanguage");
  196. }
  197. return;
  198. }
  199. std::string const& name = mf->GetRequiredDefinition(langComp);
  200. std::string path;
  201. if (!cmSystemTools::FileIsFullPath(name)) {
  202. path = cmSystemTools::FindProgram(name);
  203. } else {
  204. path = name;
  205. }
  206. if (!optional && (path.empty() || !cmSystemTools::FileExists(path))) {
  207. return;
  208. }
  209. cmValue cname =
  210. this->GetCMakeInstance()->GetState()->GetInitializedCacheValue(langComp);
  211. // Split compiler from arguments
  212. cmList cnameArgList;
  213. if (cname && !cname->empty()) {
  214. cnameArgList.assign(*cname);
  215. cname = cmValue(cnameArgList.front());
  216. }
  217. std::string changeVars;
  218. if (cname && !optional) {
  219. std::string cnameString;
  220. if (!cmSystemTools::FileIsFullPath(*cname)) {
  221. cnameString = cmSystemTools::FindProgram(*cname);
  222. } else {
  223. cnameString = *cname;
  224. }
  225. std::string pathString = path;
  226. // get rid of potentially multiple slashes:
  227. cmSystemTools::ConvertToUnixSlashes(cnameString);
  228. cmSystemTools::ConvertToUnixSlashes(pathString);
  229. if (cnameString != pathString) {
  230. cmValue cvars = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  231. "__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  232. if (cvars) {
  233. changeVars += *cvars;
  234. changeVars += ";";
  235. }
  236. changeVars += langComp;
  237. changeVars += ";";
  238. changeVars += *cname;
  239. this->GetCMakeInstance()->GetState()->SetGlobalProperty(
  240. "__CMAKE_DELETE_CACHE_CHANGE_VARS_", changeVars.c_str());
  241. }
  242. }
  243. }
  244. void cmGlobalGenerator::AddBuildExportSet(cmExportBuildFileGenerator* gen)
  245. {
  246. this->BuildExportSets[gen->GetMainExportFileName()] = gen;
  247. }
  248. void cmGlobalGenerator::AddBuildExportExportSet(
  249. cmExportBuildFileGenerator* gen)
  250. {
  251. this->BuildExportExportSets[gen->GetMainExportFileName()] = gen;
  252. this->AddBuildExportSet(gen);
  253. }
  254. bool cmGlobalGenerator::GenerateImportFile(const std::string& file)
  255. {
  256. auto const it = this->BuildExportSets.find(file);
  257. if (it != this->BuildExportSets.end()) {
  258. bool result = it->second->GenerateImportFile();
  259. if (!this->ConfigureDoneCMP0026AndCMP0024) {
  260. for (const auto& m : this->Makefiles) {
  261. m->RemoveExportBuildFileGeneratorCMP0024(it->second);
  262. }
  263. }
  264. this->BuildExportSets.erase(it);
  265. return result;
  266. }
  267. return false;
  268. }
  269. void cmGlobalGenerator::ForceLinkerLanguages()
  270. {
  271. }
  272. bool cmGlobalGenerator::CheckTargetsForMissingSources() const
  273. {
  274. bool failed = false;
  275. for (const auto& localGen : this->LocalGenerators) {
  276. for (const auto& target : localGen->GetGeneratorTargets()) {
  277. if (!target->CanCompileSources() ||
  278. cmIsOn(target->GetProperty("ghs_integrity_app"))) {
  279. continue;
  280. }
  281. if (target->GetAllConfigSources().empty()) {
  282. std::ostringstream e;
  283. e << "No SOURCES given to target: " << target->GetName();
  284. this->GetCMakeInstance()->IssueMessage(
  285. MessageType::FATAL_ERROR, e.str(), target->GetBacktrace());
  286. failed = true;
  287. }
  288. }
  289. }
  290. return failed;
  291. }
  292. void cmGlobalGenerator::CheckTargetLinkLibraries() const
  293. {
  294. for (const auto& generator : this->LocalGenerators) {
  295. for (const auto& gt : generator->GetGeneratorTargets()) {
  296. gt->CheckLinkLibraries();
  297. }
  298. for (const auto& gt : generator->GetOwnedImportedGeneratorTargets()) {
  299. gt->CheckLinkLibraries();
  300. }
  301. }
  302. }
  303. bool cmGlobalGenerator::CheckTargetsForType() const
  304. {
  305. if (!this->GetLanguageEnabled("Swift")) {
  306. return false;
  307. }
  308. bool failed = false;
  309. for (const auto& generator : this->LocalGenerators) {
  310. for (const auto& target : generator->GetGeneratorTargets()) {
  311. std::string systemName =
  312. target->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  313. if (systemName.find("Windows") == std::string::npos) {
  314. continue;
  315. }
  316. if (target->GetType() == cmStateEnums::EXECUTABLE) {
  317. std::vector<std::string> const& configs =
  318. target->Makefile->GetGeneratorConfigs(
  319. cmMakefile::IncludeEmptyConfig);
  320. for (std::string const& config : configs) {
  321. if (target->IsWin32Executable(config) &&
  322. target->GetLinkerLanguage(config) == "Swift") {
  323. this->GetCMakeInstance()->IssueMessage(
  324. MessageType::FATAL_ERROR,
  325. "WIN32_EXECUTABLE property is not supported on Swift "
  326. "executables",
  327. target->GetBacktrace());
  328. failed = true;
  329. }
  330. }
  331. }
  332. }
  333. }
  334. return failed;
  335. }
  336. bool cmGlobalGenerator::CheckTargetsForPchCompilePdb() const
  337. {
  338. if (!this->GetLanguageEnabled("C") && !this->GetLanguageEnabled("CXX")) {
  339. return false;
  340. }
  341. bool failed = false;
  342. for (const auto& generator : this->LocalGenerators) {
  343. for (const auto& target : generator->GetGeneratorTargets()) {
  344. if (!target->CanCompileSources() ||
  345. cmIsOn(target->GetProperty("ghs_integrity_app"))) {
  346. continue;
  347. }
  348. std::string const& reuseFrom =
  349. target->GetSafeProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  350. std::string const& compilePdb =
  351. target->GetSafeProperty("COMPILE_PDB_NAME");
  352. if (!reuseFrom.empty() && reuseFrom != compilePdb) {
  353. const std::string e = cmStrCat(
  354. "PRECOMPILE_HEADERS_REUSE_FROM property is set on target (\"",
  355. target->GetName(),
  356. "\"). Reusable precompile headers requires the COMPILE_PDB_NAME"
  357. " property to have the value \"",
  358. reuseFrom, "\"\n");
  359. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e,
  360. target->GetBacktrace());
  361. failed = true;
  362. }
  363. }
  364. }
  365. return failed;
  366. }
  367. bool cmGlobalGenerator::IsExportedTargetsFile(
  368. const std::string& filename) const
  369. {
  370. auto const it = this->BuildExportSets.find(filename);
  371. if (it == this->BuildExportSets.end()) {
  372. return false;
  373. }
  374. return !cm::contains(this->BuildExportExportSets, filename);
  375. }
  376. // Find the make program for the generator, required for try compiles
  377. bool cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
  378. {
  379. if (this->FindMakeProgramFile.empty()) {
  380. cmSystemTools::Error(
  381. "Generator implementation error, "
  382. "all generators must specify this->FindMakeProgramFile");
  383. return false;
  384. }
  385. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  386. std::string setMakeProgram = mf->GetModulesFile(this->FindMakeProgramFile);
  387. if (!setMakeProgram.empty()) {
  388. mf->ReadListFile(setMakeProgram);
  389. }
  390. }
  391. if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
  392. std::ostringstream err;
  393. err << "CMake was unable to find a build program corresponding to \""
  394. << this->GetName() << "\". CMAKE_MAKE_PROGRAM is not set. You "
  395. << "probably need to select a different build tool.";
  396. cmSystemTools::Error(err.str());
  397. cmSystemTools::SetFatalErrorOccurred();
  398. return false;
  399. }
  400. std::string makeProgram = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
  401. // if there are spaces in the make program use short path
  402. // but do not short path the actual program name, as
  403. // this can cause trouble with VSExpress
  404. if (makeProgram.find(' ') != std::string::npos) {
  405. std::string dir;
  406. std::string file;
  407. cmSystemTools::SplitProgramPath(makeProgram, dir, file);
  408. std::string saveFile = file;
  409. cmSystemTools::GetShortPath(makeProgram, makeProgram);
  410. cmSystemTools::SplitProgramPath(makeProgram, dir, file);
  411. makeProgram = cmStrCat(dir, '/', saveFile);
  412. mf->AddCacheDefinition("CMAKE_MAKE_PROGRAM", makeProgram, "make program",
  413. cmStateEnums::FILEPATH);
  414. }
  415. return true;
  416. }
  417. bool cmGlobalGenerator::CheckLanguages(
  418. std::vector<std::string> const& /* languages */, cmMakefile* /* mf */) const
  419. {
  420. return true;
  421. }
  422. // enable the given language
  423. //
  424. // The following files are loaded in this order:
  425. //
  426. // First figure out what OS we are running on:
  427. //
  428. // CMakeSystem.cmake - configured file created by CMakeDetermineSystem.cmake
  429. // CMakeDetermineSystem.cmake - figure out os info and create
  430. // CMakeSystem.cmake IF CMAKE_SYSTEM
  431. // not set
  432. // CMakeSystem.cmake - configured file created by
  433. // CMakeDetermineSystem.cmake IF CMAKE_SYSTEM_LOADED
  434. // CMakeSystemSpecificInitialize.cmake
  435. // - includes Platform/${CMAKE_SYSTEM_NAME}-Initialize.cmake
  436. // Next try and enable all languages found in the languages vector
  437. //
  438. // FOREACH LANG in languages
  439. // CMake(LANG)Compiler.cmake - configured file create by
  440. // CMakeDetermine(LANG)Compiler.cmake
  441. // CMakeDetermine(LANG)Compiler.cmake - Finds compiler for LANG and
  442. // creates CMake(LANG)Compiler.cmake
  443. // CMake(LANG)Compiler.cmake - configured file created by
  444. // CMakeDetermine(LANG)Compiler.cmake
  445. //
  446. // CMakeSystemSpecificInformation.cmake
  447. // - includes Platform/${CMAKE_SYSTEM_NAME}.cmake
  448. // may use compiler stuff
  449. // FOREACH LANG in languages
  450. // CMake(LANG)Information.cmake
  451. // - loads Platform/${CMAKE_SYSTEM_NAME}-${COMPILER}.cmake
  452. // CMakeTest(LANG)Compiler.cmake
  453. // - Make sure the compiler works with a try compile if
  454. // CMakeDetermine(LANG) was loaded
  455. //
  456. // Now load a few files that can override values set in any of the above
  457. // (PROJECTNAME)Compatibility.cmake
  458. // - load any backwards compatibility stuff for current project
  459. // ${CMAKE_USER_MAKE_RULES_OVERRIDE}
  460. // - allow users a chance to override system variables
  461. //
  462. //
  463. void cmGlobalGenerator::EnableLanguage(
  464. std::vector<std::string> const& languages, cmMakefile* mf, bool optional)
  465. {
  466. if (!this->IsMultiConfig() &&
  467. !this->GetCMakeInstance()->GetIsInTryCompile()) {
  468. std::string envBuildType;
  469. if (!mf->GetDefinition("CMAKE_BUILD_TYPE") &&
  470. cmSystemTools::GetEnv("CMAKE_BUILD_TYPE", envBuildType)) {
  471. mf->AddCacheDefinition(
  472. "CMAKE_BUILD_TYPE", envBuildType,
  473. "Choose the type of build. Options include: empty, "
  474. "Debug, Release, RelWithDebInfo, MinSizeRel.",
  475. cmStateEnums::STRING);
  476. }
  477. }
  478. if (languages.empty()) {
  479. cmSystemTools::Error("EnableLanguage must have a lang specified!");
  480. cmSystemTools::SetFatalErrorOccurred();
  481. return;
  482. }
  483. std::set<std::string> cur_languages(languages.begin(), languages.end());
  484. for (std::string const& li : cur_languages) {
  485. if (!this->LanguagesInProgress.insert(li).second) {
  486. std::ostringstream e;
  487. e << "Language '" << li
  488. << "' is currently being enabled. "
  489. "Recursive call not allowed.";
  490. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  491. cmSystemTools::SetFatalErrorOccurred();
  492. return;
  493. }
  494. }
  495. if (this->TryCompileOuterMakefile) {
  496. // In a try-compile we can only enable languages provided by caller.
  497. for (std::string const& lang : languages) {
  498. if (lang == "NONE") {
  499. this->SetLanguageEnabled("NONE", mf);
  500. } else {
  501. if (!cm::contains(this->LanguagesReady, lang)) {
  502. std::ostringstream e;
  503. e << "The test project needs language " << lang
  504. << " which is not enabled.";
  505. this->TryCompileOuterMakefile->IssueMessage(MessageType::FATAL_ERROR,
  506. e.str());
  507. cmSystemTools::SetFatalErrorOccurred();
  508. return;
  509. }
  510. }
  511. }
  512. }
  513. bool fatalError = false;
  514. mf->AddDefinitionBool("RUN_CONFIGURE", true);
  515. std::string rootBin =
  516. cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles");
  517. // If the configuration files path has been set,
  518. // then we are in a try compile and need to copy the enable language
  519. // files from the parent cmake bin dir, into the try compile bin dir
  520. if (!this->ConfiguredFilesPath.empty()) {
  521. rootBin = this->ConfiguredFilesPath;
  522. }
  523. rootBin += '/';
  524. rootBin += cmVersion::GetCMakeVersion();
  525. // set the dir for parent files so they can be used by modules
  526. mf->AddDefinition("CMAKE_PLATFORM_INFO_DIR", rootBin);
  527. if (!this->CMakeInstance->GetIsInTryCompile()) {
  528. // Keep a mark in the cache to indicate that we've initialized the
  529. // platform information directory. If the platform information
  530. // directory exists but the mark is missing then CMakeCache.txt
  531. // has been removed or replaced without also removing the CMakeFiles/
  532. // directory. In this case remove the platform information directory
  533. // so that it will be re-initialized and the relevant information
  534. // restored in the cache.
  535. if (cmSystemTools::FileIsDirectory(rootBin) &&
  536. !mf->IsOn(kCMAKE_PLATFORM_INFO_INITIALIZED)) {
  537. cmSystemTools::RemoveADirectory(rootBin);
  538. }
  539. this->GetCMakeInstance()->AddCacheEntry(
  540. kCMAKE_PLATFORM_INFO_INITIALIZED, "1",
  541. "Platform information initialized", cmStateEnums::INTERNAL);
  542. }
  543. // try and load the CMakeSystem.cmake if it is there
  544. std::string fpath = rootBin;
  545. bool const readCMakeSystem = !mf->GetDefinition("CMAKE_SYSTEM_LOADED");
  546. if (readCMakeSystem) {
  547. fpath += "/CMakeSystem.cmake";
  548. if (cmSystemTools::FileExists(fpath)) {
  549. mf->ReadListFile(fpath);
  550. }
  551. }
  552. // Load the CMakeDetermineSystem.cmake file and find out
  553. // what platform we are running on
  554. if (!mf->GetDefinition("CMAKE_SYSTEM")) {
  555. #if defined(_WIN32) && !defined(__CYGWIN__)
  556. cmSystemTools::WindowsVersion windowsVersion =
  557. cmSystemTools::GetWindowsVersion();
  558. std::ostringstream windowsVersionString;
  559. windowsVersionString << windowsVersion.dwMajorVersion << "."
  560. << windowsVersion.dwMinorVersion << "."
  561. << windowsVersion.dwBuildNumber;
  562. mf->AddDefinition("CMAKE_HOST_SYSTEM_VERSION", windowsVersionString.str());
  563. #endif
  564. // Read the DetermineSystem file
  565. std::string systemFile = mf->GetModulesFile("CMakeDetermineSystem.cmake");
  566. mf->ReadListFile(systemFile);
  567. // load the CMakeSystem.cmake from the binary directory
  568. // this file is configured by the CMakeDetermineSystem.cmake file
  569. fpath = cmStrCat(rootBin, "/CMakeSystem.cmake");
  570. mf->ReadListFile(fpath);
  571. }
  572. if (readCMakeSystem) {
  573. // Tell the generator about the instance, if any.
  574. std::string instance = mf->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE");
  575. if (!this->SetGeneratorInstance(instance, mf)) {
  576. cmSystemTools::SetFatalErrorOccurred();
  577. return;
  578. }
  579. // Tell the generator about the target system.
  580. std::string system = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  581. if (!this->SetSystemName(system, mf)) {
  582. cmSystemTools::SetFatalErrorOccurred();
  583. return;
  584. }
  585. // Tell the generator about the platform, if any.
  586. std::string platform = mf->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM");
  587. if (!this->SetGeneratorPlatform(platform, mf)) {
  588. cmSystemTools::SetFatalErrorOccurred();
  589. return;
  590. }
  591. // Tell the generator about the toolset, if any.
  592. std::string toolset = mf->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET");
  593. if (!this->SetGeneratorToolset(toolset, false, mf)) {
  594. cmSystemTools::SetFatalErrorOccurred();
  595. return;
  596. }
  597. // Find the native build tool for this generator.
  598. if (!this->FindMakeProgram(mf)) {
  599. return;
  600. }
  601. // One-time includes of user-provided project setup files
  602. mf->GetState()->SetInTopLevelIncludes(true);
  603. std::string includes =
  604. mf->GetSafeDefinition("CMAKE_PROJECT_TOP_LEVEL_INCLUDES");
  605. cmList includesList{ includes };
  606. for (std::string const& setupFile : includesList) {
  607. std::string absSetupFile = cmSystemTools::CollapseFullPath(
  608. setupFile, mf->GetCurrentSourceDirectory());
  609. if (!cmSystemTools::FileExists(absSetupFile)) {
  610. cmSystemTools::Error(
  611. "CMAKE_PROJECT_TOP_LEVEL_INCLUDES file does not exist: " +
  612. setupFile);
  613. mf->GetState()->SetInTopLevelIncludes(false);
  614. return;
  615. }
  616. if (cmSystemTools::FileIsDirectory(absSetupFile)) {
  617. cmSystemTools::Error(
  618. "CMAKE_PROJECT_TOP_LEVEL_INCLUDES file is a directory: " +
  619. setupFile);
  620. mf->GetState()->SetInTopLevelIncludes(false);
  621. return;
  622. }
  623. if (!mf->ReadListFile(absSetupFile)) {
  624. cmSystemTools::Error(
  625. "Failed reading CMAKE_PROJECT_TOP_LEVEL_INCLUDES file: " +
  626. setupFile);
  627. mf->GetState()->SetInTopLevelIncludes(false);
  628. return;
  629. }
  630. }
  631. }
  632. mf->GetState()->SetInTopLevelIncludes(false);
  633. // Check that the languages are supported by the generator and its
  634. // native build tool found above.
  635. if (!this->CheckLanguages(languages, mf)) {
  636. return;
  637. }
  638. // **** Load the system specific initialization if not yet loaded
  639. if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INITIALIZE_LOADED")) {
  640. fpath = mf->GetModulesFile("CMakeSystemSpecificInitialize.cmake");
  641. if (!mf->ReadListFile(fpath)) {
  642. cmSystemTools::Error("Could not find cmake module file: "
  643. "CMakeSystemSpecificInitialize.cmake");
  644. }
  645. }
  646. std::map<std::string, bool> needTestLanguage;
  647. std::map<std::string, bool> needSetLanguageEnabledMaps;
  648. // foreach language
  649. // load the CMakeDetermine(LANG)Compiler.cmake file to find
  650. // the compiler
  651. for (std::string const& lang : languages) {
  652. needSetLanguageEnabledMaps[lang] = false;
  653. if (lang == "NONE") {
  654. this->SetLanguageEnabled("NONE", mf);
  655. continue;
  656. }
  657. std::string loadedLang = cmStrCat("CMAKE_", lang, "_COMPILER_LOADED");
  658. if (!mf->GetDefinition(loadedLang)) {
  659. fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  660. // If the existing build tree was already configured with this
  661. // version of CMake then try to load the configured file first
  662. // to avoid duplicate compiler tests.
  663. if (cmSystemTools::FileExists(fpath)) {
  664. if (!mf->ReadListFile(fpath)) {
  665. cmSystemTools::Error("Could not find cmake module file: " + fpath);
  666. }
  667. // if this file was found then the language was already determined
  668. // to be working
  669. needTestLanguage[lang] = false;
  670. this->SetLanguageEnabledFlag(lang, mf);
  671. needSetLanguageEnabledMaps[lang] = true;
  672. // this can only be called after loading CMake(LANG)Compiler.cmake
  673. }
  674. }
  675. if (!this->GetLanguageEnabled(lang)) {
  676. if (this->CMakeInstance->GetIsInTryCompile()) {
  677. cmSystemTools::Error("This should not have happened. "
  678. "If you see this message, you are probably "
  679. "using a broken CMakeLists.txt file or a "
  680. "problematic release of CMake");
  681. }
  682. // if the CMake(LANG)Compiler.cmake file was not found then
  683. // load CMakeDetermine(LANG)Compiler.cmake
  684. std::string determineCompiler =
  685. cmStrCat("CMakeDetermine", lang, "Compiler.cmake");
  686. std::string determineFile = mf->GetModulesFile(determineCompiler);
  687. if (!mf->ReadListFile(determineFile)) {
  688. cmSystemTools::Error("Could not find cmake module file: " +
  689. determineCompiler);
  690. }
  691. if (cmSystemTools::GetFatalErrorOccurred()) {
  692. return;
  693. }
  694. needTestLanguage[lang] = true;
  695. // Some generators like visual studio should not use the env variables
  696. // So the global generator can specify that in this variable
  697. if ((mf->GetPolicyStatus(cmPolicies::CMP0132) == cmPolicies::OLD ||
  698. mf->GetPolicyStatus(cmPolicies::CMP0132) == cmPolicies::WARN) &&
  699. !mf->GetDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV")) {
  700. // put ${CMake_(LANG)_COMPILER_ENV_VAR}=${CMAKE_(LANG)_COMPILER
  701. // into the environment, in case user scripts want to run
  702. // configure, or sub cmakes
  703. std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER");
  704. std::string compilerEnv =
  705. cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR");
  706. const std::string& envVar = mf->GetRequiredDefinition(compilerEnv);
  707. const std::string& envVarValue =
  708. mf->GetRequiredDefinition(compilerName);
  709. std::string env = cmStrCat(envVar, '=', envVarValue);
  710. cmSystemTools::PutEnv(env);
  711. }
  712. // if determineLanguage was called then load the file it
  713. // configures CMake(LANG)Compiler.cmake
  714. fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  715. if (!mf->ReadListFile(fpath)) {
  716. cmSystemTools::Error("Could not find cmake module file: " + fpath);
  717. }
  718. this->SetLanguageEnabledFlag(lang, mf);
  719. needSetLanguageEnabledMaps[lang] = true;
  720. // this can only be called after loading CMake(LANG)Compiler.cmake
  721. // the language must be enabled for try compile to work, but we do
  722. // not know if it is a working compiler yet so set the test language
  723. // flag
  724. needTestLanguage[lang] = true;
  725. } // end if(!this->GetLanguageEnabled(lang) )
  726. } // end loop over languages
  727. // **** Load the system specific information if not yet loaded
  728. if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INFORMATION_LOADED")) {
  729. fpath = mf->GetModulesFile("CMakeSystemSpecificInformation.cmake");
  730. if (!mf->ReadListFile(fpath)) {
  731. cmSystemTools::Error("Could not find cmake module file: "
  732. "CMakeSystemSpecificInformation.cmake");
  733. }
  734. }
  735. // loop over languages again loading CMake(LANG)Information.cmake
  736. //
  737. for (std::string const& lang : languages) {
  738. if (lang == "NONE") {
  739. this->SetLanguageEnabled("NONE", mf);
  740. continue;
  741. }
  742. // Check that the compiler was found.
  743. std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER");
  744. std::string compilerEnv = cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR");
  745. std::ostringstream noCompiler;
  746. cmValue compilerFile = mf->GetDefinition(compilerName);
  747. if (!cmNonempty(compilerFile) || cmIsNOTFOUND(*compilerFile)) {
  748. /* clang-format off */
  749. noCompiler <<
  750. "No " << compilerName << " could be found.\n"
  751. ;
  752. /* clang-format on */
  753. } else if ((lang != "RC") && (lang != "ASM_MARMASM") &&
  754. (lang != "ASM_MASM")) {
  755. if (!cmSystemTools::FileIsFullPath(*compilerFile)) {
  756. /* clang-format off */
  757. noCompiler <<
  758. "The " << compilerName << ":\n"
  759. " " << *compilerFile << "\n"
  760. "is not a full path and was not found in the PATH.\n"
  761. ;
  762. /* clang-format on */
  763. } else if (!cmSystemTools::FileExists(*compilerFile)) {
  764. /* clang-format off */
  765. noCompiler <<
  766. "The " << compilerName << ":\n"
  767. " " << *compilerFile << "\n"
  768. "is not a full path to an existing compiler tool.\n"
  769. ;
  770. /* clang-format on */
  771. }
  772. }
  773. if (!noCompiler.str().empty()) {
  774. // Skip testing this language since the compiler is not found.
  775. needTestLanguage[lang] = false;
  776. if (!optional) {
  777. // The compiler was not found and it is not optional. Remove
  778. // CMake(LANG)Compiler.cmake so we try again next time CMake runs.
  779. std::string compilerLangFile =
  780. cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  781. cmSystemTools::RemoveFile(compilerLangFile);
  782. if (!this->CMakeInstance->GetIsInTryCompile()) {
  783. this->PrintCompilerAdvice(noCompiler, lang,
  784. mf->GetDefinition(compilerEnv));
  785. mf->IssueMessage(MessageType::FATAL_ERROR, noCompiler.str());
  786. fatalError = true;
  787. }
  788. }
  789. }
  790. std::string langLoadedVar =
  791. cmStrCat("CMAKE_", lang, "_INFORMATION_LOADED");
  792. if (!mf->GetDefinition(langLoadedVar)) {
  793. fpath = cmStrCat("CMake", lang, "Information.cmake");
  794. std::string informationFile = mf->GetModulesFile(fpath);
  795. if (informationFile.empty()) {
  796. cmSystemTools::Error("Could not find cmake module file: " + fpath);
  797. } else if (!mf->ReadListFile(informationFile)) {
  798. cmSystemTools::Error("Could not process cmake module file: " +
  799. informationFile);
  800. }
  801. }
  802. if (needSetLanguageEnabledMaps[lang]) {
  803. this->SetLanguageEnabledMaps(lang, mf);
  804. }
  805. this->LanguagesReady.insert(lang);
  806. // Test the compiler for the language just setup
  807. // (but only if a compiler has been actually found)
  808. // At this point we should have enough info for a try compile
  809. // which is used in the backward stuff
  810. // If the language is untested then test it now with a try compile.
  811. if (needTestLanguage[lang]) {
  812. if (!this->CMakeInstance->GetIsInTryCompile()) {
  813. std::string testLang = cmStrCat("CMakeTest", lang, "Compiler.cmake");
  814. std::string ifpath = mf->GetModulesFile(testLang);
  815. if (!mf->ReadListFile(ifpath)) {
  816. cmSystemTools::Error("Could not find cmake module file: " +
  817. testLang);
  818. }
  819. std::string compilerWorks =
  820. cmStrCat("CMAKE_", lang, "_COMPILER_WORKS");
  821. // if the compiler did not work, then remove the
  822. // CMake(LANG)Compiler.cmake file so that it will get tested the
  823. // next time cmake is run
  824. if (!mf->IsOn(compilerWorks)) {
  825. std::string compilerLangFile =
  826. cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake");
  827. cmSystemTools::RemoveFile(compilerLangFile);
  828. }
  829. } // end if in try compile
  830. } // end need test language
  831. // Store the shared library flags so that we can satisfy CMP0018
  832. std::string sharedLibFlagsVar =
  833. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  834. this->LanguageToOriginalSharedLibFlags[lang] =
  835. mf->GetSafeDefinition(sharedLibFlagsVar);
  836. // Translate compiler ids for compatibility.
  837. this->CheckCompilerIdCompatibility(mf, lang);
  838. } // end for each language
  839. // Now load files that can override any settings on the platform or for
  840. // the project First load the project compatibility file if it is in
  841. // cmake
  842. std::string projectCompatibility =
  843. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/",
  844. mf->GetSafeDefinition("PROJECT_NAME"), "Compatibility.cmake");
  845. if (cmSystemTools::FileExists(projectCompatibility)) {
  846. mf->ReadListFile(projectCompatibility);
  847. }
  848. // Inform any extra generator of the new language.
  849. if (this->ExtraGenerator) {
  850. this->ExtraGenerator->EnableLanguage(languages, mf, false);
  851. }
  852. if (fatalError) {
  853. cmSystemTools::SetFatalErrorOccurred();
  854. }
  855. for (std::string const& lang : cur_languages) {
  856. this->LanguagesInProgress.erase(lang);
  857. }
  858. }
  859. void cmGlobalGenerator::PrintCompilerAdvice(std::ostream& os,
  860. std::string const& lang,
  861. cmValue envVar) const
  862. {
  863. // Subclasses override this method if they do not support this advice.
  864. os << "Tell CMake where to find the compiler by setting ";
  865. if (envVar) {
  866. os << "either the environment variable \"" << *envVar << "\" or ";
  867. }
  868. os << "the CMake cache entry CMAKE_" << lang
  869. << "_COMPILER "
  870. "to the full path to the compiler, or to the compiler name "
  871. "if it is in the PATH.";
  872. }
  873. void cmGlobalGenerator::CheckCompilerIdCompatibility(
  874. cmMakefile* mf, std::string const& lang) const
  875. {
  876. std::string compilerIdVar = "CMAKE_" + lang + "_COMPILER_ID";
  877. std::string const compilerId = mf->GetSafeDefinition(compilerIdVar);
  878. if (compilerId == "AppleClang") {
  879. switch (mf->GetPolicyStatus(cmPolicies::CMP0025)) {
  880. case cmPolicies::WARN:
  881. if (!this->CMakeInstance->GetIsInTryCompile() &&
  882. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0025")) {
  883. std::ostringstream w;
  884. /* clang-format off */
  885. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0025) << "\n"
  886. "Converting " << lang <<
  887. R"( compiler id "AppleClang" to "Clang" for compatibility.)"
  888. ;
  889. /* clang-format on */
  890. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  891. }
  892. CM_FALLTHROUGH;
  893. case cmPolicies::OLD:
  894. // OLD behavior is to convert AppleClang to Clang.
  895. mf->AddDefinition(compilerIdVar, "Clang");
  896. break;
  897. case cmPolicies::REQUIRED_IF_USED:
  898. case cmPolicies::REQUIRED_ALWAYS:
  899. mf->IssueMessage(
  900. MessageType::FATAL_ERROR,
  901. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0025));
  902. break;
  903. case cmPolicies::NEW:
  904. // NEW behavior is to keep AppleClang.
  905. break;
  906. }
  907. }
  908. if (compilerId == "QCC") {
  909. switch (mf->GetPolicyStatus(cmPolicies::CMP0047)) {
  910. case cmPolicies::WARN:
  911. if (!this->CMakeInstance->GetIsInTryCompile() &&
  912. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0047")) {
  913. std::ostringstream w;
  914. /* clang-format off */
  915. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0047) << "\n"
  916. "Converting " << lang <<
  917. R"( compiler id "QCC" to "GNU" for compatibility.)"
  918. ;
  919. /* clang-format on */
  920. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  921. }
  922. CM_FALLTHROUGH;
  923. case cmPolicies::OLD:
  924. // OLD behavior is to convert QCC to GNU.
  925. mf->AddDefinition(compilerIdVar, "GNU");
  926. if (lang == "C") {
  927. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCC", "1");
  928. } else if (lang == "CXX") {
  929. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCXX", "1");
  930. }
  931. break;
  932. case cmPolicies::REQUIRED_IF_USED:
  933. case cmPolicies::REQUIRED_ALWAYS:
  934. mf->IssueMessage(
  935. MessageType::FATAL_ERROR,
  936. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0047));
  937. CM_FALLTHROUGH;
  938. case cmPolicies::NEW:
  939. // NEW behavior is to keep QCC.
  940. break;
  941. }
  942. }
  943. if (compilerId == "XLClang") {
  944. switch (mf->GetPolicyStatus(cmPolicies::CMP0089)) {
  945. case cmPolicies::WARN:
  946. if (!this->CMakeInstance->GetIsInTryCompile() &&
  947. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0089")) {
  948. std::ostringstream w;
  949. /* clang-format off */
  950. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0089) << "\n"
  951. "Converting " << lang <<
  952. R"( compiler id "XLClang" to "XL" for compatibility.)"
  953. ;
  954. /* clang-format on */
  955. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  956. }
  957. CM_FALLTHROUGH;
  958. case cmPolicies::OLD:
  959. // OLD behavior is to convert XLClang to XL.
  960. mf->AddDefinition(compilerIdVar, "XL");
  961. break;
  962. case cmPolicies::REQUIRED_IF_USED:
  963. case cmPolicies::REQUIRED_ALWAYS:
  964. mf->IssueMessage(
  965. MessageType::FATAL_ERROR,
  966. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0089));
  967. break;
  968. case cmPolicies::NEW:
  969. // NEW behavior is to keep AppleClang.
  970. break;
  971. }
  972. }
  973. if (compilerId == "LCC") {
  974. switch (mf->GetPolicyStatus(cmPolicies::CMP0129)) {
  975. case cmPolicies::WARN:
  976. if (!this->CMakeInstance->GetIsInTryCompile() &&
  977. mf->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0129")) {
  978. std::ostringstream w;
  979. /* clang-format off */
  980. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0129) << "\n"
  981. "Converting " << lang <<
  982. R"( compiler id "LCC" to "GNU" for compatibility.)"
  983. ;
  984. /* clang-format on */
  985. mf->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  986. }
  987. CM_FALLTHROUGH;
  988. case cmPolicies::OLD:
  989. // OLD behavior is to convert LCC to GNU.
  990. mf->AddDefinition(compilerIdVar, "GNU");
  991. if (lang == "C") {
  992. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCC", "1");
  993. } else if (lang == "CXX") {
  994. mf->AddDefinition("CMAKE_COMPILER_IS_GNUCXX", "1");
  995. } else if (lang == "Fortran") {
  996. mf->AddDefinition("CMAKE_COMPILER_IS_GNUG77", "1");
  997. }
  998. {
  999. // Fix compiler versions.
  1000. std::string version = "CMAKE_" + lang + "_COMPILER_VERSION";
  1001. std::string emulated = "CMAKE_" + lang + "_SIMULATE_VERSION";
  1002. std::string emulatedId = "CMAKE_" + lang + "_SIMULATE_ID";
  1003. std::string const& actual = mf->GetRequiredDefinition(emulated);
  1004. mf->AddDefinition(version, actual);
  1005. mf->RemoveDefinition(emulatedId);
  1006. mf->RemoveDefinition(emulated);
  1007. }
  1008. break;
  1009. case cmPolicies::REQUIRED_IF_USED:
  1010. case cmPolicies::REQUIRED_ALWAYS:
  1011. mf->IssueMessage(
  1012. MessageType::FATAL_ERROR,
  1013. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0129));
  1014. CM_FALLTHROUGH;
  1015. case cmPolicies::NEW:
  1016. // NEW behavior is to keep LCC.
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. std::string cmGlobalGenerator::GetLanguageOutputExtension(
  1022. cmSourceFile const& source) const
  1023. {
  1024. const std::string& lang = source.GetLanguage();
  1025. if (!lang.empty()) {
  1026. auto const it = this->LanguageToOutputExtension.find(lang);
  1027. if (it != this->LanguageToOutputExtension.end()) {
  1028. return it->second;
  1029. }
  1030. } else {
  1031. // if no language is found then check to see if it is already an
  1032. // output extension for some language. In that case it should be ignored
  1033. // and in this map, so it will not be compiled but will just be used.
  1034. std::string const& ext = source.GetExtension();
  1035. if (!ext.empty()) {
  1036. if (this->OutputExtensions.count(ext)) {
  1037. return ext;
  1038. }
  1039. }
  1040. }
  1041. return "";
  1042. }
  1043. std::string cmGlobalGenerator::GetLanguageFromExtension(const char* ext) const
  1044. {
  1045. // if there is an extension and it starts with . then move past the
  1046. // . because the extensions are not stored with a . in the map
  1047. if (!ext) {
  1048. return "";
  1049. }
  1050. if (*ext == '.') {
  1051. ++ext;
  1052. }
  1053. auto const it = this->ExtensionToLanguage.find(ext);
  1054. if (it != this->ExtensionToLanguage.end()) {
  1055. return it->second;
  1056. }
  1057. return "";
  1058. }
  1059. /* SetLanguageEnabled() is now split in two parts:
  1060. at first the enabled-flag is set. This can then be used in EnabledLanguage()
  1061. for checking whether the language is already enabled. After setting this
  1062. flag still the values from the cmake variables have to be copied into the
  1063. internal maps, this is done in SetLanguageEnabledMaps() which is called
  1064. after the system- and compiler specific files have been loaded.
  1065. This split was done originally so that compiler-specific configuration
  1066. files could change the object file extension
  1067. (CMAKE_<LANG>_OUTPUT_EXTENSION) before the CMake variables were copied
  1068. to the C++ maps.
  1069. */
  1070. void cmGlobalGenerator::SetLanguageEnabled(const std::string& l,
  1071. cmMakefile* mf)
  1072. {
  1073. this->SetLanguageEnabledFlag(l, mf);
  1074. this->SetLanguageEnabledMaps(l, mf);
  1075. }
  1076. void cmGlobalGenerator::SetLanguageEnabledFlag(const std::string& l,
  1077. cmMakefile* mf)
  1078. {
  1079. this->CMakeInstance->GetState()->SetLanguageEnabled(l);
  1080. // Fill the language-to-extension map with the current variable
  1081. // settings to make sure it is available for the try_compile()
  1082. // command source file signature. In SetLanguageEnabledMaps this
  1083. // will be done again to account for any compiler- or
  1084. // platform-specific entries.
  1085. this->FillExtensionToLanguageMap(l, mf);
  1086. }
  1087. void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l,
  1088. cmMakefile* mf)
  1089. {
  1090. // use LanguageToLinkerPreference to detect whether this functions has
  1091. // run before
  1092. if (cm::contains(this->LanguageToLinkerPreference, l)) {
  1093. return;
  1094. }
  1095. std::string linkerPrefVar = "CMAKE_" + l + "_LINKER_PREFERENCE";
  1096. cmValue linkerPref = mf->GetDefinition(linkerPrefVar);
  1097. int preference = 0;
  1098. if (cmNonempty(linkerPref)) {
  1099. if (sscanf(linkerPref->c_str(), "%d", &preference) != 1) {
  1100. // backward compatibility: before 2.6 LINKER_PREFERENCE
  1101. // was either "None" or "Preferred", and only the first character was
  1102. // tested. So if there is a custom language out there and it is
  1103. // "Preferred", set its preference high
  1104. if ((*linkerPref)[0] == 'P') {
  1105. preference = 100;
  1106. } else {
  1107. preference = 0;
  1108. }
  1109. }
  1110. }
  1111. if (preference < 0) {
  1112. std::string msg =
  1113. cmStrCat(linkerPrefVar, " is negative, adjusting it to 0");
  1114. cmSystemTools::Message(msg, "Warning");
  1115. preference = 0;
  1116. }
  1117. this->LanguageToLinkerPreference[l] = preference;
  1118. std::string outputExtensionVar = "CMAKE_" + l + "_OUTPUT_EXTENSION";
  1119. if (cmValue p = mf->GetDefinition(outputExtensionVar)) {
  1120. std::string outputExtension = *p;
  1121. this->LanguageToOutputExtension[l] = outputExtension;
  1122. this->OutputExtensions[outputExtension] = outputExtension;
  1123. if (cmHasPrefix(outputExtension, ".")) {
  1124. outputExtension = outputExtension.substr(1);
  1125. this->OutputExtensions[outputExtension] = outputExtension;
  1126. }
  1127. }
  1128. // The map was originally filled by SetLanguageEnabledFlag, but
  1129. // since then the compiler- and platform-specific files have been
  1130. // loaded which might have added more entries.
  1131. this->FillExtensionToLanguageMap(l, mf);
  1132. std::string ignoreExtensionsVar =
  1133. std::string("CMAKE_") + std::string(l) + std::string("_IGNORE_EXTENSIONS");
  1134. std::string ignoreExts = mf->GetSafeDefinition(ignoreExtensionsVar);
  1135. cmList extensionList{ ignoreExts };
  1136. for (std::string const& i : extensionList) {
  1137. this->IgnoreExtensions[i] = true;
  1138. }
  1139. }
  1140. void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l,
  1141. cmMakefile* mf)
  1142. {
  1143. std::string extensionsVar = std::string("CMAKE_") + std::string(l) +
  1144. std::string("_SOURCE_FILE_EXTENSIONS");
  1145. const std::string& exts = mf->GetSafeDefinition(extensionsVar);
  1146. cmList extensionList{ exts };
  1147. for (std::string const& i : extensionList) {
  1148. this->ExtensionToLanguage[i] = l;
  1149. }
  1150. }
  1151. cmValue cmGlobalGenerator::GetGlobalSetting(std::string const& name) const
  1152. {
  1153. assert(!this->Makefiles.empty());
  1154. return this->Makefiles[0]->GetDefinition(name);
  1155. }
  1156. bool cmGlobalGenerator::GlobalSettingIsOn(std::string const& name) const
  1157. {
  1158. assert(!this->Makefiles.empty());
  1159. return this->Makefiles[0]->IsOn(name);
  1160. }
  1161. std::string cmGlobalGenerator::GetSafeGlobalSetting(
  1162. std::string const& name) const
  1163. {
  1164. assert(!this->Makefiles.empty());
  1165. return this->Makefiles[0]->GetDefinition(name);
  1166. }
  1167. bool cmGlobalGenerator::IgnoreFile(const char* ext) const
  1168. {
  1169. if (!this->GetLanguageFromExtension(ext).empty()) {
  1170. return false;
  1171. }
  1172. return (this->IgnoreExtensions.count(ext) > 0);
  1173. }
  1174. bool cmGlobalGenerator::GetLanguageEnabled(const std::string& l) const
  1175. {
  1176. return this->CMakeInstance->GetState()->GetLanguageEnabled(l);
  1177. }
  1178. void cmGlobalGenerator::ClearEnabledLanguages()
  1179. {
  1180. this->CMakeInstance->GetState()->ClearEnabledLanguages();
  1181. }
  1182. void cmGlobalGenerator::CreateLocalGenerators()
  1183. {
  1184. this->LocalGeneratorSearchIndex.clear();
  1185. this->LocalGenerators.clear();
  1186. this->LocalGenerators.reserve(this->Makefiles.size());
  1187. for (const auto& m : this->Makefiles) {
  1188. auto lg = this->CreateLocalGenerator(m.get());
  1189. this->IndexLocalGenerator(lg.get());
  1190. this->LocalGenerators.push_back(std::move(lg));
  1191. }
  1192. }
  1193. void cmGlobalGenerator::Configure()
  1194. {
  1195. auto startTime = std::chrono::steady_clock::now();
  1196. this->FirstTimeProgress = 0.0f;
  1197. this->ClearGeneratorMembers();
  1198. this->NextDeferId = 0;
  1199. cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
  1200. snapshot.GetDirectory().SetCurrentSource(
  1201. this->CMakeInstance->GetHomeDirectory());
  1202. snapshot.GetDirectory().SetCurrentBinary(
  1203. this->CMakeInstance->GetHomeOutputDirectory());
  1204. auto dirMfu = cm::make_unique<cmMakefile>(this, snapshot);
  1205. auto* dirMf = dirMfu.get();
  1206. this->Makefiles.push_back(std::move(dirMfu));
  1207. dirMf->SetRecursionDepth(this->RecursionDepth);
  1208. this->IndexMakefile(dirMf);
  1209. this->BinaryDirectories.insert(
  1210. this->CMakeInstance->GetHomeOutputDirectory());
  1211. if (this->ExtraGenerator && !this->CMakeInstance->GetIsInTryCompile()) {
  1212. this->CMakeInstance->IssueMessage(
  1213. MessageType::DEPRECATION_WARNING,
  1214. cmStrCat("Support for \"Extra Generators\" like\n ",
  1215. this->ExtraGenerator->GetName(),
  1216. "\nis deprecated and will be removed from a future version "
  1217. "of CMake. IDEs may use the cmake-file-api(7) to view "
  1218. "CMake-generated project build trees."));
  1219. }
  1220. // now do it
  1221. this->ConfigureDoneCMP0026AndCMP0024 = false;
  1222. dirMf->Configure();
  1223. dirMf->EnforceDirectoryLevelRules();
  1224. this->ConfigureDoneCMP0026AndCMP0024 = true;
  1225. // Put a copy of each global target in every directory.
  1226. {
  1227. std::vector<GlobalTargetInfo> globalTargets;
  1228. this->CreateDefaultGlobalTargets(globalTargets);
  1229. for (const auto& mf : this->Makefiles) {
  1230. for (GlobalTargetInfo const& globalTarget : globalTargets) {
  1231. this->CreateGlobalTarget(globalTarget, mf.get());
  1232. }
  1233. }
  1234. }
  1235. // update the cache entry for the number of local generators, this is used
  1236. // for progress
  1237. char num[100];
  1238. snprintf(num, sizeof(num), "%d", static_cast<int>(this->Makefiles.size()));
  1239. this->GetCMakeInstance()->AddCacheEntry("CMAKE_NUMBER_OF_MAKEFILES", num,
  1240. "number of local generators",
  1241. cmStateEnums::INTERNAL);
  1242. auto endTime = std::chrono::steady_clock::now();
  1243. if (this->CMakeInstance->GetWorkingMode() == cmake::NORMAL_MODE) {
  1244. std::ostringstream msg;
  1245. if (cmSystemTools::GetErrorOccurredFlag()) {
  1246. msg << "Configuring incomplete, errors occurred!";
  1247. } else {
  1248. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  1249. endTime - startTime);
  1250. msg << "Configuring done (" << std::fixed << std::setprecision(1)
  1251. << ms.count() / 1000.0L << "s)";
  1252. }
  1253. this->CMakeInstance->UpdateProgress(msg.str(), -1);
  1254. }
  1255. }
  1256. void cmGlobalGenerator::CreateGenerationObjects(TargetTypes targetTypes)
  1257. {
  1258. this->CreateLocalGenerators();
  1259. // Commit side effects only if we are actually generating
  1260. if (this->GetConfigureDoneCMP0026()) {
  1261. this->CheckTargetProperties();
  1262. }
  1263. this->CreateGeneratorTargets(targetTypes);
  1264. if (targetTypes == TargetTypes::AllTargets) {
  1265. this->ComputeBuildFileGenerators();
  1266. }
  1267. }
  1268. void cmGlobalGenerator::CreateImportedGenerationObjects(
  1269. cmMakefile* mf, const std::vector<std::string>& targets,
  1270. std::vector<const cmGeneratorTarget*>& exports)
  1271. {
  1272. this->CreateGenerationObjects(ImportedOnly);
  1273. auto const mfit =
  1274. std::find_if(this->Makefiles.begin(), this->Makefiles.end(),
  1275. [mf](const std::unique_ptr<cmMakefile>& item) {
  1276. return item.get() == mf;
  1277. });
  1278. auto& lg =
  1279. this->LocalGenerators[std::distance(this->Makefiles.begin(), mfit)];
  1280. for (std::string const& t : targets) {
  1281. cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(t);
  1282. if (gt) {
  1283. exports.push_back(gt);
  1284. }
  1285. }
  1286. }
  1287. cmExportBuildFileGenerator* cmGlobalGenerator::GetExportedTargetsFile(
  1288. const std::string& filename) const
  1289. {
  1290. auto const it = this->BuildExportSets.find(filename);
  1291. return it == this->BuildExportSets.end() ? nullptr : it->second;
  1292. }
  1293. void cmGlobalGenerator::AddCMP0042WarnTarget(const std::string& target)
  1294. {
  1295. this->CMP0042WarnTargets.insert(target);
  1296. }
  1297. void cmGlobalGenerator::AddCMP0068WarnTarget(const std::string& target)
  1298. {
  1299. this->CMP0068WarnTargets.insert(target);
  1300. }
  1301. bool cmGlobalGenerator::CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const
  1302. {
  1303. // If the property is not enabled then okay.
  1304. if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(
  1305. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  1306. return true;
  1307. }
  1308. // This generator does not support duplicate custom targets.
  1309. std::ostringstream e;
  1310. e << "This project has enabled the ALLOW_DUPLICATE_CUSTOM_TARGETS "
  1311. << "global property. "
  1312. << "The \"" << this->GetName() << "\" generator does not support "
  1313. << "duplicate custom targets. "
  1314. << "Consider using a Makefiles generator or fix the project to not "
  1315. << "use duplicate target names.";
  1316. cmSystemTools::Error(e.str());
  1317. return false;
  1318. }
  1319. void cmGlobalGenerator::CxxModuleSupportCheck() const
  1320. {
  1321. bool const diagnose = !this->DiagnosedCxxModuleSupport &&
  1322. !this->CMakeInstance->GetIsInTryCompile();
  1323. if (diagnose) {
  1324. this->DiagnosedCxxModuleSupport = true;
  1325. this->GetCMakeInstance()->IssueMessage(
  1326. MessageType::AUTHOR_WARNING,
  1327. "C++20 modules support via CMAKE_EXPERIMENTAL_CXX_MODULE_DYNDEP "
  1328. "is experimental. It is meant only for compiler developers to try.");
  1329. }
  1330. }
  1331. void cmGlobalGenerator::ComputeBuildFileGenerators()
  1332. {
  1333. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1334. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const& gens =
  1335. this->Makefiles[i]->GetExportBuildFileGenerators();
  1336. for (std::unique_ptr<cmExportBuildFileGenerator> const& g : gens) {
  1337. g->Compute(this->LocalGenerators[i].get());
  1338. }
  1339. }
  1340. }
  1341. bool cmGlobalGenerator::UnsupportedVariableIsDefined(const std::string& name,
  1342. bool supported) const
  1343. {
  1344. if (!supported && this->Makefiles.front()->GetDefinition(name)) {
  1345. std::ostringstream e;
  1346. /* clang-format off */
  1347. e <<
  1348. "Generator\n"
  1349. " " << this->GetName() << "\n"
  1350. "does not support variable\n"
  1351. " " << name << "\n"
  1352. "but it has been specified."
  1353. ;
  1354. /* clang-format on */
  1355. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1356. return true;
  1357. }
  1358. return false;
  1359. }
  1360. bool cmGlobalGenerator::Compute()
  1361. {
  1362. // Make sure unsupported variables are not used.
  1363. if (this->UnsupportedVariableIsDefined("CMAKE_DEFAULT_BUILD_TYPE",
  1364. this->SupportsDefaultBuildType())) {
  1365. return false;
  1366. }
  1367. if (this->UnsupportedVariableIsDefined("CMAKE_CROSS_CONFIGS",
  1368. this->SupportsCrossConfigs())) {
  1369. return false;
  1370. }
  1371. if (this->UnsupportedVariableIsDefined("CMAKE_DEFAULT_CONFIGS",
  1372. this->SupportsDefaultConfigs())) {
  1373. return false;
  1374. }
  1375. if (!this->InspectConfigTypeVariables()) {
  1376. return false;
  1377. }
  1378. // Some generators track files replaced during the Generate.
  1379. // Start with an empty vector:
  1380. this->FilesReplacedDuringGenerate.clear();
  1381. // clear targets to issue warning CMP0042 for
  1382. this->CMP0042WarnTargets.clear();
  1383. // clear targets to issue warning CMP0068 for
  1384. this->CMP0068WarnTargets.clear();
  1385. // Check whether this generator is allowed to run.
  1386. if (!this->CheckALLOW_DUPLICATE_CUSTOM_TARGETS()) {
  1387. return false;
  1388. }
  1389. this->FinalizeTargetConfiguration();
  1390. this->CreateGenerationObjects();
  1391. // at this point this->LocalGenerators has been filled,
  1392. // so create the map from project name to vector of local generators
  1393. this->FillProjectMap();
  1394. // Add automatically generated sources (e.g. unity build).
  1395. if (!this->AddAutomaticSources()) {
  1396. return false;
  1397. }
  1398. // Iterate through all targets and add verification targets for header sets
  1399. if (!this->AddHeaderSetVerification()) {
  1400. return false;
  1401. }
  1402. #ifndef CMAKE_BOOTSTRAP
  1403. this->QtAutoGen =
  1404. cm::make_unique<cmQtAutoGenGlobalInitializer>(this->LocalGenerators);
  1405. if (!this->QtAutoGen->InitializeCustomTargets()) {
  1406. return false;
  1407. }
  1408. #endif
  1409. // Add generator specific helper commands
  1410. for (const auto& localGen : this->LocalGenerators) {
  1411. localGen->AddHelperCommands();
  1412. }
  1413. // Perform up-front computation in order to handle errors (such as unknown
  1414. // features) at this point. While processing the compile features we also
  1415. // calculate and cache the language standard required by the compile
  1416. // features.
  1417. for (const auto& localGen : this->LocalGenerators) {
  1418. if (!localGen->ComputeTargetCompileFeatures()) {
  1419. return false;
  1420. }
  1421. }
  1422. for (const auto& localGen : this->LocalGenerators) {
  1423. cmMakefile* mf = localGen->GetMakefile();
  1424. for (const auto& g : mf->GetInstallGenerators()) {
  1425. if (!g->Compute(localGen.get())) {
  1426. return false;
  1427. }
  1428. }
  1429. }
  1430. this->AddExtraIDETargets();
  1431. // Trace the dependencies, after that no custom commands should be added
  1432. // because their dependencies might not be handled correctly
  1433. for (const auto& localGen : this->LocalGenerators) {
  1434. localGen->TraceDependencies();
  1435. }
  1436. // Make sure that all (non-imported) targets have source files added!
  1437. if (this->CheckTargetsForMissingSources()) {
  1438. return false;
  1439. }
  1440. this->ForceLinkerLanguages();
  1441. // Compute the manifest of main targets generated.
  1442. for (const auto& localGen : this->LocalGenerators) {
  1443. localGen->ComputeTargetManifest();
  1444. }
  1445. // Compute the inter-target dependencies.
  1446. if (!this->ComputeTargetDepends()) {
  1447. return false;
  1448. }
  1449. this->ComputeTargetOrder();
  1450. if (this->CheckTargetsForType()) {
  1451. return false;
  1452. }
  1453. if (this->CheckTargetsForPchCompilePdb()) {
  1454. return false;
  1455. }
  1456. for (const auto& localGen : this->LocalGenerators) {
  1457. localGen->ComputeHomeRelativeOutputPath();
  1458. }
  1459. return true;
  1460. }
  1461. void cmGlobalGenerator::Generate()
  1462. {
  1463. auto startTime = std::chrono::steady_clock::now();
  1464. // Create a map from local generator to the complete set of targets
  1465. // it builds by default.
  1466. this->InitializeProgressMarks();
  1467. this->DiagnosedCxxModuleSupport = false;
  1468. this->ProcessEvaluationFiles();
  1469. this->CMakeInstance->UpdateProgress("Generating", 0.1f);
  1470. #ifndef CMAKE_BOOTSTRAP
  1471. if (!this->QtAutoGen->SetupCustomTargets()) {
  1472. if (!cmSystemTools::GetErrorOccurredFlag()) {
  1473. this->GetCMakeInstance()->IssueMessage(
  1474. MessageType::FATAL_ERROR,
  1475. "Problem setting up custom targets for QtAutoGen");
  1476. }
  1477. return;
  1478. }
  1479. #endif
  1480. // Generate project files
  1481. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1482. this->SetCurrentMakefile(this->LocalGenerators[i]->GetMakefile());
  1483. this->LocalGenerators[i]->Generate();
  1484. if (!this->LocalGenerators[i]->GetMakefile()->IsOn(
  1485. "CMAKE_SKIP_INSTALL_RULES")) {
  1486. this->LocalGenerators[i]->GenerateInstallRules();
  1487. }
  1488. this->LocalGenerators[i]->GenerateTestFiles();
  1489. this->CMakeInstance->UpdateProgress(
  1490. "Generating",
  1491. 0.1f +
  1492. 0.9f * (static_cast<float>(i) + 1.0f) /
  1493. static_cast<float>(this->LocalGenerators.size()));
  1494. }
  1495. this->SetCurrentMakefile(nullptr);
  1496. if (!this->GenerateCPackPropertiesFile()) {
  1497. this->GetCMakeInstance()->IssueMessage(
  1498. MessageType::FATAL_ERROR, "Could not write CPack properties file.");
  1499. }
  1500. for (auto& buildExpSet : this->BuildExportSets) {
  1501. if (!buildExpSet.second->GenerateImportFile()) {
  1502. if (!cmSystemTools::GetErrorOccurredFlag()) {
  1503. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  1504. "Could not write export file.");
  1505. }
  1506. return;
  1507. }
  1508. }
  1509. // Update rule hashes.
  1510. this->CheckRuleHashes();
  1511. this->WriteSummary();
  1512. if (this->ExtraGenerator) {
  1513. this->ExtraGenerator->Generate();
  1514. }
  1515. // Perform validation checks on memoized link structures.
  1516. this->CheckTargetLinkLibraries();
  1517. if (!this->CMP0042WarnTargets.empty()) {
  1518. std::ostringstream w;
  1519. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0042) << "\n";
  1520. w << "MACOSX_RPATH is not specified for"
  1521. " the following targets:\n";
  1522. for (std::string const& t : this->CMP0042WarnTargets) {
  1523. w << " " << t << "\n";
  1524. }
  1525. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1526. w.str());
  1527. }
  1528. if (!this->CMP0068WarnTargets.empty()) {
  1529. std::ostringstream w;
  1530. /* clang-format off */
  1531. w <<
  1532. cmPolicies::GetPolicyWarning(cmPolicies::CMP0068) << "\n"
  1533. "For compatibility with older versions of CMake, the install_name "
  1534. "fields for the following targets are still affected by RPATH "
  1535. "settings:\n"
  1536. ;
  1537. /* clang-format on */
  1538. for (std::string const& t : this->CMP0068WarnTargets) {
  1539. w << " " << t << "\n";
  1540. }
  1541. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1542. w.str());
  1543. }
  1544. auto endTime = std::chrono::steady_clock::now();
  1545. auto ms =
  1546. std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
  1547. std::ostringstream msg;
  1548. msg << "Generating done (" << std::fixed << std::setprecision(1)
  1549. << ms.count() / 1000.0L << "s)";
  1550. this->CMakeInstance->UpdateProgress(msg.str(), -1);
  1551. }
  1552. bool cmGlobalGenerator::ComputeTargetDepends()
  1553. {
  1554. cmComputeTargetDepends ctd(this);
  1555. if (!ctd.Compute()) {
  1556. return false;
  1557. }
  1558. for (cmGeneratorTarget const* target : ctd.GetTargets()) {
  1559. ctd.GetTargetDirectDepends(target, this->TargetDependencies[target]);
  1560. }
  1561. return true;
  1562. }
  1563. std::vector<cmGeneratorTarget*>
  1564. cmGlobalGenerator::GetLocalGeneratorTargetsInOrder(cmLocalGenerator* lg) const
  1565. {
  1566. std::vector<cmGeneratorTarget*> gts;
  1567. cm::append(gts, lg->GetGeneratorTargets());
  1568. std::sort(gts.begin(), gts.end(),
  1569. [this](cmGeneratorTarget const* l, cmGeneratorTarget const* r) {
  1570. return this->TargetOrderIndexLess(l, r);
  1571. });
  1572. return gts;
  1573. }
  1574. void cmGlobalGenerator::ComputeTargetOrder()
  1575. {
  1576. size_t index = 0;
  1577. auto const& lgens = this->GetLocalGenerators();
  1578. for (auto const& lgen : lgens) {
  1579. const auto& targets = lgen->GetGeneratorTargets();
  1580. for (const auto& gt : targets) {
  1581. this->ComputeTargetOrder(gt.get(), index);
  1582. }
  1583. }
  1584. assert(index == this->TargetOrderIndex.size());
  1585. }
  1586. void cmGlobalGenerator::ComputeTargetOrder(cmGeneratorTarget const* gt,
  1587. size_t& index)
  1588. {
  1589. std::map<cmGeneratorTarget const*, size_t>::value_type value(gt, 0);
  1590. auto insertion = this->TargetOrderIndex.insert(value);
  1591. if (!insertion.second) {
  1592. return;
  1593. }
  1594. auto entry = insertion.first;
  1595. const auto& deps = this->GetTargetDirectDepends(gt);
  1596. for (const auto& d : deps) {
  1597. this->ComputeTargetOrder(d, index);
  1598. }
  1599. entry->second = index++;
  1600. }
  1601. bool cmGlobalGenerator::AddHeaderSetVerification()
  1602. {
  1603. for (auto const& gen : this->LocalGenerators) {
  1604. // Because AddHeaderSetVerification() adds generator targets, we need to
  1605. // cache the existing list of generator targets before starting.
  1606. std::vector<cmGeneratorTarget*> genTargets;
  1607. genTargets.reserve(gen->GetGeneratorTargets().size());
  1608. for (auto const& tgt : gen->GetGeneratorTargets()) {
  1609. genTargets.push_back(tgt.get());
  1610. }
  1611. for (auto* tgt : genTargets) {
  1612. if (!tgt->AddHeaderSetVerification()) {
  1613. return false;
  1614. }
  1615. }
  1616. }
  1617. cmTarget* allVerifyTarget = this->Makefiles.front()->FindTargetToUse(
  1618. "all_verify_interface_header_sets", true);
  1619. if (allVerifyTarget) {
  1620. this->LocalGenerators.front()->AddGeneratorTarget(
  1621. cm::make_unique<cmGeneratorTarget>(allVerifyTarget,
  1622. this->LocalGenerators.front().get()));
  1623. }
  1624. return true;
  1625. }
  1626. bool cmGlobalGenerator::AddAutomaticSources()
  1627. {
  1628. for (const auto& lg : this->LocalGenerators) {
  1629. lg->CreateEvaluationFileOutputs();
  1630. }
  1631. for (const auto& lg : this->LocalGenerators) {
  1632. for (const auto& gt : lg->GetGeneratorTargets()) {
  1633. if (!gt->CanCompileSources()) {
  1634. continue;
  1635. }
  1636. lg->AddUnityBuild(gt.get());
  1637. lg->AddISPCDependencies(gt.get());
  1638. // Targets that re-use a PCH are handled below.
  1639. if (!gt->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
  1640. lg->AddPchDependencies(gt.get());
  1641. }
  1642. lg->AddXCConfigSources(gt.get());
  1643. }
  1644. }
  1645. for (const auto& lg : this->LocalGenerators) {
  1646. for (const auto& gt : lg->GetGeneratorTargets()) {
  1647. if (!gt->CanCompileSources()) {
  1648. continue;
  1649. }
  1650. // Handle targets that re-use a PCH from an above-handled target.
  1651. if (gt->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
  1652. lg->AddPchDependencies(gt.get());
  1653. }
  1654. }
  1655. }
  1656. // The above transformations may have changed the classification of sources.
  1657. // Clear the source list and classification cache (KindedSources) of all
  1658. // targets so that it will be recomputed correctly by the generators later
  1659. // now that the above transformations are done for all targets.
  1660. for (const auto& lg : this->LocalGenerators) {
  1661. for (const auto& gt : lg->GetGeneratorTargets()) {
  1662. gt->ClearSourcesCache();
  1663. }
  1664. }
  1665. return true;
  1666. }
  1667. std::unique_ptr<cmLinkLineComputer> cmGlobalGenerator::CreateLinkLineComputer(
  1668. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir) const
  1669. {
  1670. return cm::make_unique<cmLinkLineComputer>(outputConverter, stateDir);
  1671. }
  1672. std::unique_ptr<cmLinkLineComputer>
  1673. cmGlobalGenerator::CreateMSVC60LinkLineComputer(
  1674. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir) const
  1675. {
  1676. return std::unique_ptr<cmLinkLineComputer>(
  1677. cm::make_unique<cmMSVC60LinkLineComputer>(outputConverter, stateDir));
  1678. }
  1679. void cmGlobalGenerator::FinalizeTargetConfiguration()
  1680. {
  1681. std::vector<std::string> const langs =
  1682. this->CMakeInstance->GetState()->GetEnabledLanguages();
  1683. // Construct per-target generator information.
  1684. for (const auto& mf : this->Makefiles) {
  1685. const cmBTStringRange noConfigCompileDefinitions =
  1686. mf->GetCompileDefinitionsEntries();
  1687. cm::optional<std::map<std::string, cmValue>> perConfigCompileDefinitions;
  1688. for (auto& target : mf->GetTargets()) {
  1689. cmTarget* t = &target.second;
  1690. t->FinalizeTargetConfiguration(noConfigCompileDefinitions,
  1691. perConfigCompileDefinitions);
  1692. }
  1693. // The standard include directories for each language
  1694. // should be treated as system include directories.
  1695. std::set<std::string> standardIncludesSet;
  1696. for (std::string const& li : langs) {
  1697. std::string const standardIncludesVar =
  1698. "CMAKE_" + li + "_STANDARD_INCLUDE_DIRECTORIES";
  1699. std::string const& standardIncludesStr =
  1700. mf->GetSafeDefinition(standardIncludesVar);
  1701. cmList standardIncludesList{ standardIncludesStr };
  1702. standardIncludesSet.insert(standardIncludesList.begin(),
  1703. standardIncludesList.end());
  1704. }
  1705. mf->AddSystemIncludeDirectories(standardIncludesSet);
  1706. }
  1707. }
  1708. void cmGlobalGenerator::CreateGeneratorTargets(
  1709. TargetTypes targetTypes, cmMakefile* mf, cmLocalGenerator* lg,
  1710. std::map<cmTarget*, cmGeneratorTarget*> const& importedMap)
  1711. {
  1712. if (targetTypes == AllTargets) {
  1713. for (cmTarget* target : mf->GetOrderedTargets()) {
  1714. lg->AddGeneratorTarget(cm::make_unique<cmGeneratorTarget>(target, lg));
  1715. }
  1716. }
  1717. for (cmTarget* t : mf->GetImportedTargets()) {
  1718. lg->AddImportedGeneratorTarget(importedMap.find(t)->second);
  1719. }
  1720. }
  1721. void cmGlobalGenerator::CreateGeneratorTargets(TargetTypes targetTypes)
  1722. {
  1723. std::map<cmTarget*, cmGeneratorTarget*> importedMap;
  1724. for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
  1725. auto& mf = this->Makefiles[i];
  1726. for (const auto& ownedImpTgt : mf->GetOwnedImportedTargets()) {
  1727. cmLocalGenerator* lg = this->LocalGenerators[i].get();
  1728. auto gt = cm::make_unique<cmGeneratorTarget>(ownedImpTgt.get(), lg);
  1729. importedMap[ownedImpTgt.get()] = gt.get();
  1730. lg->AddOwnedImportedGeneratorTarget(std::move(gt));
  1731. }
  1732. }
  1733. // Construct per-target generator information.
  1734. for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
  1735. this->CreateGeneratorTargets(targetTypes, this->Makefiles[i].get(),
  1736. this->LocalGenerators[i].get(), importedMap);
  1737. }
  1738. }
  1739. void cmGlobalGenerator::ClearGeneratorMembers()
  1740. {
  1741. this->BuildExportSets.clear();
  1742. this->Makefiles.clear();
  1743. this->LocalGenerators.clear();
  1744. this->AliasTargets.clear();
  1745. this->ExportSets.clear();
  1746. this->InstallComponents.clear();
  1747. this->TargetDependencies.clear();
  1748. this->TargetSearchIndex.clear();
  1749. this->GeneratorTargetSearchIndex.clear();
  1750. this->MakefileSearchIndex.clear();
  1751. this->LocalGeneratorSearchIndex.clear();
  1752. this->TargetOrderIndex.clear();
  1753. this->ProjectMap.clear();
  1754. this->RuleHashes.clear();
  1755. this->DirectoryContentMap.clear();
  1756. this->BinaryDirectories.clear();
  1757. this->GeneratedFiles.clear();
  1758. }
  1759. void cmGlobalGenerator::ComputeTargetObjectDirectory(
  1760. cmGeneratorTarget* /*unused*/) const
  1761. {
  1762. }
  1763. void cmGlobalGenerator::CheckTargetProperties()
  1764. {
  1765. // check for link libraries and include directories containing "NOTFOUND"
  1766. // and for infinite loops
  1767. std::map<std::string, std::string> notFoundMap;
  1768. cmState* state = this->GetCMakeInstance()->GetState();
  1769. for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
  1770. this->Makefiles[i]->Generate(*this->LocalGenerators[i]);
  1771. for (auto const& target : this->Makefiles[i]->GetTargets()) {
  1772. if (target.second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  1773. continue;
  1774. }
  1775. for (auto const& lib : target.second.GetOriginalLinkLibraries()) {
  1776. if (lib.first.size() > 9 && cmIsNOTFOUND(lib.first)) {
  1777. std::string varName = lib.first.substr(0, lib.first.size() - 9);
  1778. if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
  1779. varName += " (ADVANCED)";
  1780. }
  1781. std::string text =
  1782. cmStrCat(notFoundMap[varName], "\n linked by target \"",
  1783. target.second.GetName(), "\" in directory ",
  1784. this->Makefiles[i]->GetCurrentSourceDirectory());
  1785. notFoundMap[varName] = text;
  1786. }
  1787. }
  1788. cmValue incDirProp = target.second.GetProperty("INCLUDE_DIRECTORIES");
  1789. if (!incDirProp) {
  1790. continue;
  1791. }
  1792. std::string incDirs = cmGeneratorExpression::Preprocess(
  1793. *incDirProp, cmGeneratorExpression::StripAllGeneratorExpressions);
  1794. cmList incs(incDirs);
  1795. for (std::string const& incDir : incs) {
  1796. if (incDir.size() > 9 && cmIsNOTFOUND(incDir)) {
  1797. std::string varName = incDir.substr(0, incDir.size() - 9);
  1798. if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
  1799. varName += " (ADVANCED)";
  1800. }
  1801. std::string text =
  1802. cmStrCat(notFoundMap[varName],
  1803. "\n used as include directory in directory ",
  1804. this->Makefiles[i]->GetCurrentSourceDirectory());
  1805. notFoundMap[varName] = text;
  1806. }
  1807. }
  1808. }
  1809. }
  1810. if (!notFoundMap.empty()) {
  1811. std::string notFoundVars;
  1812. for (auto const& notFound : notFoundMap) {
  1813. notFoundVars += notFound.first;
  1814. notFoundVars += notFound.second;
  1815. notFoundVars += "\n";
  1816. }
  1817. cmSystemTools::Error("The following variables are used in this project, "
  1818. "but they are set to NOTFOUND.\n"
  1819. "Please set them or make sure they are set and "
  1820. "tested correctly in the CMake files:\n" +
  1821. notFoundVars);
  1822. }
  1823. }
  1824. int cmGlobalGenerator::TryCompile(int jobs, const std::string& srcdir,
  1825. const std::string& bindir,
  1826. const std::string& projectName,
  1827. const std::string& target, bool fast,
  1828. std::string& output, cmMakefile* mf)
  1829. {
  1830. // if this is not set, then this is a first time configure
  1831. // and there is a good chance that the try compile stuff will
  1832. // take the bulk of the time, so try and guess some progress
  1833. // by getting closer and closer to 100 without actually getting there.
  1834. if (!this->CMakeInstance->GetState()->GetInitializedCacheValue(
  1835. "CMAKE_NUMBER_OF_MAKEFILES")) {
  1836. // If CMAKE_NUMBER_OF_MAKEFILES is not set
  1837. // we are in the first time progress and we have no
  1838. // idea how long it will be. So, just move 1/10th of the way
  1839. // there each time, and don't go over 95%
  1840. this->FirstTimeProgress += ((1.0f - this->FirstTimeProgress) / 30.0f);
  1841. if (this->FirstTimeProgress > 0.95f) {
  1842. this->FirstTimeProgress = 0.95f;
  1843. }
  1844. this->CMakeInstance->UpdateProgress("Configuring",
  1845. this->FirstTimeProgress);
  1846. }
  1847. std::vector<std::string> newTarget = {};
  1848. if (!target.empty()) {
  1849. newTarget = { target };
  1850. }
  1851. std::string config =
  1852. mf->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  1853. cmBuildOptions defaultBuildOptions(false, fast, PackageResolveMode::Disable);
  1854. return this->Build(jobs, srcdir, bindir, projectName, newTarget, output, "",
  1855. config, defaultBuildOptions, true,
  1856. this->TryCompileTimeout);
  1857. }
  1858. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  1859. cmGlobalGenerator::GenerateBuildCommand(
  1860. const std::string& /*unused*/, const std::string& /*unused*/,
  1861. const std::string& /*unused*/, std::vector<std::string> const& /*unused*/,
  1862. const std::string& /*unused*/, int /*unused*/, bool /*unused*/,
  1863. const cmBuildOptions& /*unused*/, std::vector<std::string> const& /*unused*/)
  1864. {
  1865. GeneratedMakeCommand makeCommand;
  1866. makeCommand.Add("cmGlobalGenerator::GenerateBuildCommand not implemented");
  1867. return { std::move(makeCommand) };
  1868. }
  1869. void cmGlobalGenerator::PrintBuildCommandAdvice(std::ostream& /*os*/,
  1870. int /*jobs*/) const
  1871. {
  1872. // Subclasses override this method if they e.g want to give a warning that
  1873. // they do not support certain build command line options
  1874. }
  1875. int cmGlobalGenerator::Build(
  1876. int jobs, const std::string& /*unused*/, const std::string& bindir,
  1877. const std::string& projectName, const std::vector<std::string>& targets,
  1878. std::string& output, const std::string& makeCommandCSTR,
  1879. const std::string& config, const cmBuildOptions& buildOptions, bool verbose,
  1880. cmDuration timeout, cmSystemTools::OutputOption outputflag,
  1881. std::vector<std::string> const& nativeOptions)
  1882. {
  1883. bool hideconsole = cmSystemTools::GetRunCommandHideConsole();
  1884. /**
  1885. * Run an executable command and put the stdout in output.
  1886. */
  1887. cmWorkingDirectory workdir(bindir);
  1888. output += "Change Dir: ";
  1889. output += bindir;
  1890. output += "\n";
  1891. if (workdir.Failed()) {
  1892. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1893. std::string err = cmStrCat("Failed to change directory: ",
  1894. std::strerror(workdir.GetLastResult()));
  1895. cmSystemTools::Error(err);
  1896. output += err;
  1897. output += "\n";
  1898. return 1;
  1899. }
  1900. std::string realConfig = config;
  1901. if (realConfig.empty()) {
  1902. realConfig = this->GetDefaultBuildConfig();
  1903. }
  1904. int retVal = 0;
  1905. cmSystemTools::SetRunCommandHideConsole(true);
  1906. std::string outputBuffer;
  1907. std::string* outputPtr = &outputBuffer;
  1908. std::vector<GeneratedMakeCommand> makeCommand = this->GenerateBuildCommand(
  1909. makeCommandCSTR, projectName, bindir, targets, realConfig, jobs, verbose,
  1910. buildOptions, nativeOptions);
  1911. // Workaround to convince some commands to produce output.
  1912. if (outputflag == cmSystemTools::OUTPUT_PASSTHROUGH &&
  1913. makeCommand.back().RequiresOutputForward) {
  1914. outputflag = cmSystemTools::OUTPUT_FORWARD;
  1915. }
  1916. // should we do a clean first?
  1917. if (buildOptions.Clean) {
  1918. std::vector<GeneratedMakeCommand> cleanCommand =
  1919. this->GenerateBuildCommand(makeCommandCSTR, projectName, bindir,
  1920. { "clean" }, realConfig, jobs, verbose,
  1921. buildOptions);
  1922. output += "\nRun Clean Command:";
  1923. output += cleanCommand.front().Printable();
  1924. output += "\n";
  1925. if (cleanCommand.size() != 1) {
  1926. this->GetCMakeInstance()->IssueMessage(MessageType::INTERNAL_ERROR,
  1927. "The generator did not produce "
  1928. "exactly one command for the "
  1929. "'clean' target");
  1930. return 1;
  1931. }
  1932. if (!cmSystemTools::RunSingleCommand(cleanCommand.front().PrimaryCommand,
  1933. outputPtr, outputPtr, &retVal,
  1934. nullptr, outputflag, timeout)) {
  1935. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1936. cmSystemTools::Error("Generator: execution of make clean failed.");
  1937. output += *outputPtr;
  1938. output += "\nGenerator: execution of make clean failed.\n";
  1939. return 1;
  1940. }
  1941. output += *outputPtr;
  1942. }
  1943. // now build
  1944. std::string makeCommandStr;
  1945. output += "\nRun Build Command(s):";
  1946. retVal = 0;
  1947. for (auto command = makeCommand.begin();
  1948. command != makeCommand.end() && retVal == 0; ++command) {
  1949. makeCommandStr = command->Printable();
  1950. if (command != makeCommand.end()) {
  1951. makeCommandStr += " && ";
  1952. }
  1953. output += makeCommandStr;
  1954. if (!cmSystemTools::RunSingleCommand(command->PrimaryCommand, outputPtr,
  1955. outputPtr, &retVal, nullptr,
  1956. outputflag, timeout)) {
  1957. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1958. cmSystemTools::Error(
  1959. "Generator: execution of make failed. Make command was: " +
  1960. makeCommandStr);
  1961. output += *outputPtr;
  1962. output += "\nGenerator: execution of make failed. Make command was: " +
  1963. makeCommandStr + "\n";
  1964. return 1;
  1965. }
  1966. output += *outputPtr;
  1967. }
  1968. output += "\n";
  1969. cmSystemTools::SetRunCommandHideConsole(hideconsole);
  1970. // The OpenWatcom tools do not return an error code when a link
  1971. // library is not found!
  1972. if (this->CMakeInstance->GetState()->UseWatcomWMake() && retVal == 0 &&
  1973. output.find("W1008: cannot open") != std::string::npos) {
  1974. retVal = 1;
  1975. }
  1976. return retVal;
  1977. }
  1978. bool cmGlobalGenerator::Open(const std::string& bindir,
  1979. const std::string& projectName, bool dryRun)
  1980. {
  1981. if (this->ExtraGenerator) {
  1982. return this->ExtraGenerator->Open(bindir, projectName, dryRun);
  1983. }
  1984. return false;
  1985. }
  1986. std::string cmGlobalGenerator::GenerateCMakeBuildCommand(
  1987. const std::string& target, const std::string& config,
  1988. const std::string& parallel, const std::string& native, bool ignoreErrors)
  1989. {
  1990. std::string makeCommand = cmSystemTools::GetCMakeCommand();
  1991. makeCommand =
  1992. cmStrCat(cmSystemTools::ConvertToOutputPath(makeCommand), " --build .");
  1993. if (!config.empty()) {
  1994. makeCommand += " --config \"";
  1995. makeCommand += config;
  1996. makeCommand += "\"";
  1997. }
  1998. if (!parallel.empty()) {
  1999. makeCommand += " --parallel \"";
  2000. makeCommand += parallel;
  2001. makeCommand += "\"";
  2002. }
  2003. if (!target.empty()) {
  2004. makeCommand += " --target \"";
  2005. makeCommand += target;
  2006. makeCommand += "\"";
  2007. }
  2008. const char* sep = " -- ";
  2009. if (ignoreErrors) {
  2010. const char* iflag = this->GetBuildIgnoreErrorsFlag();
  2011. if (iflag && *iflag) {
  2012. makeCommand += sep;
  2013. makeCommand += iflag;
  2014. sep = " ";
  2015. }
  2016. }
  2017. if (!native.empty()) {
  2018. makeCommand += sep;
  2019. makeCommand += native;
  2020. }
  2021. return makeCommand;
  2022. }
  2023. void cmGlobalGenerator::AddMakefile(std::unique_ptr<cmMakefile> mf)
  2024. {
  2025. this->IndexMakefile(mf.get());
  2026. this->Makefiles.push_back(std::move(mf));
  2027. // update progress
  2028. // estimate how many lg there will be
  2029. cmValue numGenC = this->CMakeInstance->GetState()->GetInitializedCacheValue(
  2030. "CMAKE_NUMBER_OF_MAKEFILES");
  2031. if (!numGenC) {
  2032. // If CMAKE_NUMBER_OF_MAKEFILES is not set
  2033. // we are in the first time progress and we have no
  2034. // idea how long it will be. So, just move half way
  2035. // there each time, and don't go over 95%
  2036. this->FirstTimeProgress += ((1.0f - this->FirstTimeProgress) / 30.0f);
  2037. if (this->FirstTimeProgress > 0.95f) {
  2038. this->FirstTimeProgress = 0.95f;
  2039. }
  2040. this->CMakeInstance->UpdateProgress("Configuring",
  2041. this->FirstTimeProgress);
  2042. return;
  2043. }
  2044. int numGen = atoi(numGenC->c_str());
  2045. float prog =
  2046. static_cast<float>(this->Makefiles.size()) / static_cast<float>(numGen);
  2047. if (prog > 1.0f) {
  2048. prog = 1.0f;
  2049. }
  2050. this->CMakeInstance->UpdateProgress("Configuring", prog);
  2051. }
  2052. void cmGlobalGenerator::AddInstallComponent(const std::string& component)
  2053. {
  2054. if (!component.empty()) {
  2055. this->InstallComponents.insert(component);
  2056. }
  2057. }
  2058. void cmGlobalGenerator::MarkAsGeneratedFile(const std::string& filepath)
  2059. {
  2060. this->GeneratedFiles.insert(filepath);
  2061. }
  2062. bool cmGlobalGenerator::IsGeneratedFile(const std::string& filepath)
  2063. {
  2064. return this->GeneratedFiles.find(filepath) != this->GeneratedFiles.end();
  2065. }
  2066. void cmGlobalGenerator::EnableInstallTarget()
  2067. {
  2068. this->InstallTargetEnabled = true;
  2069. }
  2070. std::unique_ptr<cmLocalGenerator> cmGlobalGenerator::CreateLocalGenerator(
  2071. cmMakefile* mf)
  2072. {
  2073. return cm::make_unique<cmLocalGenerator>(this, mf);
  2074. }
  2075. void cmGlobalGenerator::EnableLanguagesFromGenerator(cmGlobalGenerator* gen,
  2076. cmMakefile* mf)
  2077. {
  2078. this->SetConfiguredFilesPath(gen);
  2079. this->TryCompileOuterMakefile = mf;
  2080. cmValue make =
  2081. gen->GetCMakeInstance()->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
  2082. this->GetCMakeInstance()->AddCacheEntry(
  2083. "CMAKE_MAKE_PROGRAM", make, "make program", cmStateEnums::FILEPATH);
  2084. // copy the enabled languages
  2085. this->GetCMakeInstance()->GetState()->SetEnabledLanguages(
  2086. gen->GetCMakeInstance()->GetState()->GetEnabledLanguages());
  2087. this->LanguagesReady = gen->LanguagesReady;
  2088. this->ExtensionToLanguage = gen->ExtensionToLanguage;
  2089. this->IgnoreExtensions = gen->IgnoreExtensions;
  2090. this->LanguageToOutputExtension = gen->LanguageToOutputExtension;
  2091. this->LanguageToLinkerPreference = gen->LanguageToLinkerPreference;
  2092. this->OutputExtensions = gen->OutputExtensions;
  2093. }
  2094. void cmGlobalGenerator::SetConfiguredFilesPath(cmGlobalGenerator* gen)
  2095. {
  2096. if (!gen->ConfiguredFilesPath.empty()) {
  2097. this->ConfiguredFilesPath = gen->ConfiguredFilesPath;
  2098. } else {
  2099. this->ConfiguredFilesPath =
  2100. cmStrCat(gen->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles");
  2101. }
  2102. }
  2103. bool cmGlobalGenerator::IsExcluded(cmStateSnapshot const& rootSnp,
  2104. cmStateSnapshot const& snp_) const
  2105. {
  2106. cmStateSnapshot snp = snp_;
  2107. while (snp.IsValid()) {
  2108. if (snp == rootSnp) {
  2109. // No directory excludes itself.
  2110. return false;
  2111. }
  2112. if (snp.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  2113. // This directory is excluded from its parent.
  2114. return true;
  2115. }
  2116. snp = snp.GetBuildsystemDirectoryParent();
  2117. }
  2118. return false;
  2119. }
  2120. bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
  2121. cmLocalGenerator* gen) const
  2122. {
  2123. assert(gen);
  2124. cmStateSnapshot rootSnp = root->GetStateSnapshot();
  2125. cmStateSnapshot snp = gen->GetStateSnapshot();
  2126. return this->IsExcluded(rootSnp, snp);
  2127. }
  2128. bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
  2129. const cmGeneratorTarget* target) const
  2130. {
  2131. if (!target->IsInBuildSystem()) {
  2132. return true;
  2133. }
  2134. cmMakefile* mf = root->GetMakefile();
  2135. const std::string EXCLUDE_FROM_ALL = "EXCLUDE_FROM_ALL";
  2136. if (cmValue exclude = target->GetProperty(EXCLUDE_FROM_ALL)) {
  2137. // Expand the property value per configuration.
  2138. unsigned int trueCount = 0;
  2139. unsigned int falseCount = 0;
  2140. const std::vector<std::string>& configs =
  2141. mf->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2142. for (const std::string& config : configs) {
  2143. cmGeneratorExpressionInterpreter genexInterpreter(root, config, target);
  2144. if (cmIsOn(genexInterpreter.Evaluate(*exclude, EXCLUDE_FROM_ALL))) {
  2145. ++trueCount;
  2146. } else {
  2147. ++falseCount;
  2148. }
  2149. }
  2150. // Check whether the genex expansion of the property agrees in all
  2151. // configurations.
  2152. if (trueCount > 0 && falseCount > 0) {
  2153. std::ostringstream e;
  2154. e << "The EXCLUDE_FROM_ALL property of target \"" << target->GetName()
  2155. << "\" varies by configuration. This is not supported by the \""
  2156. << root->GetGlobalGenerator()->GetName() << "\" generator.";
  2157. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2158. }
  2159. return trueCount;
  2160. }
  2161. // This target is included in its directory. Check whether the
  2162. // directory is excluded.
  2163. return this->IsExcluded(root, target->GetLocalGenerator());
  2164. }
  2165. void cmGlobalGenerator::GetEnabledLanguages(
  2166. std::vector<std::string>& lang) const
  2167. {
  2168. lang = this->CMakeInstance->GetState()->GetEnabledLanguages();
  2169. }
  2170. int cmGlobalGenerator::GetLinkerPreference(const std::string& lang) const
  2171. {
  2172. auto const it = this->LanguageToLinkerPreference.find(lang);
  2173. if (it != this->LanguageToLinkerPreference.end()) {
  2174. return it->second;
  2175. }
  2176. return 0;
  2177. }
  2178. void cmGlobalGenerator::FillProjectMap()
  2179. {
  2180. this->ProjectMap.clear(); // make sure we start with a clean map
  2181. for (const auto& localGen : this->LocalGenerators) {
  2182. // for each local generator add all projects
  2183. cmStateSnapshot snp = localGen->GetStateSnapshot();
  2184. std::string name;
  2185. do {
  2186. std::string snpProjName = snp.GetProjectName();
  2187. if (name != snpProjName) {
  2188. name = snpProjName;
  2189. this->ProjectMap[name].push_back(localGen.get());
  2190. }
  2191. snp = snp.GetBuildsystemDirectoryParent();
  2192. } while (snp.IsValid());
  2193. }
  2194. }
  2195. cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const
  2196. {
  2197. auto const it = this->MakefileSearchIndex.find(start_dir);
  2198. if (it != this->MakefileSearchIndex.end()) {
  2199. return it->second;
  2200. }
  2201. return nullptr;
  2202. }
  2203. cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator(
  2204. cmDirectoryId const& id) const
  2205. {
  2206. auto const it = this->LocalGeneratorSearchIndex.find(id.String);
  2207. if (it != this->LocalGeneratorSearchIndex.end()) {
  2208. return it->second;
  2209. }
  2210. return nullptr;
  2211. }
  2212. void cmGlobalGenerator::AddAlias(const std::string& name,
  2213. std::string const& tgtName)
  2214. {
  2215. this->AliasTargets[name] = tgtName;
  2216. }
  2217. bool cmGlobalGenerator::IsAlias(const std::string& name) const
  2218. {
  2219. return cm::contains(this->AliasTargets, name);
  2220. }
  2221. void cmGlobalGenerator::IndexTarget(cmTarget* t)
  2222. {
  2223. if (!t->IsImported() || t->IsImportedGloballyVisible()) {
  2224. this->TargetSearchIndex[t->GetName()] = t;
  2225. }
  2226. }
  2227. void cmGlobalGenerator::IndexGeneratorTarget(cmGeneratorTarget* gt)
  2228. {
  2229. if (!gt->IsImported() || gt->IsImportedGloballyVisible()) {
  2230. this->GeneratorTargetSearchIndex[gt->GetName()] = gt;
  2231. }
  2232. }
  2233. static char const hexDigits[] = "0123456789abcdef";
  2234. std::string cmGlobalGenerator::IndexGeneratorTargetUniquely(
  2235. cmGeneratorTarget const* gt)
  2236. {
  2237. // Use the pointer value to uniquely identify the target instance.
  2238. // Use a ":" prefix to avoid conflict with project-defined targets.
  2239. // We must satisfy cmGeneratorExpression::IsValidTargetName so use no
  2240. // other special characters.
  2241. constexpr size_t sizeof_ptr =
  2242. sizeof(gt); // NOLINT(bugprone-sizeof-expression)
  2243. char buf[1 + sizeof_ptr * 2];
  2244. char* b = buf;
  2245. *b++ = ':';
  2246. for (size_t i = 0; i < sizeof_ptr; ++i) {
  2247. unsigned char const c = reinterpret_cast<unsigned char const*>(&gt)[i];
  2248. *b++ = hexDigits[(c & 0xf0) >> 4];
  2249. *b++ = hexDigits[(c & 0x0f)];
  2250. }
  2251. std::string id(buf, sizeof(buf));
  2252. // We internally index pointers to non-const generator targets
  2253. // but our callers only have pointers to const generator targets.
  2254. // They will give up non-const privileges when looking up anyway.
  2255. this->GeneratorTargetSearchIndex[id] = const_cast<cmGeneratorTarget*>(gt);
  2256. return id;
  2257. }
  2258. void cmGlobalGenerator::IndexMakefile(cmMakefile* mf)
  2259. {
  2260. // We index by both source and binary directory. add_subdirectory
  2261. // supports multiple build directories sharing the same source directory.
  2262. // The source directory index will reference only the first time it is used.
  2263. this->MakefileSearchIndex.insert(
  2264. MakefileMap::value_type(mf->GetCurrentSourceDirectory(), mf));
  2265. this->MakefileSearchIndex.insert(
  2266. MakefileMap::value_type(mf->GetCurrentBinaryDirectory(), mf));
  2267. }
  2268. void cmGlobalGenerator::IndexLocalGenerator(cmLocalGenerator* lg)
  2269. {
  2270. cmDirectoryId id = lg->GetMakefile()->GetDirectoryId();
  2271. this->LocalGeneratorSearchIndex[id.String] = lg;
  2272. }
  2273. cmTarget* cmGlobalGenerator::FindTargetImpl(std::string const& name) const
  2274. {
  2275. auto const it = this->TargetSearchIndex.find(name);
  2276. if (it != this->TargetSearchIndex.end()) {
  2277. return it->second;
  2278. }
  2279. return nullptr;
  2280. }
  2281. cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
  2282. std::string const& name) const
  2283. {
  2284. auto const it = this->GeneratorTargetSearchIndex.find(name);
  2285. if (it != this->GeneratorTargetSearchIndex.end()) {
  2286. return it->second;
  2287. }
  2288. return nullptr;
  2289. }
  2290. cmTarget* cmGlobalGenerator::FindTarget(const std::string& name,
  2291. bool excludeAliases) const
  2292. {
  2293. if (!excludeAliases) {
  2294. auto const ai = this->AliasTargets.find(name);
  2295. if (ai != this->AliasTargets.end()) {
  2296. return this->FindTargetImpl(ai->second);
  2297. }
  2298. }
  2299. return this->FindTargetImpl(name);
  2300. }
  2301. cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTarget(
  2302. const std::string& name) const
  2303. {
  2304. auto const ai = this->AliasTargets.find(name);
  2305. if (ai != this->AliasTargets.end()) {
  2306. return this->FindGeneratorTargetImpl(ai->second);
  2307. }
  2308. return this->FindGeneratorTargetImpl(name);
  2309. }
  2310. bool cmGlobalGenerator::NameResolvesToFramework(
  2311. const std::string& libname) const
  2312. {
  2313. if (cmSystemTools::IsPathToFramework(libname)) {
  2314. return true;
  2315. }
  2316. if (cmTarget* tgt = this->FindTarget(libname)) {
  2317. if (tgt->IsFrameworkOnApple()) {
  2318. return true;
  2319. }
  2320. }
  2321. return false;
  2322. }
  2323. // If the file has no extension it's either a raw executable or might
  2324. // be a direct reference to a binary within a framework (bad practice!).
  2325. // This is where we change the path to point to the framework directory.
  2326. // .tbd files also can be located in SDK frameworks (they are
  2327. // placeholders for actual libraries shipped with the OS)
  2328. cm::optional<cmGlobalGenerator::FrameworkDescriptor>
  2329. cmGlobalGenerator::SplitFrameworkPath(const std::string& path,
  2330. FrameworkFormat format) const
  2331. {
  2332. // Check for framework structure:
  2333. // (/path/to/)?FwName.framework
  2334. // or (/path/to/)?FwName.framework/FwName(.tbd)?
  2335. // or (/path/to/)?FwName.framework/Versions/*/FwName(.tbd)?
  2336. static cmsys::RegularExpression frameworkPath(
  2337. "((.+)/)?(.+)\\.framework(/Versions/[^/]+)?(/(.+))?$");
  2338. auto ext = cmSystemTools::GetFilenameLastExtension(path);
  2339. if ((ext.empty() || ext == ".tbd" || ext == ".framework") &&
  2340. frameworkPath.find(path)) {
  2341. auto name = frameworkPath.match(3);
  2342. auto libname =
  2343. cmSystemTools::GetFilenameWithoutExtension(frameworkPath.match(6));
  2344. if (format == FrameworkFormat::Strict && libname.empty()) {
  2345. return cm::nullopt;
  2346. }
  2347. if (!libname.empty() && !cmHasPrefix(libname, name)) {
  2348. return cm::nullopt;
  2349. }
  2350. if (libname.empty() || name.size() == libname.size()) {
  2351. return FrameworkDescriptor{ frameworkPath.match(2), name };
  2352. }
  2353. return FrameworkDescriptor{ frameworkPath.match(2), name,
  2354. libname.substr(name.size()) };
  2355. }
  2356. if (format == FrameworkFormat::Extended) {
  2357. // path format can be more flexible: (/path/to/)?fwName(.framework)?
  2358. auto fwDir = cmSystemTools::GetParentDirectory(path);
  2359. auto name = cmSystemTools::GetFilenameLastExtension(path) == ".framework"
  2360. ? cmSystemTools::GetFilenameWithoutExtension(path)
  2361. : cmSystemTools::GetFilenameName(path);
  2362. return FrameworkDescriptor{ fwDir, name };
  2363. }
  2364. return cm::nullopt;
  2365. }
  2366. bool cmGlobalGenerator::CheckCMP0037(std::string const& targetName,
  2367. std::string const& reason) const
  2368. {
  2369. cmTarget* tgt = this->FindTarget(targetName);
  2370. if (!tgt) {
  2371. return true;
  2372. }
  2373. MessageType messageType = MessageType::AUTHOR_WARNING;
  2374. std::ostringstream e;
  2375. bool issueMessage = false;
  2376. switch (tgt->GetPolicyStatusCMP0037()) {
  2377. case cmPolicies::WARN:
  2378. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  2379. issueMessage = true;
  2380. CM_FALLTHROUGH;
  2381. case cmPolicies::OLD:
  2382. break;
  2383. case cmPolicies::NEW:
  2384. case cmPolicies::REQUIRED_IF_USED:
  2385. case cmPolicies::REQUIRED_ALWAYS:
  2386. issueMessage = true;
  2387. messageType = MessageType::FATAL_ERROR;
  2388. break;
  2389. }
  2390. if (issueMessage) {
  2391. e << "The target name \"" << targetName << "\" is reserved " << reason
  2392. << ".";
  2393. if (messageType == MessageType::AUTHOR_WARNING) {
  2394. e << " It may result in undefined behavior.";
  2395. }
  2396. this->GetCMakeInstance()->IssueMessage(messageType, e.str(),
  2397. tgt->GetBacktrace());
  2398. if (messageType == MessageType::FATAL_ERROR) {
  2399. return false;
  2400. }
  2401. }
  2402. return true;
  2403. }
  2404. void cmGlobalGenerator::CreateDefaultGlobalTargets(
  2405. std::vector<GlobalTargetInfo>& targets)
  2406. {
  2407. this->AddGlobalTarget_Package(targets);
  2408. this->AddGlobalTarget_PackageSource(targets);
  2409. this->AddGlobalTarget_Test(targets);
  2410. this->AddGlobalTarget_EditCache(targets);
  2411. this->AddGlobalTarget_RebuildCache(targets);
  2412. this->AddGlobalTarget_Install(targets);
  2413. }
  2414. void cmGlobalGenerator::AddGlobalTarget_Package(
  2415. std::vector<GlobalTargetInfo>& targets)
  2416. {
  2417. auto& mf = this->Makefiles[0];
  2418. std::string configFile =
  2419. cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackConfig.cmake");
  2420. if (!cmSystemTools::FileExists(configFile)) {
  2421. return;
  2422. }
  2423. static const auto reservedTargets = { "package", "PACKAGE" };
  2424. for (auto const& target : reservedTargets) {
  2425. if (!this->CheckCMP0037(target, "when CPack packaging is enabled")) {
  2426. return;
  2427. }
  2428. }
  2429. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2430. GlobalTargetInfo gti;
  2431. gti.Name = this->GetPackageTargetName();
  2432. gti.Message = "Run CPack packaging tool...";
  2433. gti.UsesTerminal = true;
  2434. gti.WorkingDir = mf->GetCurrentBinaryDirectory();
  2435. cmCustomCommandLine singleLine;
  2436. singleLine.push_back(cmSystemTools::GetCPackCommand());
  2437. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2438. singleLine.push_back("-C");
  2439. singleLine.push_back(cmakeCfgIntDir);
  2440. }
  2441. singleLine.push_back("--config");
  2442. singleLine.push_back("./CPackConfig.cmake");
  2443. gti.CommandLines.push_back(std::move(singleLine));
  2444. if (this->GetPreinstallTargetName()) {
  2445. gti.Depends.emplace_back(this->GetPreinstallTargetName());
  2446. } else {
  2447. cmValue noPackageAll =
  2448. mf->GetDefinition("CMAKE_SKIP_PACKAGE_ALL_DEPENDENCY");
  2449. if (cmIsOff(noPackageAll)) {
  2450. gti.Depends.emplace_back(this->GetAllTargetName());
  2451. }
  2452. }
  2453. targets.push_back(std::move(gti));
  2454. }
  2455. void cmGlobalGenerator::AddGlobalTarget_PackageSource(
  2456. std::vector<GlobalTargetInfo>& targets)
  2457. {
  2458. const char* packageSourceTargetName = this->GetPackageSourceTargetName();
  2459. if (!packageSourceTargetName) {
  2460. return;
  2461. }
  2462. auto& mf = this->Makefiles[0];
  2463. std::string configFile =
  2464. cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackSourceConfig.cmake");
  2465. if (!cmSystemTools::FileExists(configFile)) {
  2466. return;
  2467. }
  2468. static const auto reservedTargets = { "package_source" };
  2469. for (auto const& target : reservedTargets) {
  2470. if (!this->CheckCMP0037(target,
  2471. "when CPack source packaging is enabled")) {
  2472. return;
  2473. }
  2474. }
  2475. GlobalTargetInfo gti;
  2476. gti.Name = packageSourceTargetName;
  2477. gti.Message = "Run CPack packaging tool for source...";
  2478. gti.WorkingDir = mf->GetCurrentBinaryDirectory();
  2479. gti.UsesTerminal = true;
  2480. cmCustomCommandLine singleLine;
  2481. singleLine.push_back(cmSystemTools::GetCPackCommand());
  2482. singleLine.push_back("--config");
  2483. singleLine.push_back("./CPackSourceConfig.cmake");
  2484. singleLine.push_back(std::move(configFile));
  2485. gti.CommandLines.push_back(std::move(singleLine));
  2486. targets.push_back(std::move(gti));
  2487. }
  2488. void cmGlobalGenerator::AddGlobalTarget_Test(
  2489. std::vector<GlobalTargetInfo>& targets)
  2490. {
  2491. auto& mf = this->Makefiles[0];
  2492. if (!mf->IsOn("CMAKE_TESTING_ENABLED")) {
  2493. return;
  2494. }
  2495. static const auto reservedTargets = { "test", "RUN_TESTS" };
  2496. for (auto const& target : reservedTargets) {
  2497. if (!this->CheckCMP0037(target, "when CTest testing is enabled")) {
  2498. return;
  2499. }
  2500. }
  2501. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2502. GlobalTargetInfo gti;
  2503. gti.Name = this->GetTestTargetName();
  2504. gti.Message = "Running tests...";
  2505. gti.UsesTerminal = true;
  2506. cmCustomCommandLine singleLine;
  2507. singleLine.push_back(cmSystemTools::GetCTestCommand());
  2508. singleLine.push_back("--force-new-ctest-process");
  2509. cmList args(mf->GetDefinition("CMAKE_CTEST_ARGUMENTS"));
  2510. for (auto const& arg : args) {
  2511. singleLine.push_back(arg);
  2512. }
  2513. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2514. singleLine.push_back("-C");
  2515. singleLine.push_back(cmakeCfgIntDir);
  2516. } else // TODO: This is a hack. Should be something to do with the
  2517. // generator
  2518. {
  2519. singleLine.push_back("$(ARGS)");
  2520. }
  2521. gti.CommandLines.push_back(std::move(singleLine));
  2522. targets.push_back(std::move(gti));
  2523. }
  2524. void cmGlobalGenerator::AddGlobalTarget_EditCache(
  2525. std::vector<GlobalTargetInfo>& targets) const
  2526. {
  2527. const char* editCacheTargetName = this->GetEditCacheTargetName();
  2528. if (!editCacheTargetName) {
  2529. return;
  2530. }
  2531. GlobalTargetInfo gti;
  2532. gti.Name = editCacheTargetName;
  2533. gti.PerConfig = cmTarget::PerConfig::No;
  2534. cmCustomCommandLine singleLine;
  2535. // Use generator preference for the edit_cache rule if it is defined.
  2536. std::string edit_cmd = this->GetEditCacheCommand();
  2537. if (!edit_cmd.empty()) {
  2538. singleLine.push_back(std::move(edit_cmd));
  2539. singleLine.push_back("-S$(CMAKE_SOURCE_DIR)");
  2540. singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
  2541. gti.Message = "Running CMake cache editor...";
  2542. gti.UsesTerminal = true;
  2543. } else {
  2544. singleLine.push_back(cmSystemTools::GetCMakeCommand());
  2545. singleLine.push_back("-E");
  2546. singleLine.push_back("echo");
  2547. singleLine.push_back("No interactive CMake dialog available.");
  2548. gti.Message = "No interactive CMake dialog available...";
  2549. gti.UsesTerminal = false;
  2550. gti.StdPipesUTF8 = true;
  2551. }
  2552. gti.CommandLines.push_back(std::move(singleLine));
  2553. targets.push_back(std::move(gti));
  2554. }
  2555. void cmGlobalGenerator::AddGlobalTarget_RebuildCache(
  2556. std::vector<GlobalTargetInfo>& targets) const
  2557. {
  2558. const char* rebuildCacheTargetName = this->GetRebuildCacheTargetName();
  2559. if (!rebuildCacheTargetName) {
  2560. return;
  2561. }
  2562. GlobalTargetInfo gti;
  2563. gti.Name = rebuildCacheTargetName;
  2564. gti.Message = "Running CMake to regenerate build system...";
  2565. gti.UsesTerminal = true;
  2566. gti.PerConfig = cmTarget::PerConfig::No;
  2567. cmCustomCommandLine singleLine;
  2568. singleLine.push_back(cmSystemTools::GetCMakeCommand());
  2569. singleLine.push_back("--regenerate-during-build");
  2570. singleLine.push_back("-S$(CMAKE_SOURCE_DIR)");
  2571. singleLine.push_back("-B$(CMAKE_BINARY_DIR)");
  2572. gti.CommandLines.push_back(std::move(singleLine));
  2573. gti.StdPipesUTF8 = true;
  2574. targets.push_back(std::move(gti));
  2575. }
  2576. void cmGlobalGenerator::AddGlobalTarget_Install(
  2577. std::vector<GlobalTargetInfo>& targets)
  2578. {
  2579. auto& mf = this->Makefiles[0];
  2580. const char* cmakeCfgIntDir = this->GetCMakeCFGIntDir();
  2581. bool skipInstallRules = mf->IsOn("CMAKE_SKIP_INSTALL_RULES");
  2582. if (this->InstallTargetEnabled && skipInstallRules) {
  2583. this->CMakeInstance->IssueMessage(
  2584. MessageType::WARNING,
  2585. "CMAKE_SKIP_INSTALL_RULES was enabled even though "
  2586. "installation rules have been specified",
  2587. mf->GetBacktrace());
  2588. } else if (this->InstallTargetEnabled && !skipInstallRules) {
  2589. if (!(cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.')) {
  2590. std::set<std::string>* componentsSet = &this->InstallComponents;
  2591. std::ostringstream ostr;
  2592. if (!componentsSet->empty()) {
  2593. ostr << "Available install components are: ";
  2594. ostr << cmWrap('"', *componentsSet, '"', " ");
  2595. } else {
  2596. ostr << "Only default component available";
  2597. }
  2598. GlobalTargetInfo gti;
  2599. gti.Name = "list_install_components";
  2600. gti.Message = ostr.str();
  2601. gti.UsesTerminal = false;
  2602. targets.push_back(std::move(gti));
  2603. }
  2604. std::string cmd = cmSystemTools::GetCMakeCommand();
  2605. GlobalTargetInfo gti;
  2606. gti.Name = this->GetInstallTargetName();
  2607. gti.Message = "Install the project...";
  2608. gti.UsesTerminal = true;
  2609. gti.StdPipesUTF8 = true;
  2610. cmCustomCommandLine singleLine;
  2611. if (this->GetPreinstallTargetName()) {
  2612. gti.Depends.emplace_back(this->GetPreinstallTargetName());
  2613. } else {
  2614. cmValue noall = mf->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
  2615. if (cmIsOff(noall)) {
  2616. gti.Depends.emplace_back(this->GetAllTargetName());
  2617. }
  2618. }
  2619. if (mf->GetDefinition("CMake_BINARY_DIR") &&
  2620. !mf->IsOn("CMAKE_CROSSCOMPILING")) {
  2621. // We are building CMake itself. We cannot use the original
  2622. // executable to install over itself. The generator will
  2623. // automatically convert this name to the build-time location.
  2624. cmd = "cmake";
  2625. }
  2626. singleLine.push_back(cmd);
  2627. if (cmNonempty(cmakeCfgIntDir) && cmakeCfgIntDir[0] != '.') {
  2628. std::string cfgArg = "-DBUILD_TYPE=";
  2629. bool useEPN = this->UseEffectivePlatformName(mf.get());
  2630. if (useEPN) {
  2631. cfgArg += "$(CONFIGURATION)";
  2632. singleLine.push_back(cfgArg);
  2633. cfgArg = "-DEFFECTIVE_PLATFORM_NAME=$(EFFECTIVE_PLATFORM_NAME)";
  2634. } else {
  2635. cfgArg += this->GetCMakeCFGIntDir();
  2636. }
  2637. singleLine.push_back(cfgArg);
  2638. }
  2639. singleLine.push_back("-P");
  2640. singleLine.push_back("cmake_install.cmake");
  2641. gti.CommandLines.push_back(singleLine);
  2642. targets.push_back(gti);
  2643. // install_local
  2644. if (const char* install_local = this->GetInstallLocalTargetName()) {
  2645. gti.Name = install_local;
  2646. gti.Message = "Installing only the local directory...";
  2647. gti.UsesTerminal = true;
  2648. gti.CommandLines.clear();
  2649. cmCustomCommandLine localCmdLine = singleLine;
  2650. localCmdLine.insert(localCmdLine.begin() + 1,
  2651. "-DCMAKE_INSTALL_LOCAL_ONLY=1");
  2652. gti.CommandLines.push_back(std::move(localCmdLine));
  2653. targets.push_back(gti);
  2654. }
  2655. // install_strip
  2656. const char* install_strip = this->GetInstallStripTargetName();
  2657. if ((install_strip != nullptr) && (mf->IsSet("CMAKE_STRIP"))) {
  2658. gti.Name = install_strip;
  2659. gti.Message = "Installing the project stripped...";
  2660. gti.UsesTerminal = true;
  2661. gti.CommandLines.clear();
  2662. cmCustomCommandLine stripCmdLine = singleLine;
  2663. stripCmdLine.insert(stripCmdLine.begin() + 1,
  2664. "-DCMAKE_INSTALL_DO_STRIP=1");
  2665. gti.CommandLines.push_back(std::move(stripCmdLine));
  2666. targets.push_back(gti);
  2667. }
  2668. }
  2669. }
  2670. std::string cmGlobalGenerator::GetPredefinedTargetsFolder() const
  2671. {
  2672. cmValue prop = this->GetCMakeInstance()->GetState()->GetGlobalProperty(
  2673. "PREDEFINED_TARGETS_FOLDER");
  2674. if (prop) {
  2675. return *prop;
  2676. }
  2677. return "CMakePredefinedTargets";
  2678. }
  2679. bool cmGlobalGenerator::UseFolderProperty() const
  2680. {
  2681. const cmValue prop =
  2682. this->GetCMakeInstance()->GetState()->GetGlobalProperty("USE_FOLDERS");
  2683. // If this property is defined, let the setter turn this on or off.
  2684. if (prop) {
  2685. return cmIsOn(*prop);
  2686. }
  2687. // If CMP0143 is NEW `treat` "USE_FOLDERS" as ON. Otherwise `treat` it as OFF
  2688. assert(!this->Makefiles.empty());
  2689. return (this->Makefiles[0]->GetPolicyStatus(cmPolicies::CMP0143) ==
  2690. cmPolicies::NEW);
  2691. }
  2692. void cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti,
  2693. cmMakefile* mf)
  2694. {
  2695. // Package
  2696. auto tb =
  2697. mf->CreateNewTarget(gti.Name, cmStateEnums::GLOBAL_TARGET, gti.PerConfig);
  2698. // Do nothing if gti.Name is already used
  2699. if (!tb.second) {
  2700. return;
  2701. }
  2702. cmTarget& target = tb.first;
  2703. target.SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  2704. // Store the custom command in the target.
  2705. cmCustomCommand cc;
  2706. cc.SetCommandLines(gti.CommandLines);
  2707. cc.SetWorkingDirectory(gti.WorkingDir.c_str());
  2708. cc.SetStdPipesUTF8(gti.StdPipesUTF8);
  2709. cc.SetUsesTerminal(gti.UsesTerminal);
  2710. target.AddPostBuildCommand(std::move(cc));
  2711. if (!gti.Message.empty()) {
  2712. target.SetProperty("EchoString", gti.Message);
  2713. }
  2714. for (std::string const& d : gti.Depends) {
  2715. target.AddUtility(d, false);
  2716. }
  2717. // Organize in the "predefined targets" folder:
  2718. //
  2719. if (this->UseFolderProperty()) {
  2720. target.SetProperty("FOLDER", this->GetPredefinedTargetsFolder());
  2721. }
  2722. }
  2723. std::string cmGlobalGenerator::GenerateRuleFile(
  2724. std::string const& output) const
  2725. {
  2726. std::string ruleFile = cmStrCat(output, ".rule");
  2727. const char* dir = this->GetCMakeCFGIntDir();
  2728. if (dir && dir[0] == '$') {
  2729. cmSystemTools::ReplaceString(ruleFile, dir, "/CMakeFiles");
  2730. }
  2731. return ruleFile;
  2732. }
  2733. bool cmGlobalGenerator::ShouldStripResourcePath(cmMakefile* mf) const
  2734. {
  2735. return mf->PlatformIsAppleEmbedded();
  2736. }
  2737. std::string cmGlobalGenerator::GetSharedLibFlagsForLanguage(
  2738. std::string const& l) const
  2739. {
  2740. auto const it = this->LanguageToOriginalSharedLibFlags.find(l);
  2741. if (it != this->LanguageToOriginalSharedLibFlags.end()) {
  2742. return it->second;
  2743. }
  2744. return "";
  2745. }
  2746. void cmGlobalGenerator::AppendDirectoryForConfig(const std::string& /*unused*/,
  2747. const std::string& /*unused*/,
  2748. const std::string& /*unused*/,
  2749. std::string& /*unused*/)
  2750. {
  2751. // Subclasses that support multiple configurations should implement
  2752. // this method to append the subdirectory for the given build
  2753. // configuration.
  2754. }
  2755. cmGlobalGenerator::TargetDependSet const&
  2756. cmGlobalGenerator::GetTargetDirectDepends(cmGeneratorTarget const* target)
  2757. {
  2758. return this->TargetDependencies[target];
  2759. }
  2760. bool cmGlobalGenerator::TargetOrderIndexLess(cmGeneratorTarget const* l,
  2761. cmGeneratorTarget const* r) const
  2762. {
  2763. return this->TargetOrderIndex.at(l) < this->TargetOrderIndex.at(r);
  2764. }
  2765. bool cmGlobalGenerator::IsReservedTarget(std::string const& name)
  2766. {
  2767. // The following is a list of targets reserved
  2768. // by one or more of the cmake generators.
  2769. // Adding additional targets to this list will require a policy!
  2770. const char* reservedTargets[] = { "all", "ALL_BUILD", "help",
  2771. "install", "INSTALL", "preinstall",
  2772. "clean", "edit_cache", "rebuild_cache",
  2773. "ZERO_CHECK" };
  2774. return cm::contains(reservedTargets, name);
  2775. }
  2776. void cmGlobalGenerator::SetExternalMakefileProjectGenerator(
  2777. std::unique_ptr<cmExternalMakefileProjectGenerator> extraGenerator)
  2778. {
  2779. this->ExtraGenerator = std::move(extraGenerator);
  2780. if (this->ExtraGenerator) {
  2781. this->ExtraGenerator->SetGlobalGenerator(this);
  2782. }
  2783. }
  2784. std::string cmGlobalGenerator::GetExtraGeneratorName() const
  2785. {
  2786. return this->ExtraGenerator ? this->ExtraGenerator->GetName()
  2787. : std::string();
  2788. }
  2789. void cmGlobalGenerator::FileReplacedDuringGenerate(const std::string& filename)
  2790. {
  2791. this->FilesReplacedDuringGenerate.push_back(filename);
  2792. }
  2793. void cmGlobalGenerator::GetFilesReplacedDuringGenerate(
  2794. std::vector<std::string>& filenames)
  2795. {
  2796. filenames.clear();
  2797. std::copy(this->FilesReplacedDuringGenerate.begin(),
  2798. this->FilesReplacedDuringGenerate.end(),
  2799. std::back_inserter(filenames));
  2800. }
  2801. void cmGlobalGenerator::GetTargetSets(
  2802. TargetDependSet& projectTargets, TargetDependSet& originalTargets,
  2803. cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
  2804. {
  2805. // loop over all local generators
  2806. for (auto* generator : generators) {
  2807. // check to make sure generator is not excluded
  2808. if (this->IsExcluded(root, generator)) {
  2809. continue;
  2810. }
  2811. // loop over all the generator targets in the makefile
  2812. for (const auto& target : generator->GetGeneratorTargets()) {
  2813. if (this->IsRootOnlyTarget(target.get()) &&
  2814. target->GetLocalGenerator() != root) {
  2815. continue;
  2816. }
  2817. // put the target in the set of original targets
  2818. originalTargets.insert(target.get());
  2819. // Get the set of targets that depend on target
  2820. this->AddTargetDepends(target.get(), projectTargets);
  2821. }
  2822. }
  2823. }
  2824. bool cmGlobalGenerator::IsRootOnlyTarget(cmGeneratorTarget* target) const
  2825. {
  2826. return (target->GetType() == cmStateEnums::GLOBAL_TARGET ||
  2827. target->GetName() == this->GetAllTargetName());
  2828. }
  2829. void cmGlobalGenerator::AddTargetDepends(cmGeneratorTarget const* target,
  2830. TargetDependSet& projectTargets)
  2831. {
  2832. // add the target itself
  2833. if (projectTargets.insert(target).second) {
  2834. // This is the first time we have encountered the target.
  2835. // Recursively follow its dependencies.
  2836. for (auto const& t : this->GetTargetDirectDepends(target)) {
  2837. this->AddTargetDepends(t, projectTargets);
  2838. }
  2839. }
  2840. }
  2841. void cmGlobalGenerator::AddToManifest(std::string const& f)
  2842. {
  2843. // Add to the content listing for the file's directory.
  2844. std::string dir = cmSystemTools::GetFilenamePath(f);
  2845. std::string file = cmSystemTools::GetFilenameName(f);
  2846. DirectoryContent& dc = this->DirectoryContentMap[dir];
  2847. dc.Generated.insert(file);
  2848. dc.All.insert(file);
  2849. }
  2850. std::set<std::string> const& cmGlobalGenerator::GetDirectoryContent(
  2851. std::string const& dir, bool needDisk)
  2852. {
  2853. DirectoryContent& dc = this->DirectoryContentMap[dir];
  2854. if (needDisk) {
  2855. long mt = cmSystemTools::ModifiedTime(dir);
  2856. if (mt != dc.LastDiskTime) {
  2857. // Reset to non-loaded directory content.
  2858. dc.All = dc.Generated;
  2859. // Load the directory content from disk.
  2860. cmsys::Directory d;
  2861. if (d.Load(dir)) {
  2862. unsigned long n = d.GetNumberOfFiles();
  2863. for (unsigned long i = 0; i < n; ++i) {
  2864. const char* f = d.GetFile(i);
  2865. if (strcmp(f, ".") != 0 && strcmp(f, "..") != 0) {
  2866. dc.All.insert(f);
  2867. }
  2868. }
  2869. }
  2870. dc.LastDiskTime = mt;
  2871. }
  2872. }
  2873. return dc.All;
  2874. }
  2875. void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs,
  2876. std::string const& content)
  2877. {
  2878. #if !defined(CMAKE_BOOTSTRAP)
  2879. // Ignore if there are no outputs.
  2880. if (outputs.empty()) {
  2881. return;
  2882. }
  2883. // Compute a hash of the rule.
  2884. RuleHash hash;
  2885. {
  2886. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2887. std::string const md5_hex = md5.HashString(content);
  2888. memcpy(hash.Data, md5_hex.c_str(), 32);
  2889. }
  2890. // Shorten the output name (in expected use case).
  2891. std::string fname =
  2892. this->LocalGenerators[0]->MaybeRelativeToTopBinDir(outputs[0]);
  2893. // Associate the hash with this output.
  2894. this->RuleHashes[fname] = hash;
  2895. #else
  2896. (void)outputs;
  2897. (void)content;
  2898. #endif
  2899. }
  2900. void cmGlobalGenerator::CheckRuleHashes()
  2901. {
  2902. #if !defined(CMAKE_BOOTSTRAP)
  2903. std::string home = this->GetCMakeInstance()->GetHomeOutputDirectory();
  2904. std::string pfile = cmStrCat(home, "/CMakeFiles/CMakeRuleHashes.txt");
  2905. this->CheckRuleHashes(pfile, home);
  2906. this->WriteRuleHashes(pfile);
  2907. #endif
  2908. }
  2909. void cmGlobalGenerator::CheckRuleHashes(std::string const& pfile,
  2910. std::string const& home)
  2911. {
  2912. #if defined(_WIN32) || defined(__CYGWIN__)
  2913. cmsys::ifstream fin(pfile.c_str(), std::ios::in | std::ios::binary);
  2914. #else
  2915. cmsys::ifstream fin(pfile.c_str());
  2916. #endif
  2917. if (!fin) {
  2918. return;
  2919. }
  2920. std::string line;
  2921. std::string fname;
  2922. while (cmSystemTools::GetLineFromStream(fin, line)) {
  2923. // Line format is a 32-byte hex string followed by a space
  2924. // followed by a file name (with no escaping).
  2925. // Skip blank and comment lines.
  2926. if (line.size() < 34 || line[0] == '#') {
  2927. continue;
  2928. }
  2929. // Get the filename.
  2930. fname = line.substr(33);
  2931. // Look for a hash for this file's rule.
  2932. auto const rhi = this->RuleHashes.find(fname);
  2933. if (rhi != this->RuleHashes.end()) {
  2934. // Compare the rule hash in the file to that we were given.
  2935. if (strncmp(line.c_str(), rhi->second.Data, 32) != 0) {
  2936. // The rule has changed. Delete the output so it will be
  2937. // built again.
  2938. fname = cmSystemTools::CollapseFullPath(fname, home);
  2939. cmSystemTools::RemoveFile(fname);
  2940. }
  2941. } else {
  2942. // We have no hash for a rule previously listed. This may be a
  2943. // case where a user has turned off a build option and might
  2944. // want to turn it back on later, so do not delete the file.
  2945. // Instead, we keep the rule hash as long as the file exists so
  2946. // that if the feature is turned back on and the rule has
  2947. // changed the file is still rebuilt.
  2948. std::string fpath = cmSystemTools::CollapseFullPath(fname, home);
  2949. if (cmSystemTools::FileExists(fpath)) {
  2950. RuleHash hash;
  2951. memcpy(hash.Data, line.c_str(), 32);
  2952. this->RuleHashes[fname] = hash;
  2953. }
  2954. }
  2955. }
  2956. }
  2957. void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile)
  2958. {
  2959. // Now generate a new persistence file with the current hashes.
  2960. if (this->RuleHashes.empty()) {
  2961. cmSystemTools::RemoveFile(pfile);
  2962. } else {
  2963. cmGeneratedFileStream fout(pfile);
  2964. fout << "# Hashes of file build rules.\n";
  2965. for (auto const& rh : this->RuleHashes) {
  2966. fout.write(rh.second.Data, 32);
  2967. fout << " " << rh.first << "\n";
  2968. }
  2969. }
  2970. }
  2971. void cmGlobalGenerator::WriteSummary()
  2972. {
  2973. // Record all target directories in a central location.
  2974. std::string fname = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  2975. "/CMakeFiles/TargetDirectories.txt");
  2976. cmGeneratedFileStream fout(fname);
  2977. for (const auto& lg : this->LocalGenerators) {
  2978. for (const auto& tgt : lg->GetGeneratorTargets()) {
  2979. if (!tgt->IsInBuildSystem()) {
  2980. continue;
  2981. }
  2982. this->WriteSummary(tgt.get());
  2983. fout << tgt->GetSupportDirectory() << "\n";
  2984. }
  2985. }
  2986. }
  2987. void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
  2988. {
  2989. // Place the labels file in a per-target support directory.
  2990. std::string dir = target->GetSupportDirectory();
  2991. std::string file = cmStrCat(dir, "/Labels.txt");
  2992. std::string json_file = dir + "/Labels.json";
  2993. #ifndef CMAKE_BOOTSTRAP
  2994. // Check whether labels are enabled for this target.
  2995. cmValue targetLabels = target->GetProperty("LABELS");
  2996. cmValue directoryLabels =
  2997. target->Target->GetMakefile()->GetProperty("LABELS");
  2998. cmValue cmakeDirectoryLabels =
  2999. target->Target->GetMakefile()->GetDefinition("CMAKE_DIRECTORY_LABELS");
  3000. if (targetLabels || directoryLabels || cmakeDirectoryLabels) {
  3001. Json::Value lj_root(Json::objectValue);
  3002. Json::Value& lj_target = lj_root["target"] = Json::objectValue;
  3003. lj_target["name"] = target->GetName();
  3004. Json::Value& lj_target_labels = lj_target["labels"] = Json::arrayValue;
  3005. Json::Value& lj_sources = lj_root["sources"] = Json::arrayValue;
  3006. cmSystemTools::MakeDirectory(dir);
  3007. cmGeneratedFileStream fout(file);
  3008. cmList labels;
  3009. // List the target-wide labels. All sources in the target get
  3010. // these labels.
  3011. if (targetLabels) {
  3012. labels.assign(*targetLabels);
  3013. if (!labels.empty()) {
  3014. fout << "# Target labels\n";
  3015. for (std::string const& l : labels) {
  3016. fout << " " << l << "\n";
  3017. lj_target_labels.append(l);
  3018. }
  3019. }
  3020. }
  3021. // List directory labels
  3022. cmList directoryLabelsList;
  3023. cmList cmakeDirectoryLabelsList;
  3024. if (directoryLabels) {
  3025. directoryLabelsList.assign(*directoryLabels);
  3026. }
  3027. if (cmakeDirectoryLabels) {
  3028. cmakeDirectoryLabelsList.assign(*cmakeDirectoryLabels);
  3029. }
  3030. if (!directoryLabelsList.empty() || !cmakeDirectoryLabelsList.empty()) {
  3031. fout << "# Directory labels\n";
  3032. }
  3033. for (auto const& li : directoryLabelsList) {
  3034. fout << " " << li << "\n";
  3035. lj_target_labels.append(li);
  3036. }
  3037. for (auto const& li : cmakeDirectoryLabelsList) {
  3038. fout << " " << li << "\n";
  3039. lj_target_labels.append(li);
  3040. }
  3041. // List the source files with any per-source labels.
  3042. fout << "# Source files and their labels\n";
  3043. std::vector<cmSourceFile*> sources;
  3044. std::vector<std::string> const& configs =
  3045. target->Target->GetMakefile()->GetGeneratorConfigs(
  3046. cmMakefile::IncludeEmptyConfig);
  3047. for (std::string const& c : configs) {
  3048. target->GetSourceFiles(sources, c);
  3049. }
  3050. auto const sourcesEnd = cmRemoveDuplicates(sources);
  3051. for (cmSourceFile* sf : cmMakeRange(sources.cbegin(), sourcesEnd)) {
  3052. Json::Value& lj_source = lj_sources.append(Json::objectValue);
  3053. std::string const& sfp = sf->ResolveFullPath();
  3054. fout << sfp << "\n";
  3055. lj_source["file"] = sfp;
  3056. if (cmValue svalue = sf->GetProperty("LABELS")) {
  3057. Json::Value& lj_source_labels = lj_source["labels"] = Json::arrayValue;
  3058. labels.assign(*svalue);
  3059. for (auto const& label : labels) {
  3060. fout << " " << label << "\n";
  3061. lj_source_labels.append(label);
  3062. }
  3063. }
  3064. }
  3065. cmGeneratedFileStream json_fout(json_file);
  3066. json_fout << lj_root;
  3067. } else
  3068. #endif
  3069. {
  3070. cmSystemTools::RemoveFile(file);
  3071. cmSystemTools::RemoveFile(json_file);
  3072. }
  3073. }
  3074. // static
  3075. std::string cmGlobalGenerator::EscapeJSON(const std::string& s)
  3076. {
  3077. std::string result;
  3078. result.reserve(s.size());
  3079. for (char i : s) {
  3080. switch (i) {
  3081. case '"':
  3082. case '\\':
  3083. result += '\\';
  3084. result += i;
  3085. break;
  3086. case '\n':
  3087. result += "\\n";
  3088. break;
  3089. case '\t':
  3090. result += "\\t";
  3091. break;
  3092. default:
  3093. result += i;
  3094. }
  3095. }
  3096. return result;
  3097. }
  3098. void cmGlobalGenerator::SetFilenameTargetDepends(
  3099. cmSourceFile* sf, std::set<cmGeneratorTarget const*> const& tgts)
  3100. {
  3101. this->FilenameTargetDepends[sf] = tgts;
  3102. }
  3103. std::set<cmGeneratorTarget const*> const&
  3104. cmGlobalGenerator::GetFilenameTargetDepends(cmSourceFile* sf) const
  3105. {
  3106. return this->FilenameTargetDepends[sf];
  3107. }
  3108. const std::string& cmGlobalGenerator::GetRealPath(const std::string& dir)
  3109. {
  3110. auto i = this->RealPaths.lower_bound(dir);
  3111. if (i == this->RealPaths.end() ||
  3112. this->RealPaths.key_comp()(dir, i->first)) {
  3113. i = this->RealPaths.emplace_hint(i, dir, cmSystemTools::GetRealPath(dir));
  3114. }
  3115. return i->second;
  3116. }
  3117. std::string cmGlobalGenerator::NewDeferId()
  3118. {
  3119. return cmStrCat("__"_s, std::to_string(this->NextDeferId++));
  3120. }
  3121. void cmGlobalGenerator::ProcessEvaluationFiles()
  3122. {
  3123. std::vector<std::string> generatedFiles;
  3124. for (auto& localGen : this->LocalGenerators) {
  3125. localGen->ProcessEvaluationFiles(generatedFiles);
  3126. }
  3127. }
  3128. std::string cmGlobalGenerator::ExpandCFGIntDir(
  3129. const std::string& str, const std::string& /*config*/) const
  3130. {
  3131. return str;
  3132. }
  3133. bool cmGlobalGenerator::GenerateCPackPropertiesFile()
  3134. {
  3135. cmake::InstalledFilesMap const& installedFiles =
  3136. this->CMakeInstance->GetInstalledFiles();
  3137. const auto& lg = this->LocalGenerators[0];
  3138. cmMakefile* mf = lg->GetMakefile();
  3139. std::vector<std::string> configs =
  3140. mf->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  3141. std::string config = mf->GetDefaultConfiguration();
  3142. std::string path = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(),
  3143. "/CPackProperties.cmake");
  3144. if (!cmSystemTools::FileExists(path) && installedFiles.empty()) {
  3145. return true;
  3146. }
  3147. cmGeneratedFileStream file(path);
  3148. file << "# CPack properties\n";
  3149. for (auto const& i : installedFiles) {
  3150. cmInstalledFile const& installedFile = i.second;
  3151. cmCPackPropertiesGenerator cpackPropertiesGenerator(
  3152. lg.get(), installedFile, configs);
  3153. cpackPropertiesGenerator.Generate(file, config, configs);
  3154. }
  3155. return true;
  3156. }
  3157. cmInstallRuntimeDependencySet*
  3158. cmGlobalGenerator::CreateAnonymousRuntimeDependencySet()
  3159. {
  3160. auto set = cm::make_unique<cmInstallRuntimeDependencySet>();
  3161. auto* retval = set.get();
  3162. this->RuntimeDependencySets.push_back(std::move(set));
  3163. return retval;
  3164. }
  3165. cmInstallRuntimeDependencySet* cmGlobalGenerator::GetNamedRuntimeDependencySet(
  3166. const std::string& name)
  3167. {
  3168. auto it = this->RuntimeDependencySetsByName.find(name);
  3169. if (it == this->RuntimeDependencySetsByName.end()) {
  3170. auto set = cm::make_unique<cmInstallRuntimeDependencySet>(name);
  3171. it =
  3172. this->RuntimeDependencySetsByName.insert(std::make_pair(name, set.get()))
  3173. .first;
  3174. this->RuntimeDependencySets.push_back(std::move(set));
  3175. }
  3176. return it->second;
  3177. }
  3178. cmGlobalGenerator::StripCommandStyle cmGlobalGenerator::GetStripCommandStyle(
  3179. std::string const& strip)
  3180. {
  3181. #ifdef __APPLE__
  3182. auto i = this->StripCommandStyleMap.find(strip);
  3183. if (i == this->StripCommandStyleMap.end()) {
  3184. StripCommandStyle style = StripCommandStyle::Default;
  3185. // Try running strip tool with Apple-specific options.
  3186. std::vector<std::string> cmd{ strip, "-u", "-r" };
  3187. std::string out;
  3188. std::string err;
  3189. int ret;
  3190. if (cmSystemTools::RunSingleCommand(cmd, &out, &err, &ret, nullptr,
  3191. cmSystemTools::OUTPUT_NONE) &&
  3192. // Check for Apple-specific output.
  3193. ret != 0 && cmHasLiteralPrefix(err, "fatal error: /") &&
  3194. err.find("/usr/bin/strip: no files specified") != std::string::npos) {
  3195. style = StripCommandStyle::Apple;
  3196. }
  3197. i = this->StripCommandStyleMap.emplace(strip, style).first;
  3198. }
  3199. return i->second;
  3200. #else
  3201. static_cast<void>(strip);
  3202. return StripCommandStyle::Default;
  3203. #endif
  3204. }