cmGlobalGenerator.cxx 131 KB

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