cmake.cxx 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293
  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 "cmake.h"
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <initializer_list>
  9. #include <iostream>
  10. #include <sstream>
  11. #include <stdexcept>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  17. # include <cm/iterator>
  18. #endif
  19. #include <cmext/algorithm>
  20. #include <cmext/string_view>
  21. #include "cmsys/FStream.hxx"
  22. #include "cmsys/Glob.hxx"
  23. #include "cmsys/RegularExpression.hxx"
  24. #include "cm_sys_stat.h"
  25. #include "cmCMakePresetsFile.h"
  26. #include "cmCommands.h"
  27. #include "cmDocumentation.h"
  28. #include "cmDocumentationEntry.h"
  29. #include "cmDocumentationFormatter.h"
  30. #include "cmDuration.h"
  31. #include "cmExternalMakefileProjectGenerator.h"
  32. #include "cmFileTimeCache.h"
  33. #include "cmGeneratorTarget.h"
  34. #include "cmGlobalGenerator.h"
  35. #include "cmGlobalGeneratorFactory.h"
  36. #include "cmLinkLineComputer.h"
  37. #include "cmLocalGenerator.h"
  38. #include "cmMakefile.h"
  39. #if !defined(CMAKE_BOOTSTRAP)
  40. # include "cmMakefileProfilingData.h"
  41. #endif
  42. #include "cmMessenger.h"
  43. #include "cmState.h"
  44. #include "cmStateDirectory.h"
  45. #include "cmStringAlgorithms.h"
  46. #include "cmSystemTools.h"
  47. #include "cmTarget.h"
  48. #include "cmTargetLinkLibraryType.h"
  49. #include "cmUtils.hxx"
  50. #include "cmVersionConfig.h"
  51. #include "cmWorkingDirectory.h"
  52. #if !defined(CMAKE_BOOTSTRAP)
  53. # include <unordered_map>
  54. # include <cm3p/json/writer.h>
  55. # include "cmFileAPI.h"
  56. # include "cmGraphVizWriter.h"
  57. # include "cmVariableWatch.h"
  58. #endif
  59. #if defined(__MINGW32__) && defined(CMAKE_BOOTSTRAP)
  60. # define CMAKE_BOOT_MINGW
  61. #endif
  62. // include the generator
  63. #if defined(_WIN32) && !defined(__CYGWIN__)
  64. # if !defined(CMAKE_BOOT_MINGW)
  65. # include <cmext/memory>
  66. # include "cmGlobalBorlandMakefileGenerator.h"
  67. # include "cmGlobalJOMMakefileGenerator.h"
  68. # include "cmGlobalNMakeMakefileGenerator.h"
  69. # include "cmGlobalVisualStudio10Generator.h"
  70. # include "cmGlobalVisualStudio11Generator.h"
  71. # include "cmGlobalVisualStudio12Generator.h"
  72. # include "cmGlobalVisualStudio14Generator.h"
  73. # include "cmGlobalVisualStudio9Generator.h"
  74. # include "cmGlobalVisualStudioVersionedGenerator.h"
  75. # include "cmVSSetupHelper.h"
  76. # define CMAKE_HAVE_VS_GENERATORS
  77. # endif
  78. # include "cmGlobalMSYSMakefileGenerator.h"
  79. # include "cmGlobalMinGWMakefileGenerator.h"
  80. #else
  81. #endif
  82. #if defined(CMAKE_USE_WMAKE)
  83. # include "cmGlobalWatcomWMakeGenerator.h"
  84. #endif
  85. #if !defined(CMAKE_BOOTSTRAP)
  86. # include "cmGlobalNinjaGenerator.h"
  87. # include "cmGlobalUnixMakefileGenerator3.h"
  88. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  89. # include "cmGlobalUnixMakefileGenerator3.h"
  90. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  91. # include "cmGlobalNinjaGenerator.h"
  92. #endif
  93. #if !defined(CMAKE_BOOTSTRAP)
  94. # include "cmExtraCodeBlocksGenerator.h"
  95. # include "cmExtraCodeLiteGenerator.h"
  96. # include "cmExtraEclipseCDT4Generator.h"
  97. # include "cmExtraKateGenerator.h"
  98. # include "cmExtraSublimeTextGenerator.h"
  99. #endif
  100. #if defined(__linux__) || defined(_WIN32)
  101. # include "cmGlobalGhsMultiGenerator.h"
  102. #endif
  103. #if defined(__APPLE__)
  104. # if !defined(CMAKE_BOOTSTRAP)
  105. # include "cmGlobalXCodeGenerator.h"
  106. # define CMAKE_USE_XCODE 1
  107. # endif
  108. # include <sys/resource.h>
  109. # include <sys/time.h>
  110. #endif
  111. namespace {
  112. #if !defined(CMAKE_BOOTSTRAP)
  113. using JsonValueMapType = std::unordered_map<std::string, Json::Value>;
  114. #endif
  115. } // namespace
  116. static bool cmakeCheckStampFile(const std::string& stampName);
  117. static bool cmakeCheckStampList(const std::string& stampList);
  118. #ifndef CMAKE_BOOTSTRAP
  119. static void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  120. void* ctx, const char* /*unused*/,
  121. const cmMakefile* /*unused*/)
  122. {
  123. cmake* cm = reinterpret_cast<cmake*>(ctx);
  124. cm->MarkCliAsUsed(variable);
  125. }
  126. #endif
  127. cmake::cmake(Role role, cmState::Mode mode)
  128. : FileTimeCache(cm::make_unique<cmFileTimeCache>())
  129. #ifndef CMAKE_BOOTSTRAP
  130. , VariableWatch(cm::make_unique<cmVariableWatch>())
  131. #endif
  132. , State(cm::make_unique<cmState>())
  133. , Messenger(cm::make_unique<cmMessenger>())
  134. {
  135. this->TraceFile.close();
  136. this->State->SetMode(mode);
  137. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  138. #ifdef __APPLE__
  139. struct rlimit rlp;
  140. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  141. if (rlp.rlim_cur != rlp.rlim_max) {
  142. rlp.rlim_cur = rlp.rlim_max;
  143. setrlimit(RLIMIT_STACK, &rlp);
  144. }
  145. }
  146. #endif
  147. this->AddDefaultGenerators();
  148. this->AddDefaultExtraGenerators();
  149. if (role == RoleScript || role == RoleProject) {
  150. this->AddScriptingCommands();
  151. }
  152. if (role == RoleProject) {
  153. this->AddProjectCommands();
  154. }
  155. if (mode == cmState::Project) {
  156. this->LoadEnvironmentPresets();
  157. }
  158. // Make sure we can capture the build tool output.
  159. cmSystemTools::EnableVSConsoleOutput();
  160. // Set up a list of source and header extensions.
  161. // These are used to find files when the extension is not given.
  162. {
  163. auto setupExts = [](FileExtensions& exts,
  164. std::initializer_list<cm::string_view> extList) {
  165. // Fill ordered vector
  166. exts.ordered.reserve(extList.size());
  167. for (cm::string_view ext : extList) {
  168. exts.ordered.emplace_back(ext);
  169. };
  170. // Fill unordered set
  171. exts.unordered.insert(exts.ordered.begin(), exts.ordered.end());
  172. };
  173. // The "c" extension MUST precede the "C" extension.
  174. setupExts(this->CLikeSourceFileExtensions,
  175. { "c", "C", "c++", "cc", "cpp", "cxx", "cu", "m", "M", "mm" });
  176. setupExts(this->HeaderFileExtensions,
  177. { "h", "hh", "h++", "hm", "hpp", "hxx", "in", "txx" });
  178. setupExts(this->CudaFileExtensions, { "cu" });
  179. setupExts(this->FortranFileExtensions,
  180. { "f", "F", "for", "f77", "f90", "f95", "f03" });
  181. setupExts(this->ISPCFileExtensions, { "ispc" });
  182. }
  183. }
  184. cmake::~cmake() = default;
  185. #if !defined(CMAKE_BOOTSTRAP)
  186. Json::Value cmake::ReportVersionJson() const
  187. {
  188. Json::Value version = Json::objectValue;
  189. version["string"] = CMake_VERSION;
  190. version["major"] = CMake_VERSION_MAJOR;
  191. version["minor"] = CMake_VERSION_MINOR;
  192. version["suffix"] = CMake_VERSION_SUFFIX;
  193. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  194. version["patch"] = CMake_VERSION_PATCH;
  195. return version;
  196. }
  197. Json::Value cmake::ReportCapabilitiesJson() const
  198. {
  199. Json::Value obj = Json::objectValue;
  200. // Version information:
  201. obj["version"] = this->ReportVersionJson();
  202. // Generators:
  203. std::vector<cmake::GeneratorInfo> generatorInfoList;
  204. this->GetRegisteredGenerators(generatorInfoList);
  205. JsonValueMapType generatorMap;
  206. for (cmake::GeneratorInfo const& gi : generatorInfoList) {
  207. if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
  208. // only
  209. continue;
  210. }
  211. if (gi.extraName.empty()) {
  212. Json::Value gen = Json::objectValue;
  213. gen["name"] = gi.name;
  214. gen["toolsetSupport"] = gi.supportsToolset;
  215. gen["platformSupport"] = gi.supportsPlatform;
  216. gen["extraGenerators"] = Json::arrayValue;
  217. generatorMap[gi.name] = gen;
  218. } else {
  219. Json::Value& gen = generatorMap[gi.baseName];
  220. gen["extraGenerators"].append(gi.extraName);
  221. }
  222. }
  223. Json::Value generators = Json::arrayValue;
  224. for (auto const& i : generatorMap) {
  225. generators.append(i.second);
  226. }
  227. obj["generators"] = generators;
  228. obj["fileApi"] = cmFileAPI::ReportCapabilities();
  229. obj["serverMode"] = false;
  230. return obj;
  231. }
  232. #endif
  233. std::string cmake::ReportCapabilities() const
  234. {
  235. std::string result;
  236. #if !defined(CMAKE_BOOTSTRAP)
  237. Json::FastWriter writer;
  238. result = writer.write(this->ReportCapabilitiesJson());
  239. #else
  240. result = "Not supported";
  241. #endif
  242. return result;
  243. }
  244. void cmake::CleanupCommandsAndMacros()
  245. {
  246. this->CurrentSnapshot = this->State->Reset();
  247. this->State->RemoveUserDefinedCommands();
  248. this->CurrentSnapshot.SetDefaultDefinitions();
  249. }
  250. #ifndef CMAKE_BOOTSTRAP
  251. void cmake::SetWarningFromPreset(const std::string& name,
  252. const cm::optional<bool>& warning,
  253. const cm::optional<bool>& error)
  254. {
  255. if (warning) {
  256. if (*warning) {
  257. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  258. } else {
  259. this->DiagLevels[name] = DIAG_IGNORE;
  260. }
  261. }
  262. if (error) {
  263. if (*error) {
  264. this->DiagLevels[name] = DIAG_ERROR;
  265. } else {
  266. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  267. }
  268. }
  269. }
  270. void cmake::ProcessPresetVariables()
  271. {
  272. for (auto const& var : this->UnprocessedPresetVariables) {
  273. if (!var.second) {
  274. continue;
  275. }
  276. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  277. if (!var.second->Type.empty()) {
  278. type = cmState::StringToCacheEntryType(var.second->Type);
  279. }
  280. this->ProcessCacheArg(var.first, var.second->Value, type);
  281. }
  282. }
  283. void cmake::PrintPresetVariables()
  284. {
  285. bool first = true;
  286. for (auto const& var : this->UnprocessedPresetVariables) {
  287. if (!var.second) {
  288. continue;
  289. }
  290. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  291. if (!var.second->Type.empty()) {
  292. type = cmState::StringToCacheEntryType(var.second->Type);
  293. }
  294. if (first) {
  295. std::cout << "Preset CMake variables:\n\n";
  296. first = false;
  297. }
  298. std::cout << " " << var.first;
  299. if (type != cmStateEnums::UNINITIALIZED) {
  300. std::cout << ':' << cmState::CacheEntryTypeToString(type);
  301. }
  302. std::cout << "=\"" << var.second->Value << "\"\n";
  303. }
  304. if (!first) {
  305. std::cout << '\n';
  306. }
  307. this->UnprocessedPresetVariables.clear();
  308. }
  309. void cmake::ProcessPresetEnvironment()
  310. {
  311. for (auto const& var : this->UnprocessedPresetEnvironment) {
  312. if (var.second) {
  313. cmSystemTools::PutEnv(cmStrCat(var.first, '=', *var.second));
  314. }
  315. }
  316. }
  317. void cmake::PrintPresetEnvironment()
  318. {
  319. bool first = true;
  320. for (auto const& var : this->UnprocessedPresetEnvironment) {
  321. if (!var.second) {
  322. continue;
  323. }
  324. if (first) {
  325. std::cout << "Preset environment variables:\n\n";
  326. first = false;
  327. }
  328. std::cout << " " << var.first << "=\"" << *var.second << "\"\n";
  329. }
  330. if (!first) {
  331. std::cout << '\n';
  332. }
  333. this->UnprocessedPresetEnvironment.clear();
  334. }
  335. #endif
  336. // Parse the args
  337. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  338. {
  339. auto findPackageMode = false;
  340. auto seenScriptOption = false;
  341. for (unsigned int i = 1; i < args.size(); ++i) {
  342. std::string const& arg = args[i];
  343. if (cmHasLiteralPrefix(arg, "-D")) {
  344. std::string entry = arg.substr(2);
  345. if (entry.empty()) {
  346. ++i;
  347. if (i < args.size()) {
  348. entry = args[i];
  349. } else {
  350. cmSystemTools::Error("-D must be followed with VAR=VALUE.");
  351. return false;
  352. }
  353. }
  354. std::string var;
  355. std::string value;
  356. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  357. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  358. #ifndef CMAKE_BOOTSTRAP
  359. this->UnprocessedPresetVariables.erase(var);
  360. #endif
  361. this->ProcessCacheArg(var, value, type);
  362. } else {
  363. cmSystemTools::Error("Parse error in command line argument: " + arg +
  364. "\n" + "Should be: VAR:type=value\n");
  365. return false;
  366. }
  367. } else if (cmHasLiteralPrefix(arg, "-W")) {
  368. std::string entry = arg.substr(2);
  369. if (entry.empty()) {
  370. ++i;
  371. if (i < args.size()) {
  372. entry = args[i];
  373. } else {
  374. cmSystemTools::Error("-W must be followed with [no-]<name>.");
  375. return false;
  376. }
  377. }
  378. std::string name;
  379. bool foundNo = false;
  380. bool foundError = false;
  381. unsigned int nameStartPosition = 0;
  382. if (entry.find("no-", nameStartPosition) == 0) {
  383. foundNo = true;
  384. nameStartPosition += 3;
  385. }
  386. if (entry.find("error=", nameStartPosition) == 0) {
  387. foundError = true;
  388. nameStartPosition += 6;
  389. }
  390. name = entry.substr(nameStartPosition);
  391. if (name.empty()) {
  392. cmSystemTools::Error("No warning name provided.");
  393. return false;
  394. }
  395. if (!foundNo && !foundError) {
  396. // -W<name>
  397. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  398. } else if (foundNo && !foundError) {
  399. // -Wno<name>
  400. this->DiagLevels[name] = DIAG_IGNORE;
  401. } else if (!foundNo && foundError) {
  402. // -Werror=<name>
  403. this->DiagLevels[name] = DIAG_ERROR;
  404. } else {
  405. // -Wno-error=<name>
  406. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  407. }
  408. } else if (cmHasLiteralPrefix(arg, "-U")) {
  409. std::string entryPattern = arg.substr(2);
  410. if (entryPattern.empty()) {
  411. ++i;
  412. if (i < args.size()) {
  413. entryPattern = args[i];
  414. } else {
  415. cmSystemTools::Error("-U must be followed with VAR.");
  416. return false;
  417. }
  418. }
  419. cmsys::RegularExpression regex(
  420. cmsys::Glob::PatternToRegex(entryPattern, true, true));
  421. // go through all cache entries and collect the vars which will be
  422. // removed
  423. std::vector<std::string> entriesToDelete;
  424. std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
  425. for (std::string const& ck : cacheKeys) {
  426. cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(ck);
  427. if (t != cmStateEnums::STATIC) {
  428. if (regex.find(ck)) {
  429. entriesToDelete.push_back(ck);
  430. }
  431. }
  432. }
  433. // now remove them from the cache
  434. for (std::string const& currentEntry : entriesToDelete) {
  435. #ifndef CMAKE_BOOTSTRAP
  436. this->UnprocessedPresetVariables.erase(currentEntry);
  437. #endif
  438. this->State->RemoveCacheEntry(currentEntry);
  439. }
  440. } else if (cmHasLiteralPrefix(arg, "-C")) {
  441. std::string path = arg.substr(2);
  442. if (path.empty()) {
  443. ++i;
  444. if (i < args.size()) {
  445. path = args[i];
  446. } else {
  447. cmSystemTools::Error("-C must be followed by a file name.");
  448. return false;
  449. }
  450. }
  451. cmSystemTools::Stdout("loading initial cache file " + path + "\n");
  452. // Resolve script path specified on command line relative to $PWD.
  453. path = cmSystemTools::CollapseFullPath(path);
  454. this->ReadListFile(args, path);
  455. } else if (cmHasLiteralPrefix(arg, "-P")) {
  456. i++;
  457. if (i >= args.size()) {
  458. cmSystemTools::Error("-P must be followed by a file name.");
  459. return false;
  460. }
  461. std::string path = args[i];
  462. if (path.empty()) {
  463. cmSystemTools::Error("No cmake script provided.");
  464. return false;
  465. }
  466. // Register fake project commands that hint misuse in script mode.
  467. GetProjectCommandsInScriptMode(this->GetState());
  468. // Documented behaviour of CMAKE{,_CURRENT}_{SOURCE,BINARY}_DIR is to be
  469. // set to $PWD for -P mode.
  470. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  471. this->SetHomeOutputDirectory(
  472. cmSystemTools::GetCurrentWorkingDirectory());
  473. this->ReadListFile(args, path);
  474. seenScriptOption = true;
  475. } else if (arg == "--" && seenScriptOption) {
  476. // Stop processing CMake args and avoid possible errors
  477. // when arbitrary args are given to CMake script.
  478. break;
  479. } else if (cmHasLiteralPrefix(arg, "--find-package")) {
  480. findPackageMode = true;
  481. }
  482. }
  483. if (findPackageMode) {
  484. return this->FindPackage(args);
  485. }
  486. return true;
  487. }
  488. void cmake::ProcessCacheArg(const std::string& var, const std::string& value,
  489. cmStateEnums::CacheEntryType type)
  490. {
  491. // The value is transformed if it is a filepath for example, so
  492. // we can't compare whether the value is already in the cache until
  493. // after we call AddCacheEntry.
  494. bool haveValue = false;
  495. std::string cachedValue;
  496. if (this->WarnUnusedCli) {
  497. if (cmProp v = this->State->GetInitializedCacheValue(var)) {
  498. haveValue = true;
  499. cachedValue = *v;
  500. }
  501. }
  502. this->AddCacheEntry(var, value.c_str(),
  503. "No help, variable specified on the command line.",
  504. type);
  505. if (this->WarnUnusedCli) {
  506. if (!haveValue ||
  507. cachedValue != *this->State->GetInitializedCacheValue(var)) {
  508. this->WatchUnusedCli(var);
  509. }
  510. }
  511. }
  512. void cmake::ReadListFile(const std::vector<std::string>& args,
  513. const std::string& path)
  514. {
  515. // if a generator was not yet created, temporarily create one
  516. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  517. // if a generator was not specified use a generic one
  518. std::unique_ptr<cmGlobalGenerator> gen;
  519. if (!gg) {
  520. gen = cm::make_unique<cmGlobalGenerator>(this);
  521. gg = gen.get();
  522. }
  523. // read in the list file to fill the cache
  524. if (!path.empty()) {
  525. this->CurrentSnapshot = this->State->Reset();
  526. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  527. snapshot.GetDirectory().SetCurrentBinary(this->GetHomeOutputDirectory());
  528. snapshot.GetDirectory().SetCurrentSource(this->GetHomeDirectory());
  529. snapshot.SetDefaultDefinitions();
  530. cmMakefile mf(gg, snapshot);
  531. if (this->GetWorkingMode() != NORMAL_MODE) {
  532. std::string file(cmSystemTools::CollapseFullPath(path));
  533. cmSystemTools::ConvertToUnixSlashes(file);
  534. mf.SetScriptModeFile(file);
  535. mf.SetArgcArgv(args);
  536. }
  537. if (!mf.ReadListFile(path)) {
  538. cmSystemTools::Error("Error processing file: " + path);
  539. }
  540. }
  541. }
  542. bool cmake::FindPackage(const std::vector<std::string>& args)
  543. {
  544. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  545. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  546. this->SetGlobalGenerator(cm::make_unique<cmGlobalGenerator>(this));
  547. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  548. snapshot.GetDirectory().SetCurrentBinary(
  549. cmSystemTools::GetCurrentWorkingDirectory());
  550. snapshot.GetDirectory().SetCurrentSource(
  551. cmSystemTools::GetCurrentWorkingDirectory());
  552. // read in the list file to fill the cache
  553. snapshot.SetDefaultDefinitions();
  554. auto mfu = cm::make_unique<cmMakefile>(this->GetGlobalGenerator(), snapshot);
  555. cmMakefile* mf = mfu.get();
  556. this->GlobalGenerator->AddMakefile(std::move(mfu));
  557. mf->SetArgcArgv(args);
  558. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  559. mf->ReadListFile(systemFile);
  560. std::string language = mf->GetSafeDefinition("LANGUAGE");
  561. std::string mode = mf->GetSafeDefinition("MODE");
  562. std::string packageName = mf->GetSafeDefinition("NAME");
  563. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  564. bool quiet = mf->IsOn("PACKAGE_QUIET");
  565. if (!packageFound) {
  566. if (!quiet) {
  567. printf("%s not found.\n", packageName.c_str());
  568. }
  569. } else if (mode == "EXIST"_s) {
  570. if (!quiet) {
  571. printf("%s found.\n", packageName.c_str());
  572. }
  573. } else if (mode == "COMPILE"_s) {
  574. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  575. std::vector<std::string> includeDirs = cmExpandedList(includes);
  576. this->GlobalGenerator->CreateGenerationObjects();
  577. const auto& lg = this->GlobalGenerator->LocalGenerators[0];
  578. std::string includeFlags =
  579. lg->GetIncludeFlags(includeDirs, nullptr, language);
  580. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  581. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  582. } else if (mode == "LINK"_s) {
  583. const char* targetName = "dummy";
  584. std::vector<std::string> srcs;
  585. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  586. tgt->SetProperty("LINKER_LANGUAGE", language);
  587. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  588. std::vector<std::string> libList = cmExpandedList(libs);
  589. for (std::string const& lib : libList) {
  590. tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
  591. }
  592. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  593. buildType = cmSystemTools::UpperCase(buildType);
  594. std::string linkLibs;
  595. std::string frameworkPath;
  596. std::string linkPath;
  597. std::string flags;
  598. std::string linkFlags;
  599. this->GlobalGenerator->CreateGenerationObjects();
  600. cmGeneratorTarget* gtgt =
  601. this->GlobalGenerator->FindGeneratorTarget(tgt->GetName());
  602. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  603. cmLinkLineComputer linkLineComputer(lg,
  604. lg->GetStateSnapshot().GetDirectory());
  605. lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
  606. linkFlags, frameworkPath, linkPath, gtgt);
  607. linkLibs = frameworkPath + linkPath + linkLibs;
  608. printf("%s\n", linkLibs.c_str());
  609. /* if ( use_win32 )
  610. {
  611. tgt->SetProperty("WIN32_EXECUTABLE", "ON");
  612. }
  613. if ( use_macbundle)
  614. {
  615. tgt->SetProperty("MACOSX_BUNDLE", "ON");
  616. }*/
  617. }
  618. return packageFound;
  619. }
  620. void cmake::LoadEnvironmentPresets()
  621. {
  622. std::string envGenVar;
  623. bool hasEnvironmentGenerator = false;
  624. if (cmSystemTools::GetEnv("CMAKE_GENERATOR", envGenVar)) {
  625. hasEnvironmentGenerator = true;
  626. this->EnvironmentGenerator = envGenVar;
  627. }
  628. auto readGeneratorVar = [&](std::string const& name, std::string& key) {
  629. std::string varValue;
  630. if (cmSystemTools::GetEnv(name, varValue)) {
  631. if (hasEnvironmentGenerator) {
  632. key = varValue;
  633. } else if (!this->GetIsInTryCompile()) {
  634. std::string message =
  635. cmStrCat("Warning: Environment variable ", name,
  636. " will be ignored, because CMAKE_GENERATOR is not set.");
  637. cmSystemTools::Message(message, "Warning");
  638. }
  639. }
  640. };
  641. readGeneratorVar("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance);
  642. readGeneratorVar("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform);
  643. readGeneratorVar("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset);
  644. }
  645. // Parse the args
  646. void cmake::SetArgs(const std::vector<std::string>& args)
  647. {
  648. bool haveToolset = false;
  649. bool havePlatform = false;
  650. #if !defined(CMAKE_BOOTSTRAP)
  651. std::string profilingFormat;
  652. std::string profilingOutput;
  653. std::string presetName;
  654. bool listPresets = false;
  655. #endif
  656. for (unsigned int i = 1; i < args.size(); ++i) {
  657. std::string const& arg = args[i];
  658. if (cmHasLiteralPrefix(arg, "-H") || cmHasLiteralPrefix(arg, "-S")) {
  659. std::string path = arg.substr(2);
  660. if (path.empty()) {
  661. ++i;
  662. if (i >= args.size()) {
  663. cmSystemTools::Error("No source directory specified for -S");
  664. return;
  665. }
  666. path = args[i];
  667. if (path[0] == '-') {
  668. cmSystemTools::Error("No source directory specified for -S");
  669. return;
  670. }
  671. }
  672. path = cmSystemTools::CollapseFullPath(path);
  673. cmSystemTools::ConvertToUnixSlashes(path);
  674. this->SetHomeDirectory(path);
  675. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  676. // NOLINTNEXTLINE(bugprone-branch-clone)
  677. } else if (cmHasLiteralPrefix(arg, "-O")) {
  678. // There is no local generate anymore. Ignore -O option.
  679. } else if (cmHasLiteralPrefix(arg, "-B")) {
  680. std::string path = arg.substr(2);
  681. if (path.empty()) {
  682. ++i;
  683. if (i >= args.size()) {
  684. cmSystemTools::Error("No build directory specified for -B");
  685. return;
  686. }
  687. path = args[i];
  688. if (path[0] == '-') {
  689. cmSystemTools::Error("No build directory specified for -B");
  690. return;
  691. }
  692. }
  693. path = cmSystemTools::CollapseFullPath(path);
  694. cmSystemTools::ConvertToUnixSlashes(path);
  695. this->SetHomeOutputDirectory(path);
  696. } else if ((i < args.size() - 2) &&
  697. cmHasLiteralPrefix(arg, "--check-build-system")) {
  698. this->CheckBuildSystemArgument = args[++i];
  699. this->ClearBuildSystem = (atoi(args[++i].c_str()) > 0);
  700. } else if ((i < args.size() - 1) &&
  701. cmHasLiteralPrefix(arg, "--check-stamp-file")) {
  702. this->CheckStampFile = args[++i];
  703. } else if ((i < args.size() - 1) &&
  704. cmHasLiteralPrefix(arg, "--check-stamp-list")) {
  705. this->CheckStampList = args[++i];
  706. } else if (arg == "--regenerate-during-build"_s) {
  707. this->RegenerateDuringBuild = true;
  708. }
  709. #if defined(CMAKE_HAVE_VS_GENERATORS)
  710. else if ((i < args.size() - 1) &&
  711. cmHasLiteralPrefix(arg, "--vs-solution-file")) {
  712. this->VSSolutionFile = args[++i];
  713. }
  714. #endif
  715. else if (cmHasLiteralPrefix(arg, "-D") || cmHasLiteralPrefix(arg, "-U") ||
  716. cmHasLiteralPrefix(arg, "-C")) {
  717. // skip for now
  718. // in case '-[DUC] argval' var' is given, also skip the next
  719. // in case '-[DUC]argval' is given, don't skip the next
  720. if (arg.size() == 2) {
  721. ++i;
  722. }
  723. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  724. // NOLINTNEXTLINE(bugprone-branch-clone)
  725. } else if (cmHasLiteralPrefix(arg, "-P")) {
  726. // skip for now
  727. i++;
  728. } else if (cmHasLiteralPrefix(arg, "--find-package")) {
  729. // skip for now
  730. i++;
  731. } else if (cmHasLiteralPrefix(arg, "-W")) {
  732. // skip for now
  733. } else if (cmHasLiteralPrefix(arg, "--graphviz=")) {
  734. std::string path = arg.substr(strlen("--graphviz="));
  735. path = cmSystemTools::CollapseFullPath(path);
  736. cmSystemTools::ConvertToUnixSlashes(path);
  737. this->GraphVizFile = path;
  738. if (this->GraphVizFile.empty()) {
  739. cmSystemTools::Error("No file specified for --graphviz");
  740. return;
  741. }
  742. } else if (cmHasLiteralPrefix(arg, "--debug-trycompile")) {
  743. std::cout << "debug trycompile on\n";
  744. this->DebugTryCompileOn();
  745. } else if (cmHasLiteralPrefix(arg, "--debug-output")) {
  746. std::cout << "Running with debug output on.\n";
  747. this->SetDebugOutputOn(true);
  748. } else if (cmHasLiteralPrefix(arg, "--log-level=")) {
  749. const auto logLevel =
  750. StringToLogLevel(arg.substr(sizeof("--log-level=") - 1));
  751. if (logLevel == LogLevel::LOG_UNDEFINED) {
  752. cmSystemTools::Error("Invalid level specified for --log-level");
  753. return;
  754. }
  755. this->SetLogLevel(logLevel);
  756. this->LogLevelWasSetViaCLI = true;
  757. } else if (cmHasLiteralPrefix(arg, "--loglevel=")) {
  758. // This is supported for backward compatibility. This option only
  759. // appeared in the 3.15.x release series and was renamed to
  760. // --log-level in 3.16.0
  761. const auto logLevel =
  762. StringToLogLevel(arg.substr(sizeof("--loglevel=") - 1));
  763. if (logLevel == LogLevel::LOG_UNDEFINED) {
  764. cmSystemTools::Error("Invalid level specified for --loglevel");
  765. return;
  766. }
  767. this->SetLogLevel(logLevel);
  768. this->LogLevelWasSetViaCLI = true;
  769. } else if (arg == "--log-context"_s) {
  770. this->SetShowLogContext(true);
  771. } else if (cmHasLiteralPrefix(arg, "--debug-find")) {
  772. std::cout << "Running with debug output on for the `find` commands.\n";
  773. this->SetDebugFindOutputOn(true);
  774. } else if (cmHasLiteralPrefix(arg, "--trace-expand")) {
  775. std::cout << "Running with expanded trace output on.\n";
  776. this->SetTrace(true);
  777. this->SetTraceExpand(true);
  778. } else if (cmHasLiteralPrefix(arg, "--trace-format=")) {
  779. this->SetTrace(true);
  780. const auto traceFormat =
  781. StringToTraceFormat(arg.substr(strlen("--trace-format=")));
  782. if (traceFormat == TraceFormat::TRACE_UNDEFINED) {
  783. cmSystemTools::Error("Invalid format specified for --trace-format. "
  784. "Valid formats are human, json-v1.");
  785. return;
  786. }
  787. this->SetTraceFormat(traceFormat);
  788. } else if (cmHasLiteralPrefix(arg, "--trace-source=")) {
  789. std::string file = arg.substr(strlen("--trace-source="));
  790. cmSystemTools::ConvertToUnixSlashes(file);
  791. this->AddTraceSource(file);
  792. this->SetTrace(true);
  793. } else if (cmHasLiteralPrefix(arg, "--trace-redirect=")) {
  794. std::string file = arg.substr(strlen("--trace-redirect="));
  795. cmSystemTools::ConvertToUnixSlashes(file);
  796. this->SetTraceFile(file);
  797. this->SetTrace(true);
  798. } else if (cmHasLiteralPrefix(arg, "--trace")) {
  799. std::cout << "Running with trace output on.\n";
  800. this->SetTrace(true);
  801. this->SetTraceExpand(false);
  802. } else if (cmHasLiteralPrefix(arg, "--warn-uninitialized")) {
  803. std::cout << "Warn about uninitialized values.\n";
  804. this->SetWarnUninitialized(true);
  805. } else if (cmHasLiteralPrefix(arg, "--warn-unused-vars")) {
  806. // Option was removed.
  807. } else if (cmHasLiteralPrefix(arg, "--no-warn-unused-cli")) {
  808. std::cout << "Not searching for unused variables given on the "
  809. << "command line.\n";
  810. this->SetWarnUnusedCli(false);
  811. } else if (cmHasLiteralPrefix(arg, "--check-system-vars")) {
  812. std::cout << "Also check system files when warning about unused and "
  813. << "uninitialized variables.\n";
  814. this->SetCheckSystemVars(true);
  815. } else if (cmHasLiteralPrefix(arg, "-A")) {
  816. std::string value = arg.substr(2);
  817. if (value.empty()) {
  818. ++i;
  819. if (i >= args.size()) {
  820. cmSystemTools::Error("No platform specified for -A");
  821. return;
  822. }
  823. value = args[i];
  824. }
  825. if (havePlatform) {
  826. cmSystemTools::Error("Multiple -A options not allowed");
  827. return;
  828. }
  829. this->SetGeneratorPlatform(value);
  830. havePlatform = true;
  831. } else if (cmHasLiteralPrefix(arg, "-T")) {
  832. std::string value = arg.substr(2);
  833. if (value.empty()) {
  834. ++i;
  835. if (i >= args.size()) {
  836. cmSystemTools::Error("No toolset specified for -T");
  837. return;
  838. }
  839. value = args[i];
  840. }
  841. if (haveToolset) {
  842. cmSystemTools::Error("Multiple -T options not allowed");
  843. return;
  844. }
  845. this->SetGeneratorToolset(value);
  846. haveToolset = true;
  847. } else if (cmHasLiteralPrefix(arg, "-G")) {
  848. std::string value = arg.substr(2);
  849. if (value.empty()) {
  850. ++i;
  851. if (i >= args.size()) {
  852. cmSystemTools::Error("No generator specified for -G");
  853. this->PrintGeneratorList();
  854. return;
  855. }
  856. value = args[i];
  857. }
  858. if (!this->CreateAndSetGlobalGenerator(value, true)) {
  859. return;
  860. }
  861. #if !defined(CMAKE_BOOTSTRAP)
  862. } else if (cmHasLiteralPrefix(arg, "--profiling-format")) {
  863. profilingFormat = arg.substr(strlen("--profiling-format="));
  864. if (profilingFormat.empty()) {
  865. cmSystemTools::Error("No format specified for --profiling-format");
  866. }
  867. } else if (cmHasLiteralPrefix(arg, "--profiling-output")) {
  868. profilingOutput = arg.substr(strlen("--profiling-output="));
  869. profilingOutput = cmSystemTools::CollapseFullPath(profilingOutput);
  870. cmSystemTools::ConvertToUnixSlashes(profilingOutput);
  871. if (profilingOutput.empty()) {
  872. cmSystemTools::Error("No path specified for --profiling-output");
  873. }
  874. } else if (cmHasLiteralPrefix(arg, "--preset")) {
  875. presetName = arg.substr(strlen("--preset="));
  876. if (presetName.empty()) {
  877. cmSystemTools::Error("No preset specified for --preset");
  878. }
  879. } else if (cmHasLiteralPrefix(arg, "--list-presets")) {
  880. listPresets = true;
  881. #endif
  882. }
  883. // no option assume it is the path to the source or an existing build
  884. else {
  885. this->SetDirectoriesFromFile(arg);
  886. }
  887. // Empty instance, platform and toolset if only a generator is specified
  888. if (this->GlobalGenerator) {
  889. this->GeneratorInstance = "";
  890. if (!this->GeneratorPlatformSet) {
  891. this->GeneratorPlatform = "";
  892. }
  893. if (!this->GeneratorToolsetSet) {
  894. this->GeneratorToolset = "";
  895. }
  896. }
  897. }
  898. #if !defined(CMAKE_BOOTSTRAP)
  899. if (!profilingOutput.empty() || !profilingFormat.empty()) {
  900. if (profilingOutput.empty()) {
  901. cmSystemTools::Error(
  902. "--profiling-format specified but no --profiling-output!");
  903. return;
  904. }
  905. if (profilingFormat == "google-trace"_s) {
  906. try {
  907. this->ProfilingOutput =
  908. cm::make_unique<cmMakefileProfilingData>(profilingOutput);
  909. } catch (std::runtime_error& e) {
  910. cmSystemTools::Error(
  911. cmStrCat("Could not start profiling: ", e.what()));
  912. return;
  913. }
  914. } else {
  915. cmSystemTools::Error("Invalid format specified for --profiling-format");
  916. return;
  917. }
  918. }
  919. #endif
  920. const bool haveSourceDir = !this->GetHomeDirectory().empty();
  921. const bool haveBinaryDir = !this->GetHomeOutputDirectory().empty();
  922. if (this->CurrentWorkingMode == cmake::NORMAL_MODE && !haveSourceDir &&
  923. !haveBinaryDir) {
  924. this->IssueMessage(
  925. MessageType::WARNING,
  926. "No source or binary directory provided. Both will be assumed to be "
  927. "the same as the current working directory, but note that this "
  928. "warning will become a fatal error in future CMake releases.");
  929. }
  930. if (!haveSourceDir) {
  931. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  932. }
  933. if (!haveBinaryDir) {
  934. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  935. }
  936. #if !defined(CMAKE_BOOTSTRAP)
  937. if (listPresets || !presetName.empty()) {
  938. cmCMakePresetsFile settingsFile;
  939. auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory());
  940. if (result != cmCMakePresetsFile::ReadFileResult::READ_OK) {
  941. cmSystemTools::Error(
  942. cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
  943. ": ", cmCMakePresetsFile::ResultToString(result)));
  944. return;
  945. }
  946. if (listPresets) {
  947. this->PrintPresetList(settingsFile);
  948. return;
  949. }
  950. auto preset = settingsFile.Presets.find(presetName);
  951. if (preset == settingsFile.Presets.end()) {
  952. cmSystemTools::Error(cmStrCat("No such preset in ",
  953. this->GetHomeDirectory(), ": \"",
  954. presetName, '"'));
  955. this->PrintPresetList(settingsFile);
  956. return;
  957. }
  958. if (preset->second.Unexpanded.Hidden) {
  959. cmSystemTools::Error(cmStrCat("Cannot use hidden preset in ",
  960. this->GetHomeDirectory(), ": \"",
  961. presetName, '"'));
  962. this->PrintPresetList(settingsFile);
  963. return;
  964. }
  965. auto const& expandedPreset = preset->second.Expanded;
  966. if (!expandedPreset) {
  967. cmSystemTools::Error(cmStrCat("Could not evaluate preset \"",
  968. preset->second.Unexpanded.Name,
  969. "\": Invalid macro expansion"));
  970. return;
  971. }
  972. if (!haveBinaryDir) {
  973. this->SetHomeOutputDirectory(expandedPreset->BinaryDir);
  974. }
  975. if (!this->GlobalGenerator) {
  976. if (!this->CreateAndSetGlobalGenerator(expandedPreset->Generator,
  977. false)) {
  978. return;
  979. }
  980. }
  981. this->UnprocessedPresetVariables = expandedPreset->CacheVariables;
  982. this->UnprocessedPresetEnvironment = expandedPreset->Environment;
  983. if (!expandedPreset->GeneratorConfig ||
  984. expandedPreset->GeneratorConfig ==
  985. cmCMakePresetsFile::CMakeGeneratorConfig::Default) {
  986. if (!this->GeneratorPlatformSet) {
  987. this->SetGeneratorPlatform(expandedPreset->Architecture);
  988. }
  989. if (!this->GeneratorToolsetSet) {
  990. this->SetGeneratorToolset(expandedPreset->Toolset);
  991. }
  992. }
  993. this->SetWarningFromPreset("dev", expandedPreset->WarnDev,
  994. expandedPreset->ErrorDev);
  995. this->SetWarningFromPreset("deprecated", expandedPreset->WarnDeprecated,
  996. expandedPreset->ErrorDeprecated);
  997. if (expandedPreset->WarnUninitialized == true) {
  998. this->SetWarnUninitialized(true);
  999. }
  1000. if (expandedPreset->WarnUnusedCli == false) {
  1001. this->SetWarnUnusedCli(false);
  1002. }
  1003. if (expandedPreset->WarnSystemVars == true) {
  1004. this->SetCheckSystemVars(true);
  1005. }
  1006. if (expandedPreset->DebugOutput == true) {
  1007. this->SetDebugOutputOn(true);
  1008. }
  1009. if (expandedPreset->DebugTryCompile == true) {
  1010. this->DebugTryCompileOn();
  1011. }
  1012. if (expandedPreset->DebugFind == true) {
  1013. this->SetDebugFindOutputOn(true);
  1014. }
  1015. }
  1016. #endif
  1017. }
  1018. cmake::LogLevel cmake::StringToLogLevel(const std::string& levelStr)
  1019. {
  1020. using LevelsPair = std::pair<std::string, LogLevel>;
  1021. static const std::vector<LevelsPair> levels = {
  1022. { "error", LogLevel::LOG_ERROR }, { "warning", LogLevel::LOG_WARNING },
  1023. { "notice", LogLevel::LOG_NOTICE }, { "status", LogLevel::LOG_STATUS },
  1024. { "verbose", LogLevel::LOG_VERBOSE }, { "debug", LogLevel::LOG_DEBUG },
  1025. { "trace", LogLevel::LOG_TRACE }
  1026. };
  1027. const auto levelStrLowCase = cmSystemTools::LowerCase(levelStr);
  1028. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1029. [&levelStrLowCase](const LevelsPair& p) {
  1030. return p.first == levelStrLowCase;
  1031. });
  1032. return (it != levels.cend()) ? it->second : LogLevel::LOG_UNDEFINED;
  1033. }
  1034. cmake::TraceFormat cmake::StringToTraceFormat(const std::string& traceStr)
  1035. {
  1036. using TracePair = std::pair<std::string, TraceFormat>;
  1037. static const std::vector<TracePair> levels = {
  1038. { "human", TraceFormat::TRACE_HUMAN },
  1039. { "json-v1", TraceFormat::TRACE_JSON_V1 },
  1040. };
  1041. const auto traceStrLowCase = cmSystemTools::LowerCase(traceStr);
  1042. const auto it = std::find_if(levels.cbegin(), levels.cend(),
  1043. [&traceStrLowCase](const TracePair& p) {
  1044. return p.first == traceStrLowCase;
  1045. });
  1046. return (it != levels.cend()) ? it->second : TraceFormat::TRACE_UNDEFINED;
  1047. }
  1048. void cmake::SetTraceFile(const std::string& file)
  1049. {
  1050. this->TraceFile.close();
  1051. this->TraceFile.open(file.c_str());
  1052. if (!this->TraceFile) {
  1053. std::stringstream ss;
  1054. ss << "Error opening trace file " << file << ": "
  1055. << cmSystemTools::GetLastSystemError();
  1056. cmSystemTools::Error(ss.str());
  1057. return;
  1058. }
  1059. std::cout << "Trace will be written to " << file << "\n";
  1060. }
  1061. void cmake::PrintTraceFormatVersion()
  1062. {
  1063. if (!this->GetTrace()) {
  1064. return;
  1065. }
  1066. std::string msg;
  1067. switch (this->GetTraceFormat()) {
  1068. case TraceFormat::TRACE_JSON_V1: {
  1069. #ifndef CMAKE_BOOTSTRAP
  1070. Json::Value val;
  1071. Json::Value version;
  1072. Json::StreamWriterBuilder builder;
  1073. builder["indentation"] = "";
  1074. version["major"] = 1;
  1075. version["minor"] = 1;
  1076. val["version"] = version;
  1077. msg = Json::writeString(builder, val);
  1078. #endif
  1079. break;
  1080. }
  1081. case TraceFormat::TRACE_HUMAN:
  1082. msg = "";
  1083. break;
  1084. case TraceFormat::TRACE_UNDEFINED:
  1085. msg = "INTERNAL ERROR: Trace format is TRACE_UNDEFINED";
  1086. break;
  1087. }
  1088. if (msg.empty()) {
  1089. return;
  1090. }
  1091. auto& f = this->GetTraceFile();
  1092. if (f) {
  1093. f << msg << '\n';
  1094. } else {
  1095. cmSystemTools::Message(msg);
  1096. }
  1097. }
  1098. void cmake::SetDirectoriesFromFile(const std::string& arg)
  1099. {
  1100. // Check if the argument refers to a CMakeCache.txt or
  1101. // CMakeLists.txt file.
  1102. std::string listPath;
  1103. std::string cachePath;
  1104. bool argIsFile = false;
  1105. if (cmSystemTools::FileIsDirectory(arg)) {
  1106. std::string path = cmSystemTools::CollapseFullPath(arg);
  1107. cmSystemTools::ConvertToUnixSlashes(path);
  1108. std::string cacheFile = cmStrCat(path, "/CMakeCache.txt");
  1109. std::string listFile = cmStrCat(path, "/CMakeLists.txt");
  1110. if (cmSystemTools::FileExists(cacheFile)) {
  1111. cachePath = path;
  1112. }
  1113. if (cmSystemTools::FileExists(listFile)) {
  1114. listPath = path;
  1115. }
  1116. } else if (cmSystemTools::FileExists(arg)) {
  1117. argIsFile = true;
  1118. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1119. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1120. name = cmSystemTools::LowerCase(name);
  1121. if (name == "cmakecache.txt"_s) {
  1122. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  1123. } else if (name == "cmakelists.txt"_s) {
  1124. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1125. }
  1126. } else {
  1127. // Specified file or directory does not exist. Try to set things
  1128. // up to produce a meaningful error message.
  1129. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  1130. std::string name = cmSystemTools::GetFilenameName(fullPath);
  1131. name = cmSystemTools::LowerCase(name);
  1132. if (name == "cmakecache.txt"_s || name == "cmakelists.txt"_s) {
  1133. argIsFile = true;
  1134. listPath = cmSystemTools::GetFilenamePath(fullPath);
  1135. } else {
  1136. listPath = fullPath;
  1137. }
  1138. }
  1139. // If there is a CMakeCache.txt file, use its settings.
  1140. if (!cachePath.empty()) {
  1141. if (this->LoadCache(cachePath)) {
  1142. cmProp existingValue =
  1143. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  1144. if (existingValue) {
  1145. this->SetHomeOutputDirectory(cachePath);
  1146. this->SetHomeDirectory(*existingValue);
  1147. return;
  1148. }
  1149. }
  1150. }
  1151. // If there is a CMakeLists.txt file, use it as the source tree.
  1152. if (!listPath.empty()) {
  1153. this->SetHomeDirectory(listPath);
  1154. if (argIsFile) {
  1155. // Source CMakeLists.txt file given. It was probably dropped
  1156. // onto the executable in a GUI. Default to an in-source build.
  1157. this->SetHomeOutputDirectory(listPath);
  1158. } else {
  1159. // Source directory given on command line. Use current working
  1160. // directory as build tree if -B hasn't been given already
  1161. if (this->GetHomeOutputDirectory().empty()) {
  1162. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1163. this->SetHomeOutputDirectory(cwd);
  1164. }
  1165. }
  1166. return;
  1167. }
  1168. if (this->GetHomeDirectory().empty()) {
  1169. // We didn't find a CMakeLists.txt and it wasn't specified
  1170. // with -S. Assume it is the path to the source tree
  1171. std::string full = cmSystemTools::CollapseFullPath(arg);
  1172. this->SetHomeDirectory(full);
  1173. }
  1174. if (this->GetHomeOutputDirectory().empty()) {
  1175. // We didn't find a CMakeCache.txt and it wasn't specified
  1176. // with -B. Assume the current working directory as the build tree.
  1177. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1178. this->SetHomeOutputDirectory(cwd);
  1179. }
  1180. }
  1181. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  1182. // cache
  1183. int cmake::AddCMakePaths()
  1184. {
  1185. // Save the value in the cache
  1186. this->AddCacheEntry("CMAKE_COMMAND",
  1187. cmSystemTools::GetCMakeCommand().c_str(),
  1188. "Path to CMake executable.", cmStateEnums::INTERNAL);
  1189. #ifndef CMAKE_BOOTSTRAP
  1190. this->AddCacheEntry(
  1191. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  1192. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  1193. this->AddCacheEntry(
  1194. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  1195. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  1196. #endif
  1197. if (!cmSystemTools::FileExists(
  1198. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  1199. // couldn't find modules
  1200. cmSystemTools::Error(
  1201. "Could not find CMAKE_ROOT !!!\n"
  1202. "CMake has most likely not been installed correctly.\n"
  1203. "Modules directory not found in\n" +
  1204. cmSystemTools::GetCMakeRoot());
  1205. return 0;
  1206. }
  1207. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  1208. "Path to CMake installation.", cmStateEnums::INTERNAL);
  1209. return 1;
  1210. }
  1211. void cmake::AddDefaultExtraGenerators()
  1212. {
  1213. #if !defined(CMAKE_BOOTSTRAP)
  1214. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  1215. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  1216. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  1217. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  1218. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  1219. #endif
  1220. }
  1221. void cmake::GetRegisteredGenerators(std::vector<GeneratorInfo>& generators,
  1222. bool includeNamesWithPlatform) const
  1223. {
  1224. for (const auto& gen : this->Generators) {
  1225. std::vector<std::string> names = gen->GetGeneratorNames();
  1226. if (includeNamesWithPlatform) {
  1227. cm::append(names, gen->GetGeneratorNamesWithPlatform());
  1228. }
  1229. for (std::string const& name : names) {
  1230. GeneratorInfo info;
  1231. info.supportsToolset = gen->SupportsToolset();
  1232. info.supportsPlatform = gen->SupportsPlatform();
  1233. info.supportedPlatforms = gen->GetKnownPlatforms();
  1234. info.defaultPlatform = gen->GetDefaultPlatformName();
  1235. info.name = name;
  1236. info.baseName = name;
  1237. info.isAlias = false;
  1238. generators.push_back(std::move(info));
  1239. }
  1240. }
  1241. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1242. const std::vector<std::string> genList =
  1243. eg->GetSupportedGlobalGenerators();
  1244. for (std::string const& gen : genList) {
  1245. GeneratorInfo info;
  1246. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1247. gen, eg->GetName());
  1248. info.baseName = gen;
  1249. info.extraName = eg->GetName();
  1250. info.supportsPlatform = false;
  1251. info.supportsToolset = false;
  1252. info.isAlias = false;
  1253. generators.push_back(std::move(info));
  1254. }
  1255. for (std::string const& a : eg->Aliases) {
  1256. GeneratorInfo info;
  1257. info.name = a;
  1258. if (!genList.empty()) {
  1259. info.baseName = genList.at(0);
  1260. }
  1261. info.extraName = eg->GetName();
  1262. info.supportsPlatform = false;
  1263. info.supportsToolset = false;
  1264. info.isAlias = true;
  1265. generators.push_back(std::move(info));
  1266. }
  1267. }
  1268. }
  1269. static std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>,
  1270. std::string>
  1271. createExtraGenerator(
  1272. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  1273. const std::string& name)
  1274. {
  1275. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  1276. const std::vector<std::string> generators =
  1277. i->GetSupportedGlobalGenerators();
  1278. if (i->GetName() == name) { // Match aliases
  1279. return { i->CreateExternalMakefileProjectGenerator(), generators.at(0) };
  1280. }
  1281. for (std::string const& g : generators) {
  1282. const std::string fullName =
  1283. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1284. g, i->GetName());
  1285. if (fullName == name) {
  1286. return { i->CreateExternalMakefileProjectGenerator(), g };
  1287. }
  1288. }
  1289. }
  1290. return { nullptr, name };
  1291. }
  1292. std::unique_ptr<cmGlobalGenerator> cmake::CreateGlobalGenerator(
  1293. const std::string& gname, bool allowArch)
  1294. {
  1295. std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>, std::string>
  1296. extra = createExtraGenerator(this->ExtraGenerators, gname);
  1297. std::unique_ptr<cmExternalMakefileProjectGenerator>& extraGenerator =
  1298. extra.first;
  1299. const std::string& name = extra.second;
  1300. std::unique_ptr<cmGlobalGenerator> generator;
  1301. for (const auto& g : this->Generators) {
  1302. generator = g->CreateGlobalGenerator(name, allowArch, this);
  1303. if (generator) {
  1304. break;
  1305. }
  1306. }
  1307. if (generator) {
  1308. generator->SetExternalMakefileProjectGenerator(std::move(extraGenerator));
  1309. }
  1310. return generator;
  1311. }
  1312. bool cmake::CreateAndSetGlobalGenerator(const std::string& name,
  1313. bool allowArch)
  1314. {
  1315. auto gen = this->CreateGlobalGenerator(name, allowArch);
  1316. if (!gen) {
  1317. std::string kdevError;
  1318. std::string vsError;
  1319. if (name.find("KDevelop3", 0) != std::string::npos) {
  1320. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  1321. }
  1322. if (!allowArch && cmHasLiteralPrefix(name, "Visual Studio ") &&
  1323. name.length() >= cmStrLen("Visual Studio xx xxxx ")) {
  1324. vsError = "\nUsing platforms in Visual Studio generator names is not "
  1325. "supported in CMakePresets.json.";
  1326. }
  1327. cmSystemTools::Error(
  1328. cmStrCat("Could not create named generator ", name, kdevError, vsError));
  1329. this->PrintGeneratorList();
  1330. return false;
  1331. }
  1332. this->SetGlobalGenerator(std::move(gen));
  1333. return true;
  1334. }
  1335. #ifndef CMAKE_BOOTSTRAP
  1336. void cmake::PrintPresetList(const cmCMakePresetsFile& file) const
  1337. {
  1338. std::vector<GeneratorInfo> generators;
  1339. this->GetRegisteredGenerators(generators, false);
  1340. std::vector<cmCMakePresetsFile::UnexpandedPreset> presets;
  1341. for (auto const& p : file.PresetOrder) {
  1342. auto const& preset = file.Presets.at(p);
  1343. if (!preset.Unexpanded.Hidden && preset.Expanded &&
  1344. std::find_if(generators.begin(), generators.end(),
  1345. [&preset](const GeneratorInfo& info) {
  1346. return info.name == preset.Unexpanded.Generator;
  1347. }) != generators.end()) {
  1348. presets.push_back(preset.Unexpanded);
  1349. }
  1350. }
  1351. if (presets.empty()) {
  1352. return;
  1353. }
  1354. std::cout << "Available presets:\n\n";
  1355. auto longestPresetName =
  1356. std::max_element(presets.begin(), presets.end(),
  1357. [](const cmCMakePresetsFile::UnexpandedPreset& a,
  1358. const cmCMakePresetsFile::UnexpandedPreset& b) {
  1359. return a.Name.length() < b.Name.length();
  1360. });
  1361. auto longestLength = longestPresetName->Name.length();
  1362. for (auto const& preset : presets) {
  1363. std::cout << " \"" << preset.Name << '"';
  1364. auto const& description = preset.DisplayName;
  1365. if (!description.empty()) {
  1366. for (std::size_t i = 0; i < longestLength - preset.Name.length(); ++i) {
  1367. std::cout << ' ';
  1368. }
  1369. std::cout << " - " << description;
  1370. }
  1371. std::cout << '\n';
  1372. }
  1373. }
  1374. #endif
  1375. void cmake::SetHomeDirectory(const std::string& dir)
  1376. {
  1377. this->State->SetSourceDirectory(dir);
  1378. if (this->CurrentSnapshot.IsValid()) {
  1379. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  1380. }
  1381. }
  1382. std::string const& cmake::GetHomeDirectory() const
  1383. {
  1384. return this->State->GetSourceDirectory();
  1385. }
  1386. void cmake::SetHomeOutputDirectory(const std::string& dir)
  1387. {
  1388. this->State->SetBinaryDirectory(dir);
  1389. if (this->CurrentSnapshot.IsValid()) {
  1390. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  1391. }
  1392. }
  1393. std::string const& cmake::GetHomeOutputDirectory() const
  1394. {
  1395. return this->State->GetBinaryDirectory();
  1396. }
  1397. std::string cmake::FindCacheFile(const std::string& binaryDir)
  1398. {
  1399. std::string cachePath = binaryDir;
  1400. cmSystemTools::ConvertToUnixSlashes(cachePath);
  1401. std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt");
  1402. if (!cmSystemTools::FileExists(cacheFile)) {
  1403. // search in parent directories for cache
  1404. std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles");
  1405. if (cmSystemTools::FileExists(cmakeFiles)) {
  1406. std::string cachePathFound =
  1407. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  1408. cachePath, "/");
  1409. if (!cachePathFound.empty()) {
  1410. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  1411. }
  1412. }
  1413. }
  1414. return cachePath;
  1415. }
  1416. void cmake::SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator> gg)
  1417. {
  1418. if (!gg) {
  1419. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1420. return;
  1421. }
  1422. if (this->GlobalGenerator) {
  1423. // restore the original environment variables CXX and CC
  1424. // Restore CC
  1425. std::string env = "CC=";
  1426. if (!this->CCEnvironment.empty()) {
  1427. env += this->CCEnvironment;
  1428. }
  1429. cmSystemTools::PutEnv(env);
  1430. env = "CXX=";
  1431. if (!this->CXXEnvironment.empty()) {
  1432. env += this->CXXEnvironment;
  1433. }
  1434. cmSystemTools::PutEnv(env);
  1435. }
  1436. // set the new
  1437. this->GlobalGenerator = std::move(gg);
  1438. // set the global flag for unix style paths on cmSystemTools as soon as
  1439. // the generator is set. This allows gmake to be used on windows.
  1440. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1441. // Save the environment variables CXX and CC
  1442. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1443. this->CXXEnvironment.clear();
  1444. }
  1445. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1446. this->CCEnvironment.clear();
  1447. }
  1448. }
  1449. int cmake::DoPreConfigureChecks()
  1450. {
  1451. // Make sure the Source directory contains a CMakeLists.txt file.
  1452. std::string srcList = cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1453. if (!cmSystemTools::FileExists(srcList)) {
  1454. std::ostringstream err;
  1455. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1456. err << "The source directory \"" << this->GetHomeDirectory()
  1457. << "\" does not appear to contain CMakeLists.txt.\n";
  1458. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1459. err << "The source directory \"" << this->GetHomeDirectory()
  1460. << "\" is a file, not a directory.\n";
  1461. } else {
  1462. err << "The source directory \"" << this->GetHomeDirectory()
  1463. << "\" does not exist.\n";
  1464. }
  1465. err << "Specify --help for usage, or press the help button on the CMake "
  1466. "GUI.";
  1467. cmSystemTools::Error(err.str());
  1468. return -2;
  1469. }
  1470. // do a sanity check on some values
  1471. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1472. std::string cacheStart =
  1473. cmStrCat(*this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"),
  1474. "/CMakeLists.txt");
  1475. std::string currentStart =
  1476. cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt");
  1477. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1478. std::string message =
  1479. cmStrCat("The source \"", currentStart,
  1480. "\" does not match the source \"", cacheStart,
  1481. "\" used to generate cache. Re-run cmake with a different "
  1482. "source directory.");
  1483. cmSystemTools::Error(message);
  1484. return -2;
  1485. }
  1486. } else {
  1487. return 0;
  1488. }
  1489. return 1;
  1490. }
  1491. struct SaveCacheEntry
  1492. {
  1493. std::string key;
  1494. std::string value;
  1495. std::string help;
  1496. cmStateEnums::CacheEntryType type;
  1497. };
  1498. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1499. {
  1500. std::vector<std::string> argsSplit = cmExpandedList(var, true);
  1501. // erase the property to avoid infinite recursion
  1502. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1503. if (this->State->GetIsInTryCompile()) {
  1504. return 0;
  1505. }
  1506. std::vector<SaveCacheEntry> saved;
  1507. std::ostringstream warning;
  1508. /* clang-format off */
  1509. warning
  1510. << "You have changed variables that require your cache to be deleted.\n"
  1511. << "Configure will be re-run and you may have to reset some variables.\n"
  1512. << "The following variables have changed:\n";
  1513. /* clang-format on */
  1514. for (auto i = argsSplit.begin(); i != argsSplit.end(); ++i) {
  1515. SaveCacheEntry save;
  1516. save.key = *i;
  1517. warning << *i << "= ";
  1518. i++;
  1519. if (i != argsSplit.end()) {
  1520. save.value = *i;
  1521. warning << *i << "\n";
  1522. } else {
  1523. warning << "\n";
  1524. i -= 1;
  1525. }
  1526. cmProp existingValue = this->State->GetCacheEntryValue(save.key);
  1527. if (existingValue) {
  1528. save.type = this->State->GetCacheEntryType(save.key);
  1529. if (cmProp help =
  1530. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1531. save.help = *help;
  1532. }
  1533. } else {
  1534. save.type = cmStateEnums::CacheEntryType::UNINITIALIZED;
  1535. }
  1536. saved.push_back(std::move(save));
  1537. }
  1538. // remove the cache
  1539. this->DeleteCache(this->GetHomeOutputDirectory());
  1540. // load the empty cache
  1541. this->LoadCache();
  1542. // restore the changed compilers
  1543. for (SaveCacheEntry const& i : saved) {
  1544. this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
  1545. }
  1546. cmSystemTools::Message(warning.str());
  1547. // avoid reconfigure if there were errors
  1548. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1549. // re-run configure
  1550. return this->Configure();
  1551. }
  1552. return 0;
  1553. }
  1554. int cmake::Configure()
  1555. {
  1556. DiagLevel diagLevel;
  1557. if (this->DiagLevels.count("deprecated") == 1) {
  1558. diagLevel = this->DiagLevels["deprecated"];
  1559. if (diagLevel == DIAG_IGNORE) {
  1560. this->SetSuppressDeprecatedWarnings(true);
  1561. this->SetDeprecatedWarningsAsErrors(false);
  1562. } else if (diagLevel == DIAG_WARN) {
  1563. this->SetSuppressDeprecatedWarnings(false);
  1564. this->SetDeprecatedWarningsAsErrors(false);
  1565. } else if (diagLevel == DIAG_ERROR) {
  1566. this->SetSuppressDeprecatedWarnings(false);
  1567. this->SetDeprecatedWarningsAsErrors(true);
  1568. }
  1569. }
  1570. if (this->DiagLevels.count("dev") == 1) {
  1571. bool setDeprecatedVariables = false;
  1572. cmProp cachedWarnDeprecated =
  1573. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1574. cmProp cachedErrorDeprecated =
  1575. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1576. // don't overwrite deprecated warning setting from a previous invocation
  1577. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1578. setDeprecatedVariables = true;
  1579. }
  1580. diagLevel = this->DiagLevels["dev"];
  1581. if (diagLevel == DIAG_IGNORE) {
  1582. this->SetSuppressDevWarnings(true);
  1583. this->SetDevWarningsAsErrors(false);
  1584. if (setDeprecatedVariables) {
  1585. this->SetSuppressDeprecatedWarnings(true);
  1586. this->SetDeprecatedWarningsAsErrors(false);
  1587. }
  1588. } else if (diagLevel == DIAG_WARN) {
  1589. this->SetSuppressDevWarnings(false);
  1590. this->SetDevWarningsAsErrors(false);
  1591. if (setDeprecatedVariables) {
  1592. this->SetSuppressDeprecatedWarnings(false);
  1593. this->SetDeprecatedWarningsAsErrors(false);
  1594. }
  1595. } else if (diagLevel == DIAG_ERROR) {
  1596. this->SetSuppressDevWarnings(false);
  1597. this->SetDevWarningsAsErrors(true);
  1598. if (setDeprecatedVariables) {
  1599. this->SetSuppressDeprecatedWarnings(false);
  1600. this->SetDeprecatedWarningsAsErrors(true);
  1601. }
  1602. }
  1603. }
  1604. // Cache variables may have already been set by a previous invocation,
  1605. // so we cannot rely on command line options alone. Always ensure our
  1606. // messenger is in sync with the cache.
  1607. cmProp value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1608. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(*value));
  1609. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1610. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  1611. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1612. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  1613. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1614. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(*value));
  1615. int ret = this->ActualConfigure();
  1616. cmProp delCacheVars =
  1617. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1618. if (delCacheVars && !delCacheVars->empty()) {
  1619. return this->HandleDeleteCacheVariables(*delCacheVars);
  1620. }
  1621. return ret;
  1622. }
  1623. int cmake::ActualConfigure()
  1624. {
  1625. // Construct right now our path conversion table before it's too late:
  1626. this->UpdateConversionPathTable();
  1627. this->CleanupCommandsAndMacros();
  1628. int res = this->DoPreConfigureChecks();
  1629. if (res < 0) {
  1630. return -2;
  1631. }
  1632. if (!res) {
  1633. this->AddCacheEntry(
  1634. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory().c_str(),
  1635. "Source directory with the top level CMakeLists.txt file for this "
  1636. "project",
  1637. cmStateEnums::INTERNAL);
  1638. }
  1639. // no generator specified on the command line
  1640. if (!this->GlobalGenerator) {
  1641. cmProp genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1642. cmProp extraGenName =
  1643. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1644. if (genName) {
  1645. std::string fullName =
  1646. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1647. *genName, extraGenName ? *extraGenName : "");
  1648. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1649. }
  1650. if (this->GlobalGenerator) {
  1651. // set the global flag for unix style paths on cmSystemTools as
  1652. // soon as the generator is set. This allows gmake to be used
  1653. // on windows.
  1654. cmSystemTools::SetForceUnixPaths(
  1655. this->GlobalGenerator->GetForceUnixPaths());
  1656. } else {
  1657. this->CreateDefaultGlobalGenerator();
  1658. }
  1659. if (!this->GlobalGenerator) {
  1660. cmSystemTools::Error("Could not create generator");
  1661. return -1;
  1662. }
  1663. }
  1664. cmProp genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1665. if (genName) {
  1666. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  1667. std::string message =
  1668. cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(),
  1669. "\nDoes not match the generator used previously: ", *genName,
  1670. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1671. "directory or choose a different binary directory.");
  1672. cmSystemTools::Error(message);
  1673. return -2;
  1674. }
  1675. }
  1676. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1677. this->AddCacheEntry("CMAKE_GENERATOR",
  1678. this->GlobalGenerator->GetName().c_str(),
  1679. "Name of generator.", cmStateEnums::INTERNAL);
  1680. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1681. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1682. "Name of external makefile project generator.",
  1683. cmStateEnums::INTERNAL);
  1684. }
  1685. if (cmProp instance =
  1686. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1687. if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) {
  1688. std::string message =
  1689. cmStrCat("Error: generator instance: ", this->GeneratorInstance,
  1690. "\nDoes not match the instance used previously: ", *instance,
  1691. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1692. "directory or choose a different binary directory.");
  1693. cmSystemTools::Error(message);
  1694. return -2;
  1695. }
  1696. } else {
  1697. this->AddCacheEntry(
  1698. "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
  1699. "Generator instance identifier.", cmStateEnums::INTERNAL);
  1700. }
  1701. if (cmProp platformName =
  1702. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1703. if (this->GeneratorPlatformSet &&
  1704. this->GeneratorPlatform != *platformName) {
  1705. std::string message = cmStrCat(
  1706. "Error: generator platform: ", this->GeneratorPlatform,
  1707. "\nDoes not match the platform used previously: ", *platformName,
  1708. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1709. "directory or choose a different binary directory.");
  1710. cmSystemTools::Error(message);
  1711. return -2;
  1712. }
  1713. } else {
  1714. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1715. this->GeneratorPlatform.c_str(),
  1716. "Name of generator platform.", cmStateEnums::INTERNAL);
  1717. }
  1718. if (cmProp tsName =
  1719. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1720. if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) {
  1721. std::string message =
  1722. cmStrCat("Error: generator toolset: ", this->GeneratorToolset,
  1723. "\nDoes not match the toolset used previously: ", *tsName,
  1724. "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1725. "directory or choose a different binary directory.");
  1726. cmSystemTools::Error(message);
  1727. return -2;
  1728. }
  1729. } else {
  1730. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1731. this->GeneratorToolset.c_str(),
  1732. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1733. }
  1734. // reset any system configuration information, except for when we are
  1735. // InTryCompile. With TryCompile the system info is taken from the parent's
  1736. // info to save time
  1737. if (!this->State->GetIsInTryCompile()) {
  1738. this->GlobalGenerator->ClearEnabledLanguages();
  1739. this->TruncateOutputLog("CMakeOutput.log");
  1740. this->TruncateOutputLog("CMakeError.log");
  1741. }
  1742. #if !defined(CMAKE_BOOTSTRAP)
  1743. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  1744. this->FileAPI->ReadQueries();
  1745. #endif
  1746. // actually do the configure
  1747. this->GlobalGenerator->Configure();
  1748. // Before saving the cache
  1749. // if the project did not define one of the entries below, add them now
  1750. // so users can edit the values in the cache:
  1751. // We used to always present LIBRARY_OUTPUT_PATH and
  1752. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1753. // should no longer be used. Therefore we present them only if the
  1754. // project requires compatibility with CMake 2.4. We detect this
  1755. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1756. // variable created when CMP0001 is not set to NEW.
  1757. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1758. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1759. this->AddCacheEntry(
  1760. "LIBRARY_OUTPUT_PATH", "",
  1761. "Single output directory for building all libraries.",
  1762. cmStateEnums::PATH);
  1763. }
  1764. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1765. this->AddCacheEntry(
  1766. "EXECUTABLE_OUTPUT_PATH", "",
  1767. "Single output directory for building all executables.",
  1768. cmStateEnums::PATH);
  1769. }
  1770. }
  1771. const auto& mf = this->GlobalGenerator->GetMakefiles()[0];
  1772. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1773. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1774. cmSystemTools::Error(
  1775. "CTEST_USE_LAUNCHERS is enabled, but the "
  1776. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1777. "Did you forget to include(CTest) in the toplevel "
  1778. "CMakeLists.txt ?");
  1779. }
  1780. this->State->SaveVerificationScript(this->GetHomeOutputDirectory());
  1781. this->SaveCache(this->GetHomeOutputDirectory());
  1782. if (cmSystemTools::GetErrorOccuredFlag()) {
  1783. return -1;
  1784. }
  1785. return 0;
  1786. }
  1787. std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
  1788. {
  1789. if (!this->EnvironmentGenerator.empty()) {
  1790. auto gen = this->CreateGlobalGenerator(this->EnvironmentGenerator);
  1791. if (!gen) {
  1792. cmSystemTools::Error("CMAKE_GENERATOR was set but the specified "
  1793. "generator doesn't exist. Using CMake default.");
  1794. } else {
  1795. return gen;
  1796. }
  1797. }
  1798. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1799. std::string found;
  1800. // Try to find the newest VS installed on the computer and
  1801. // use that as a default if -G is not specified
  1802. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1803. static const char* const vsVariants[] = {
  1804. /* clang-format needs this comment to break after the opening brace */
  1805. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1806. };
  1807. struct VSVersionedGenerator
  1808. {
  1809. const char* MSVersion;
  1810. const char* GeneratorName;
  1811. };
  1812. static VSVersionedGenerator const vsGenerators[] = {
  1813. { "14.0", "Visual Studio 14 2015" }, //
  1814. { "12.0", "Visual Studio 12 2013" }, //
  1815. { "11.0", "Visual Studio 11 2012" }, //
  1816. { "10.0", "Visual Studio 10 2010" }, //
  1817. { "9.0", "Visual Studio 9 2008" }
  1818. };
  1819. static const char* const vsEntries[] = {
  1820. "\\Setup\\VC;ProductDir", //
  1821. ";InstallDir" //
  1822. };
  1823. if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  1824. found = "Visual Studio 16 2019";
  1825. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  1826. found = "Visual Studio 15 2017";
  1827. } else {
  1828. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  1829. found.empty() && g != cm::cend(vsGenerators); ++g) {
  1830. for (const char* const* v = cm::cbegin(vsVariants);
  1831. found.empty() && v != cm::cend(vsVariants); ++v) {
  1832. for (const char* const* e = cm::cbegin(vsEntries);
  1833. found.empty() && e != cm::cend(vsEntries); ++e) {
  1834. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1835. std::string dir;
  1836. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1837. cmSystemTools::KeyWOW64_32) &&
  1838. cmSystemTools::PathExists(dir)) {
  1839. found = g->GeneratorName;
  1840. }
  1841. }
  1842. }
  1843. }
  1844. }
  1845. auto gen = this->CreateGlobalGenerator(found);
  1846. if (!gen) {
  1847. gen = cm::make_unique<cmGlobalNMakeMakefileGenerator>(this);
  1848. }
  1849. return std::unique_ptr<cmGlobalGenerator>(std::move(gen));
  1850. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  1851. return std::unique_ptr<cmGlobalGenerator>(
  1852. cm::make_unique<cmGlobalNinjaGenerator>(this));
  1853. #else
  1854. return std::unique_ptr<cmGlobalGenerator>(
  1855. cm::make_unique<cmGlobalUnixMakefileGenerator3>(this));
  1856. #endif
  1857. }
  1858. void cmake::CreateDefaultGlobalGenerator()
  1859. {
  1860. auto gen = this->EvaluateDefaultGlobalGenerator();
  1861. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1862. // This print could be unified for all platforms
  1863. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1864. #endif
  1865. this->SetGlobalGenerator(std::move(gen));
  1866. }
  1867. void cmake::PreLoadCMakeFiles()
  1868. {
  1869. std::vector<std::string> args;
  1870. std::string pre_load = this->GetHomeDirectory();
  1871. if (!pre_load.empty()) {
  1872. pre_load += "/PreLoad.cmake";
  1873. if (cmSystemTools::FileExists(pre_load)) {
  1874. this->ReadListFile(args, pre_load);
  1875. }
  1876. }
  1877. pre_load = this->GetHomeOutputDirectory();
  1878. if (!pre_load.empty()) {
  1879. pre_load += "/PreLoad.cmake";
  1880. if (cmSystemTools::FileExists(pre_load)) {
  1881. this->ReadListFile(args, pre_load);
  1882. }
  1883. }
  1884. }
  1885. // handle a command line invocation
  1886. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1887. {
  1888. // Process the arguments
  1889. this->SetArgs(args);
  1890. if (cmSystemTools::GetErrorOccuredFlag()) {
  1891. return -1;
  1892. }
  1893. if (this->GetWorkingMode() == HELP_MODE) {
  1894. return 0;
  1895. }
  1896. // Log the trace format version to the desired output
  1897. if (this->GetTrace()) {
  1898. this->PrintTraceFormatVersion();
  1899. }
  1900. // If we are given a stamp list file check if it is really out of date.
  1901. if (!this->CheckStampList.empty() &&
  1902. cmakeCheckStampList(this->CheckStampList)) {
  1903. return 0;
  1904. }
  1905. // If we are given a stamp file check if it is really out of date.
  1906. if (!this->CheckStampFile.empty() &&
  1907. cmakeCheckStampFile(this->CheckStampFile)) {
  1908. return 0;
  1909. }
  1910. if (this->GetWorkingMode() == NORMAL_MODE) {
  1911. // load the cache
  1912. if (this->LoadCache() < 0) {
  1913. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1914. return -1;
  1915. }
  1916. } else {
  1917. this->AddCMakePaths();
  1918. }
  1919. #ifndef CMAKE_BOOTSTRAP
  1920. this->ProcessPresetVariables();
  1921. this->ProcessPresetEnvironment();
  1922. #endif
  1923. // Add any cache args
  1924. if (!this->SetCacheArgs(args)) {
  1925. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1926. return -1;
  1927. }
  1928. #ifndef CMAKE_BOOTSTRAP
  1929. this->PrintPresetVariables();
  1930. this->PrintPresetEnvironment();
  1931. #endif
  1932. // In script mode we terminate after running the script.
  1933. if (this->GetWorkingMode() != NORMAL_MODE) {
  1934. if (cmSystemTools::GetErrorOccuredFlag()) {
  1935. return -1;
  1936. }
  1937. return 0;
  1938. }
  1939. // If MAKEFLAGS are given in the environment, remove the environment
  1940. // variable. This will prevent try-compile from succeeding when it
  1941. // should fail (if "-i" is an option). We cannot simply test
  1942. // whether "-i" is given and remove it because some make programs
  1943. // encode the MAKEFLAGS variable in a strange way.
  1944. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1945. cmSystemTools::PutEnv("MAKEFLAGS=");
  1946. }
  1947. this->PreLoadCMakeFiles();
  1948. if (noconfigure) {
  1949. return 0;
  1950. }
  1951. // now run the global generate
  1952. // Check the state of the build system to see if we need to regenerate.
  1953. if (!this->CheckBuildSystem()) {
  1954. return 0;
  1955. }
  1956. int ret = this->Configure();
  1957. if (ret) {
  1958. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1959. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1960. // CMake is running to regenerate a Visual Studio build tree
  1961. // during a build from the VS IDE. The build files cannot be
  1962. // regenerated, so we should stop the build.
  1963. cmSystemTools::Message("CMake Configure step failed. "
  1964. "Build files cannot be regenerated correctly. "
  1965. "Attempting to stop IDE build.");
  1966. cmGlobalVisualStudioGenerator& gg =
  1967. cm::static_reference_cast<cmGlobalVisualStudioGenerator>(
  1968. this->GlobalGenerator);
  1969. gg.CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1970. this->VSSolutionFile);
  1971. }
  1972. #endif
  1973. return ret;
  1974. }
  1975. ret = this->Generate();
  1976. if (ret) {
  1977. cmSystemTools::Message("CMake Generate step failed. "
  1978. "Build files cannot be regenerated correctly.");
  1979. return ret;
  1980. }
  1981. std::string message = cmStrCat("Build files have been written to: ",
  1982. this->GetHomeOutputDirectory());
  1983. this->UpdateProgress(message, -1);
  1984. return ret;
  1985. }
  1986. int cmake::Generate()
  1987. {
  1988. if (!this->GlobalGenerator) {
  1989. return -1;
  1990. }
  1991. if (!this->GlobalGenerator->Compute()) {
  1992. return -1;
  1993. }
  1994. this->GlobalGenerator->Generate();
  1995. if (!this->GraphVizFile.empty()) {
  1996. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1997. this->GenerateGraphViz(this->GraphVizFile);
  1998. }
  1999. if (this->WarnUnusedCli) {
  2000. this->RunCheckForUnusedVariables();
  2001. }
  2002. if (cmSystemTools::GetErrorOccuredFlag()) {
  2003. return -1;
  2004. }
  2005. // Save the cache again after a successful Generate so that any internal
  2006. // variables created during Generate are saved. (Specifically target GUIDs
  2007. // for the Visual Studio and Xcode generators.)
  2008. this->SaveCache(this->GetHomeOutputDirectory());
  2009. #if !defined(CMAKE_BOOTSTRAP)
  2010. this->FileAPI->WriteReplies();
  2011. #endif
  2012. return 0;
  2013. }
  2014. void cmake::AddCacheEntry(const std::string& key, const char* value,
  2015. const char* helpString, int type)
  2016. {
  2017. this->State->AddCacheEntry(key, value, helpString,
  2018. cmStateEnums::CacheEntryType(type));
  2019. this->UnwatchUnusedCli(key);
  2020. if (key == "CMAKE_WARN_DEPRECATED"_s) {
  2021. this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value));
  2022. } else if (key == "CMAKE_ERROR_DEPRECATED"_s) {
  2023. this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value));
  2024. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS"_s) {
  2025. this->Messenger->SetSuppressDevWarnings(cmIsOn(value));
  2026. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS"_s) {
  2027. this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value));
  2028. }
  2029. }
  2030. bool cmake::DoWriteGlobVerifyTarget() const
  2031. {
  2032. return this->State->DoWriteGlobVerifyTarget();
  2033. }
  2034. std::string const& cmake::GetGlobVerifyScript() const
  2035. {
  2036. return this->State->GetGlobVerifyScript();
  2037. }
  2038. std::string const& cmake::GetGlobVerifyStamp() const
  2039. {
  2040. return this->State->GetGlobVerifyStamp();
  2041. }
  2042. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  2043. bool followSymlinks, const std::string& relative,
  2044. const std::string& expression,
  2045. const std::vector<std::string>& files,
  2046. const std::string& variable,
  2047. cmListFileBacktrace const& backtrace)
  2048. {
  2049. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  2050. relative, expression, files, variable,
  2051. backtrace);
  2052. }
  2053. std::vector<std::string> cmake::GetAllExtensions() const
  2054. {
  2055. std::vector<std::string> allExt = this->CLikeSourceFileExtensions.ordered;
  2056. allExt.insert(allExt.end(), this->HeaderFileExtensions.ordered.begin(),
  2057. this->HeaderFileExtensions.ordered.end());
  2058. // cuda extensions are also in SourceFileExtensions so we ignore it here
  2059. allExt.insert(allExt.end(), this->FortranFileExtensions.ordered.begin(),
  2060. this->FortranFileExtensions.ordered.end());
  2061. allExt.insert(allExt.end(), this->ISPCFileExtensions.ordered.begin(),
  2062. this->ISPCFileExtensions.ordered.end());
  2063. return allExt;
  2064. }
  2065. std::string cmake::StripExtension(const std::string& file) const
  2066. {
  2067. auto dotpos = file.rfind('.');
  2068. if (dotpos != std::string::npos) {
  2069. #if defined(_WIN32) || defined(__APPLE__)
  2070. auto ext = cmSystemTools::LowerCase(file.substr(dotpos + 1));
  2071. #else
  2072. auto ext = cm::string_view(file).substr(dotpos + 1);
  2073. #endif
  2074. if (this->IsAKnownExtension(ext)) {
  2075. return file.substr(0, dotpos);
  2076. }
  2077. }
  2078. return file;
  2079. }
  2080. cmProp cmake::GetCacheDefinition(const std::string& name) const
  2081. {
  2082. return this->State->GetInitializedCacheValue(name);
  2083. }
  2084. void cmake::AddScriptingCommands() const
  2085. {
  2086. GetScriptingCommands(this->GetState());
  2087. }
  2088. void cmake::AddProjectCommands() const
  2089. {
  2090. GetProjectCommands(this->GetState());
  2091. }
  2092. void cmake::AddDefaultGenerators()
  2093. {
  2094. #if defined(_WIN32) && !defined(__CYGWIN__)
  2095. # if !defined(CMAKE_BOOT_MINGW)
  2096. this->Generators.push_back(
  2097. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  2098. this->Generators.push_back(
  2099. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  2100. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  2101. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  2102. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  2103. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  2104. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  2105. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  2106. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  2107. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  2108. # endif
  2109. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  2110. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  2111. #endif
  2112. #if !defined(CMAKE_BOOTSTRAP)
  2113. # if defined(__linux__) || defined(_WIN32)
  2114. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  2115. # endif
  2116. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2117. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2118. this->Generators.push_back(cmGlobalNinjaMultiGenerator::NewFactory());
  2119. #elif defined(CMAKE_BOOTSTRAP_NINJA)
  2120. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  2121. #elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
  2122. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  2123. #endif
  2124. #if defined(CMAKE_USE_WMAKE)
  2125. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  2126. #endif
  2127. #ifdef CMAKE_USE_XCODE
  2128. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  2129. #endif
  2130. }
  2131. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  2132. std::string& value,
  2133. cmStateEnums::CacheEntryType& type)
  2134. {
  2135. return cmState::ParseCacheEntry(entry, var, value, type);
  2136. }
  2137. int cmake::LoadCache()
  2138. {
  2139. // could we not read the cache
  2140. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  2141. // if it does exist, but isn't readable then warn the user
  2142. std::string cacheFile =
  2143. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt");
  2144. if (cmSystemTools::FileExists(cacheFile)) {
  2145. cmSystemTools::Error(
  2146. "There is a CMakeCache.txt file for the current binary tree but "
  2147. "cmake does not have permission to read it. Please check the "
  2148. "permissions of the directory you are trying to run CMake on.");
  2149. return -1;
  2150. }
  2151. }
  2152. // setup CMAKE_ROOT and CMAKE_COMMAND
  2153. if (!this->AddCMakePaths()) {
  2154. return -3;
  2155. }
  2156. return 0;
  2157. }
  2158. bool cmake::LoadCache(const std::string& path)
  2159. {
  2160. std::set<std::string> emptySet;
  2161. return this->LoadCache(path, true, emptySet, emptySet);
  2162. }
  2163. bool cmake::LoadCache(const std::string& path, bool internal,
  2164. std::set<std::string>& excludes,
  2165. std::set<std::string>& includes)
  2166. {
  2167. bool result = this->State->LoadCache(path, internal, excludes, includes);
  2168. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2169. "CMAKE_CACHE_MINOR_VERSION" };
  2170. for (auto const& entry : entries) {
  2171. this->UnwatchUnusedCli(entry);
  2172. }
  2173. return result;
  2174. }
  2175. bool cmake::SaveCache(const std::string& path)
  2176. {
  2177. bool result = this->State->SaveCache(path, this->GetMessenger());
  2178. static const auto entries = { "CMAKE_CACHE_MAJOR_VERSION",
  2179. "CMAKE_CACHE_MINOR_VERSION",
  2180. "CMAKE_CACHE_PATCH_VERSION",
  2181. "CMAKE_CACHEFILE_DIR" };
  2182. for (auto const& entry : entries) {
  2183. this->UnwatchUnusedCli(entry);
  2184. }
  2185. return result;
  2186. }
  2187. bool cmake::DeleteCache(const std::string& path)
  2188. {
  2189. return this->State->DeleteCache(path);
  2190. }
  2191. void cmake::SetProgressCallback(ProgressCallbackType f)
  2192. {
  2193. this->ProgressCallback = std::move(f);
  2194. }
  2195. void cmake::UpdateProgress(const std::string& msg, float prog)
  2196. {
  2197. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  2198. this->ProgressCallback(msg, prog);
  2199. }
  2200. }
  2201. bool cmake::GetIsInTryCompile() const
  2202. {
  2203. return this->State->GetIsInTryCompile();
  2204. }
  2205. void cmake::SetIsInTryCompile(bool b)
  2206. {
  2207. this->State->SetIsInTryCompile(b);
  2208. }
  2209. void cmake::AppendGlobalGeneratorsDocumentation(
  2210. std::vector<cmDocumentationEntry>& v)
  2211. {
  2212. const auto defaultGenerator = this->EvaluateDefaultGlobalGenerator();
  2213. const std::string defaultName = defaultGenerator->GetName();
  2214. bool foundDefaultOne = false;
  2215. for (const auto& g : this->Generators) {
  2216. cmDocumentationEntry e;
  2217. g->GetDocumentation(e);
  2218. if (!foundDefaultOne && cmHasPrefix(e.Name, defaultName)) {
  2219. e.CustomNamePrefix = '*';
  2220. foundDefaultOne = true;
  2221. }
  2222. v.push_back(std::move(e));
  2223. }
  2224. }
  2225. void cmake::AppendExtraGeneratorsDocumentation(
  2226. std::vector<cmDocumentationEntry>& v)
  2227. {
  2228. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  2229. const std::string doc = eg->GetDocumentation();
  2230. const std::string name = eg->GetName();
  2231. // Aliases:
  2232. for (std::string const& a : eg->Aliases) {
  2233. cmDocumentationEntry e;
  2234. e.Name = a;
  2235. e.Brief = doc;
  2236. v.push_back(std::move(e));
  2237. }
  2238. // Full names:
  2239. const std::vector<std::string> generators =
  2240. eg->GetSupportedGlobalGenerators();
  2241. for (std::string const& g : generators) {
  2242. cmDocumentationEntry e;
  2243. e.Name =
  2244. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  2245. e.Brief = doc;
  2246. v.push_back(std::move(e));
  2247. }
  2248. }
  2249. }
  2250. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  2251. {
  2252. std::vector<cmDocumentationEntry> v;
  2253. this->AppendGlobalGeneratorsDocumentation(v);
  2254. this->AppendExtraGeneratorsDocumentation(v);
  2255. return v;
  2256. }
  2257. void cmake::PrintGeneratorList()
  2258. {
  2259. #ifndef CMAKE_BOOTSTRAP
  2260. cmDocumentation doc;
  2261. auto generators = this->GetGeneratorsDocumentation();
  2262. doc.AppendSection("Generators", generators);
  2263. std::cerr << "\n";
  2264. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  2265. #endif
  2266. }
  2267. void cmake::UpdateConversionPathTable()
  2268. {
  2269. // Update the path conversion table with any specified file:
  2270. cmProp tablepath =
  2271. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  2272. if (tablepath) {
  2273. cmsys::ifstream table(tablepath->c_str());
  2274. if (!table) {
  2275. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to " + *tablepath +
  2276. ". CMake can not open file.");
  2277. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  2278. } else {
  2279. std::string a;
  2280. std::string b;
  2281. while (!table.eof()) {
  2282. // two entries per line
  2283. table >> a;
  2284. table >> b;
  2285. cmSystemTools::AddTranslationPath(a, b);
  2286. }
  2287. }
  2288. }
  2289. }
  2290. int cmake::CheckBuildSystem()
  2291. {
  2292. // We do not need to rerun CMake. Check dependency integrity.
  2293. const bool verbose = isCMakeVerbose();
  2294. // This method will check the integrity of the build system if the
  2295. // option was given on the command line. It reads the given file to
  2296. // determine whether CMake should rerun.
  2297. // If no file is provided for the check, we have to rerun.
  2298. if (this->CheckBuildSystemArgument.empty()) {
  2299. if (verbose) {
  2300. cmSystemTools::Stdout("Re-run cmake no build system arguments\n");
  2301. }
  2302. return 1;
  2303. }
  2304. // If the file provided does not exist, we have to rerun.
  2305. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  2306. if (verbose) {
  2307. std::ostringstream msg;
  2308. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  2309. << "\n";
  2310. cmSystemTools::Stdout(msg.str());
  2311. }
  2312. return 1;
  2313. }
  2314. // Read the rerun check file and use it to decide whether to do the
  2315. // global generate.
  2316. // Actually, all we need is the `set` command.
  2317. cmake cm(RoleScript, cmState::Unknown);
  2318. cm.SetHomeDirectory("");
  2319. cm.SetHomeOutputDirectory("");
  2320. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2321. cmGlobalGenerator gg(&cm);
  2322. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  2323. if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
  2324. cmSystemTools::GetErrorOccuredFlag()) {
  2325. if (verbose) {
  2326. std::ostringstream msg;
  2327. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  2328. << "\n";
  2329. cmSystemTools::Stdout(msg.str());
  2330. }
  2331. // There was an error reading the file. Just rerun.
  2332. return 1;
  2333. }
  2334. if (this->ClearBuildSystem) {
  2335. // Get the generator used for this build system.
  2336. const char* genName =
  2337. cmToCStr(mf.GetDefinition("CMAKE_DEPENDS_GENERATOR"));
  2338. if (!cmNonempty(genName)) {
  2339. genName = "Unix Makefiles";
  2340. }
  2341. // Create the generator and use it to clear the dependencies.
  2342. std::unique_ptr<cmGlobalGenerator> ggd =
  2343. this->CreateGlobalGenerator(genName);
  2344. if (ggd) {
  2345. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2346. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  2347. auto lgd = ggd->CreateLocalGenerator(&mfd);
  2348. lgd->ClearDependencies(&mfd, verbose);
  2349. }
  2350. }
  2351. // If any byproduct of makefile generation is missing we must re-run.
  2352. std::vector<std::string> products;
  2353. mf.GetDefExpandList("CMAKE_MAKEFILE_PRODUCTS", products);
  2354. for (std::string const& p : products) {
  2355. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  2356. if (verbose) {
  2357. std::ostringstream msg;
  2358. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  2359. cmSystemTools::Stdout(msg.str());
  2360. }
  2361. return 1;
  2362. }
  2363. }
  2364. // Get the set of dependencies and outputs.
  2365. std::vector<std::string> depends;
  2366. std::vector<std::string> outputs;
  2367. if (mf.GetDefExpandList("CMAKE_MAKEFILE_DEPENDS", depends)) {
  2368. mf.GetDefExpandList("CMAKE_MAKEFILE_OUTPUTS", outputs);
  2369. }
  2370. if (depends.empty() || outputs.empty()) {
  2371. // Not enough information was provided to do the test. Just rerun.
  2372. if (verbose) {
  2373. cmSystemTools::Stdout("Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  2374. "or CMAKE_MAKEFILE_OUTPUTS :\n");
  2375. }
  2376. return 1;
  2377. }
  2378. // Find the newest dependency.
  2379. auto dep = depends.begin();
  2380. std::string dep_newest = *dep++;
  2381. for (; dep != depends.end(); ++dep) {
  2382. int result = 0;
  2383. if (this->FileTimeCache->Compare(dep_newest, *dep, &result)) {
  2384. if (result < 0) {
  2385. dep_newest = *dep;
  2386. }
  2387. } else {
  2388. if (verbose) {
  2389. cmSystemTools::Stdout(
  2390. "Re-run cmake: build system dependency is missing\n");
  2391. }
  2392. return 1;
  2393. }
  2394. }
  2395. // Find the oldest output.
  2396. auto out = outputs.begin();
  2397. std::string out_oldest = *out++;
  2398. for (; out != outputs.end(); ++out) {
  2399. int result = 0;
  2400. if (this->FileTimeCache->Compare(out_oldest, *out, &result)) {
  2401. if (result > 0) {
  2402. out_oldest = *out;
  2403. }
  2404. } else {
  2405. if (verbose) {
  2406. cmSystemTools::Stdout(
  2407. "Re-run cmake: build system output is missing\n");
  2408. }
  2409. return 1;
  2410. }
  2411. }
  2412. // If any output is older than any dependency then rerun.
  2413. {
  2414. int result = 0;
  2415. if (!this->FileTimeCache->Compare(out_oldest, dep_newest, &result) ||
  2416. result < 0) {
  2417. if (verbose) {
  2418. std::ostringstream msg;
  2419. msg << "Re-run cmake file: " << out_oldest
  2420. << " older than: " << dep_newest << "\n";
  2421. cmSystemTools::Stdout(msg.str());
  2422. }
  2423. return 1;
  2424. }
  2425. }
  2426. // No need to rerun.
  2427. return 0;
  2428. }
  2429. void cmake::TruncateOutputLog(const char* fname)
  2430. {
  2431. std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname);
  2432. struct stat st;
  2433. if (::stat(fullPath.c_str(), &st)) {
  2434. return;
  2435. }
  2436. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  2437. cmSystemTools::RemoveFile(fullPath);
  2438. return;
  2439. }
  2440. off_t fsize = st.st_size;
  2441. const off_t maxFileSize = 50 * 1024;
  2442. if (fsize < maxFileSize) {
  2443. // TODO: truncate file
  2444. return;
  2445. }
  2446. }
  2447. void cmake::MarkCliAsUsed(const std::string& variable)
  2448. {
  2449. this->UsedCliVariables[variable] = true;
  2450. }
  2451. void cmake::GenerateGraphViz(const std::string& fileName) const
  2452. {
  2453. #ifndef CMAKE_BOOTSTRAP
  2454. cmGraphVizWriter gvWriter(fileName, this->GetGlobalGenerator());
  2455. std::string settingsFile =
  2456. cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake");
  2457. std::string fallbackSettingsFile =
  2458. cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake");
  2459. gvWriter.ReadSettings(settingsFile, fallbackSettingsFile);
  2460. gvWriter.Write();
  2461. #endif
  2462. }
  2463. void cmake::SetProperty(const std::string& prop, const char* value)
  2464. {
  2465. this->State->SetGlobalProperty(prop, value);
  2466. }
  2467. void cmake::AppendProperty(const std::string& prop, const std::string& value,
  2468. bool asString)
  2469. {
  2470. this->State->AppendGlobalProperty(prop, value, asString);
  2471. }
  2472. cmProp cmake::GetProperty(const std::string& prop)
  2473. {
  2474. return this->State->GetGlobalProperty(prop);
  2475. }
  2476. bool cmake::GetPropertyAsBool(const std::string& prop)
  2477. {
  2478. return this->State->GetGlobalPropertyAsBool(prop);
  2479. }
  2480. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2481. const std::string& name)
  2482. {
  2483. auto i = this->InstalledFiles.find(name);
  2484. if (i != this->InstalledFiles.end()) {
  2485. cmInstalledFile& file = i->second;
  2486. return &file;
  2487. }
  2488. cmInstalledFile& file = this->InstalledFiles[name];
  2489. file.SetName(mf, name);
  2490. return &file;
  2491. }
  2492. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2493. {
  2494. auto i = this->InstalledFiles.find(name);
  2495. if (i != this->InstalledFiles.end()) {
  2496. cmInstalledFile const& file = i->second;
  2497. return &file;
  2498. }
  2499. return nullptr;
  2500. }
  2501. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2502. {
  2503. // so create the directory
  2504. std::string resultFile;
  2505. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2506. std::string destPath = cwd + "/__cmake_systeminformation";
  2507. cmSystemTools::RemoveADirectory(destPath);
  2508. if (!cmSystemTools::MakeDirectory(destPath)) {
  2509. std::cerr << "Error: --system-information must be run from a "
  2510. "writable directory!\n";
  2511. return 1;
  2512. }
  2513. // process the arguments
  2514. bool writeToStdout = true;
  2515. for (unsigned int i = 1; i < args.size(); ++i) {
  2516. std::string const& arg = args[i];
  2517. if (cmHasLiteralPrefix(arg, "-G")) {
  2518. std::string value = arg.substr(2);
  2519. if (value.empty()) {
  2520. ++i;
  2521. if (i >= args.size()) {
  2522. cmSystemTools::Error("No generator specified for -G");
  2523. this->PrintGeneratorList();
  2524. return -1;
  2525. }
  2526. value = args[i];
  2527. }
  2528. auto gen = this->CreateGlobalGenerator(value);
  2529. if (!gen) {
  2530. cmSystemTools::Error("Could not create named generator " + value);
  2531. this->PrintGeneratorList();
  2532. } else {
  2533. this->SetGlobalGenerator(std::move(gen));
  2534. }
  2535. }
  2536. // no option assume it is the output file
  2537. else {
  2538. if (!cmSystemTools::FileIsFullPath(arg)) {
  2539. resultFile = cmStrCat(cwd, '/');
  2540. }
  2541. resultFile += arg;
  2542. writeToStdout = false;
  2543. }
  2544. }
  2545. // we have to find the module directory, so we can copy the files
  2546. this->AddCMakePaths();
  2547. std::string modulesPath =
  2548. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules");
  2549. std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake");
  2550. std::string outFile = cmStrCat(destPath, "/CMakeLists.txt");
  2551. // Copy file
  2552. if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
  2553. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2554. << "\".\n";
  2555. return 1;
  2556. }
  2557. // do we write to a file or to stdout?
  2558. if (resultFile.empty()) {
  2559. resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt");
  2560. }
  2561. {
  2562. // now run cmake on the CMakeLists file
  2563. cmWorkingDirectory workdir(destPath);
  2564. if (workdir.Failed()) {
  2565. // We created the directory and we were able to copy the CMakeLists.txt
  2566. // file to it, so we wouldn't expect to get here unless the default
  2567. // permissions are questionable or some other process has deleted the
  2568. // directory
  2569. std::cerr << "Failed to change to directory " << destPath << " : "
  2570. << std::strerror(workdir.GetLastResult()) << std::endl;
  2571. return 1;
  2572. }
  2573. std::vector<std::string> args2;
  2574. args2.push_back(args[0]);
  2575. args2.push_back(destPath);
  2576. args2.push_back("-DRESULT_FILE=" + resultFile);
  2577. int res = this->Run(args2, false);
  2578. if (res != 0) {
  2579. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2580. return res;
  2581. }
  2582. }
  2583. // echo results to stdout if needed
  2584. if (writeToStdout) {
  2585. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2586. if (fin) {
  2587. const int bufferSize = 4096;
  2588. char buffer[bufferSize];
  2589. size_t n;
  2590. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2591. for (char* c = buffer; c < buffer + n; ++c) {
  2592. putc(*c, stdout);
  2593. }
  2594. fflush(stdout);
  2595. }
  2596. fclose(fin);
  2597. }
  2598. }
  2599. // clean up the directory
  2600. cmSystemTools::RemoveADirectory(destPath);
  2601. return 0;
  2602. }
  2603. static bool cmakeCheckStampFile(const std::string& stampName)
  2604. {
  2605. // The stamp file does not exist. Use the stamp dependencies to
  2606. // determine whether it is really out of date. This works in
  2607. // conjunction with cmLocalVisualStudio7Generator to avoid
  2608. // repeatedly re-running CMake when the user rebuilds the entire
  2609. // solution.
  2610. std::string stampDepends = cmStrCat(stampName, ".depend");
  2611. #if defined(_WIN32) || defined(__CYGWIN__)
  2612. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2613. #else
  2614. cmsys::ifstream fin(stampDepends.c_str());
  2615. #endif
  2616. if (!fin) {
  2617. // The stamp dependencies file cannot be read. Just assume the
  2618. // build system is really out of date.
  2619. std::cout << "CMake is re-running because " << stampName
  2620. << " dependency file is missing.\n";
  2621. return false;
  2622. }
  2623. // Compare the stamp dependencies against the dependency file itself.
  2624. {
  2625. cmFileTimeCache ftc;
  2626. std::string dep;
  2627. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2628. int result;
  2629. if (!dep.empty() && dep[0] != '#' &&
  2630. (!ftc.Compare(stampDepends, dep, &result) || result < 0)) {
  2631. // The stamp depends file is older than this dependency. The
  2632. // build system is really out of date.
  2633. std::cout << "CMake is re-running because " << stampName
  2634. << " is out-of-date.\n";
  2635. std::cout << " the file '" << dep << "'\n";
  2636. std::cout << " is newer than '" << stampDepends << "'\n";
  2637. std::cout << " result='" << result << "'\n";
  2638. return false;
  2639. }
  2640. }
  2641. }
  2642. // The build system is up to date. The stamp file has been removed
  2643. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2644. std::ostringstream stampTempStream;
  2645. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2646. std::string stampTemp = stampTempStream.str();
  2647. {
  2648. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2649. // multiple tries in unlikely case of conflict) and use that here.
  2650. cmsys::ofstream stamp(stampTemp.c_str());
  2651. stamp << "# CMake generation timestamp file for this directory.\n";
  2652. }
  2653. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2654. // CMake does not need to re-run because the stamp file is up-to-date.
  2655. return true;
  2656. }
  2657. cmSystemTools::RemoveFile(stampTemp);
  2658. cmSystemTools::Error("Cannot restore timestamp " + stampName);
  2659. return false;
  2660. }
  2661. static bool cmakeCheckStampList(const std::string& stampList)
  2662. {
  2663. // If the stamp list does not exist CMake must rerun to generate it.
  2664. if (!cmSystemTools::FileExists(stampList)) {
  2665. std::cout << "CMake is re-running because generate.stamp.list "
  2666. << "is missing.\n";
  2667. return false;
  2668. }
  2669. cmsys::ifstream fin(stampList.c_str());
  2670. if (!fin) {
  2671. std::cout << "CMake is re-running because generate.stamp.list "
  2672. << "could not be read.\n";
  2673. return false;
  2674. }
  2675. // Check each stamp.
  2676. std::string stampName;
  2677. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2678. if (!cmakeCheckStampFile(stampName)) {
  2679. return false;
  2680. }
  2681. }
  2682. return true;
  2683. }
  2684. void cmake::IssueMessage(MessageType t, std::string const& text,
  2685. cmListFileBacktrace const& backtrace) const
  2686. {
  2687. this->Messenger->IssueMessage(t, text, backtrace);
  2688. }
  2689. std::vector<std::string> cmake::GetDebugConfigs()
  2690. {
  2691. std::vector<std::string> configs;
  2692. if (cmProp config_list =
  2693. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2694. // Expand the specified list and convert to upper-case.
  2695. cmExpandList(*config_list, configs);
  2696. std::transform(configs.begin(), configs.end(), configs.begin(),
  2697. cmSystemTools::UpperCase);
  2698. }
  2699. // If no configurations were specified, use a default list.
  2700. if (configs.empty()) {
  2701. configs.emplace_back("DEBUG");
  2702. }
  2703. return configs;
  2704. }
  2705. int cmake::Build(int jobs, const std::string& dir,
  2706. const std::vector<std::string>& targets,
  2707. const std::string& config,
  2708. const std::vector<std::string>& nativeOptions, bool clean,
  2709. bool verbose)
  2710. {
  2711. this->SetHomeDirectory("");
  2712. this->SetHomeOutputDirectory("");
  2713. if (!cmSystemTools::FileIsDirectory(dir)) {
  2714. std::cerr << "Error: " << dir << " is not a directory\n";
  2715. return 1;
  2716. }
  2717. std::string cachePath = FindCacheFile(dir);
  2718. if (!this->LoadCache(cachePath)) {
  2719. std::cerr << "Error: could not load cache\n";
  2720. return 1;
  2721. }
  2722. cmProp cachedGenerator = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2723. if (!cachedGenerator) {
  2724. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2725. return 1;
  2726. }
  2727. auto gen = this->CreateGlobalGenerator(*cachedGenerator);
  2728. if (!gen) {
  2729. std::cerr << "Error: could create CMAKE_GENERATOR \"" << *cachedGenerator
  2730. << "\"\n";
  2731. return 1;
  2732. }
  2733. this->SetGlobalGenerator(std::move(gen));
  2734. cmProp cachedGeneratorInstance =
  2735. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  2736. if (cachedGeneratorInstance) {
  2737. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2738. if (!this->GlobalGenerator->SetGeneratorInstance(*cachedGeneratorInstance,
  2739. &mf)) {
  2740. return 1;
  2741. }
  2742. }
  2743. cmProp cachedGeneratorPlatform =
  2744. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  2745. if (cachedGeneratorPlatform) {
  2746. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2747. if (!this->GlobalGenerator->SetGeneratorPlatform(*cachedGeneratorPlatform,
  2748. &mf)) {
  2749. return 1;
  2750. }
  2751. }
  2752. cmProp cachedGeneratorToolset =
  2753. this->State->GetCacheEntryValue("CMAKE_GENERATOR_TOOLSET");
  2754. if (cachedGeneratorToolset) {
  2755. cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
  2756. if (!this->GlobalGenerator->SetGeneratorToolset(*cachedGeneratorToolset,
  2757. true, &mf)) {
  2758. return 1;
  2759. }
  2760. }
  2761. std::string output;
  2762. std::string projName;
  2763. cmProp cachedProjectName =
  2764. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2765. if (!cachedProjectName) {
  2766. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2767. return 1;
  2768. }
  2769. projName = *cachedProjectName;
  2770. if (cmIsOn(this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE"))) {
  2771. verbose = true;
  2772. }
  2773. #ifdef CMAKE_HAVE_VS_GENERATORS
  2774. // For VS generators, explicitly check if regeneration is necessary before
  2775. // actually starting the build. If not done separately from the build
  2776. // itself, there is the risk of building an out-of-date solution file due
  2777. // to limitations of the underlying build system.
  2778. std::string const stampList = cachePath + "/" + "CMakeFiles/" +
  2779. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  2780. // Note that the stampList file only exists for VS generators.
  2781. if (cmSystemTools::FileExists(stampList)) {
  2782. // Check if running for Visual Studio 9 - we need to explicitly run
  2783. // the glob verification script before starting the build
  2784. this->AddScriptingCommands();
  2785. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  2786. std::string const globVerifyScript =
  2787. cachePath + "/" + "CMakeFiles/" + "VerifyGlobs.cmake";
  2788. if (cmSystemTools::FileExists(globVerifyScript)) {
  2789. std::vector<std::string> args;
  2790. this->ReadListFile(args, globVerifyScript);
  2791. }
  2792. }
  2793. if (!cmakeCheckStampList(stampList)) {
  2794. // Correctly initialize the home (=source) and home output (=binary)
  2795. // directories, which is required for running the generation step.
  2796. std::string homeOrig = this->GetHomeDirectory();
  2797. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  2798. this->SetDirectoriesFromFile(cachePath);
  2799. this->AddProjectCommands();
  2800. int ret = this->Configure();
  2801. if (ret) {
  2802. cmSystemTools::Message("CMake Configure step failed. "
  2803. "Build files cannot be regenerated correctly.");
  2804. return ret;
  2805. }
  2806. ret = this->Generate();
  2807. if (ret) {
  2808. cmSystemTools::Message("CMake Generate step failed. "
  2809. "Build files cannot be regenerated correctly.");
  2810. return ret;
  2811. }
  2812. std::string message = cmStrCat("Build files have been written to: ",
  2813. this->GetHomeOutputDirectory());
  2814. this->UpdateProgress(message, -1);
  2815. // Restore the previously set directories to their original value.
  2816. this->SetHomeDirectory(homeOrig);
  2817. this->SetHomeOutputDirectory(homeOutputOrig);
  2818. }
  2819. }
  2820. #endif
  2821. if (!this->GlobalGenerator->ReadCacheEntriesForBuild(*this->State)) {
  2822. return 1;
  2823. }
  2824. this->GlobalGenerator->PrintBuildCommandAdvice(std::cerr, jobs);
  2825. return this->GlobalGenerator->Build(
  2826. jobs, "", dir, projName, targets, output, "", config, clean, false,
  2827. verbose, cmDuration::zero(), cmSystemTools::OUTPUT_PASSTHROUGH,
  2828. nativeOptions);
  2829. }
  2830. bool cmake::Open(const std::string& dir, bool dryRun)
  2831. {
  2832. this->SetHomeDirectory("");
  2833. this->SetHomeOutputDirectory("");
  2834. if (!cmSystemTools::FileIsDirectory(dir)) {
  2835. std::cerr << "Error: " << dir << " is not a directory\n";
  2836. return false;
  2837. }
  2838. std::string cachePath = FindCacheFile(dir);
  2839. if (!this->LoadCache(cachePath)) {
  2840. std::cerr << "Error: could not load cache\n";
  2841. return false;
  2842. }
  2843. cmProp genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2844. if (!genName) {
  2845. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2846. return false;
  2847. }
  2848. cmProp extraGenName =
  2849. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  2850. std::string fullName =
  2851. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  2852. *genName, extraGenName ? *extraGenName : "");
  2853. std::unique_ptr<cmGlobalGenerator> gen =
  2854. this->CreateGlobalGenerator(fullName);
  2855. if (!gen) {
  2856. std::cerr << "Error: could create CMAKE_GENERATOR \"" << fullName
  2857. << "\"\n";
  2858. return false;
  2859. }
  2860. cmProp cachedProjectName =
  2861. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2862. if (!cachedProjectName) {
  2863. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2864. return false;
  2865. }
  2866. return gen->Open(dir, *cachedProjectName, dryRun);
  2867. }
  2868. void cmake::WatchUnusedCli(const std::string& var)
  2869. {
  2870. #ifndef CMAKE_BOOTSTRAP
  2871. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2872. if (!cm::contains(this->UsedCliVariables, var)) {
  2873. this->UsedCliVariables[var] = false;
  2874. }
  2875. #endif
  2876. }
  2877. void cmake::UnwatchUnusedCli(const std::string& var)
  2878. {
  2879. #ifndef CMAKE_BOOTSTRAP
  2880. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2881. this->UsedCliVariables.erase(var);
  2882. #endif
  2883. }
  2884. void cmake::RunCheckForUnusedVariables()
  2885. {
  2886. #ifndef CMAKE_BOOTSTRAP
  2887. bool haveUnused = false;
  2888. std::ostringstream msg;
  2889. msg << "Manually-specified variables were not used by the project:";
  2890. for (auto const& it : this->UsedCliVariables) {
  2891. if (!it.second) {
  2892. haveUnused = true;
  2893. msg << "\n " << it.first;
  2894. }
  2895. }
  2896. if (haveUnused) {
  2897. this->IssueMessage(MessageType::WARNING, msg.str());
  2898. }
  2899. #endif
  2900. }
  2901. bool cmake::GetSuppressDevWarnings() const
  2902. {
  2903. return this->Messenger->GetSuppressDevWarnings();
  2904. }
  2905. void cmake::SetSuppressDevWarnings(bool b)
  2906. {
  2907. std::string value;
  2908. // equivalent to -Wno-dev
  2909. if (b) {
  2910. value = "TRUE";
  2911. }
  2912. // equivalent to -Wdev
  2913. else {
  2914. value = "FALSE";
  2915. }
  2916. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2917. "Suppress Warnings that are meant for"
  2918. " the author of the CMakeLists.txt files.",
  2919. cmStateEnums::INTERNAL);
  2920. }
  2921. bool cmake::GetSuppressDeprecatedWarnings() const
  2922. {
  2923. return this->Messenger->GetSuppressDeprecatedWarnings();
  2924. }
  2925. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2926. {
  2927. std::string value;
  2928. // equivalent to -Wno-deprecated
  2929. if (b) {
  2930. value = "FALSE";
  2931. }
  2932. // equivalent to -Wdeprecated
  2933. else {
  2934. value = "TRUE";
  2935. }
  2936. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2937. "Whether to issue warnings for deprecated "
  2938. "functionality.",
  2939. cmStateEnums::INTERNAL);
  2940. }
  2941. bool cmake::GetDevWarningsAsErrors() const
  2942. {
  2943. return this->Messenger->GetDevWarningsAsErrors();
  2944. }
  2945. void cmake::SetDevWarningsAsErrors(bool b)
  2946. {
  2947. std::string value;
  2948. // equivalent to -Werror=dev
  2949. if (b) {
  2950. value = "FALSE";
  2951. }
  2952. // equivalent to -Wno-error=dev
  2953. else {
  2954. value = "TRUE";
  2955. }
  2956. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2957. "Suppress errors that are meant for"
  2958. " the author of the CMakeLists.txt files.",
  2959. cmStateEnums::INTERNAL);
  2960. }
  2961. bool cmake::GetDeprecatedWarningsAsErrors() const
  2962. {
  2963. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2964. }
  2965. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2966. {
  2967. std::string value;
  2968. // equivalent to -Werror=deprecated
  2969. if (b) {
  2970. value = "TRUE";
  2971. }
  2972. // equivalent to -Wno-error=deprecated
  2973. else {
  2974. value = "FALSE";
  2975. }
  2976. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2977. "Whether to issue deprecation errors for macros"
  2978. " and functions.",
  2979. cmStateEnums::INTERNAL);
  2980. }
  2981. #if !defined(CMAKE_BOOTSTRAP)
  2982. cmMakefileProfilingData& cmake::GetProfilingOutput()
  2983. {
  2984. return *(this->ProfilingOutput);
  2985. }
  2986. bool cmake::IsProfilingEnabled() const
  2987. {
  2988. return static_cast<bool>(this->ProfilingOutput);
  2989. }
  2990. #endif