cmGlobalGenerator.cxx 130 KB

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