cmGlobalGenerator.cxx 101 KB

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