cmFindPackageCommand.cxx 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315
  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 "cmFindPackageCommand.h"
  4. #include "cmSystemTools.h"
  5. #include "cmsys/Directory.hxx"
  6. #include "cmsys/FStream.hxx"
  7. #include "cmsys/Glob.hxx"
  8. #include "cmsys/RegularExpression.hxx"
  9. #include "cmsys/String.h"
  10. #include <algorithm>
  11. #include <assert.h>
  12. #include <deque>
  13. #include <functional>
  14. #include <iterator>
  15. #include <memory> // IWYU pragma: keep
  16. #include <sstream>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <utility>
  20. #include "cmAlgorithms.h"
  21. #include "cmMakefile.h"
  22. #include "cmMessageType.h"
  23. #include "cmPolicies.h"
  24. #include "cmRange.h"
  25. #include "cmSearchPath.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmVersion.h"
  29. #if defined(__HAIKU__)
  30. # include <FindDirectory.h>
  31. # include <StorageDefs.h>
  32. #endif
  33. class cmExecutionStatus;
  34. class cmFileList;
  35. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  36. "PACKAGE_REGISTRY");
  37. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  38. "BUILDS");
  39. cmFindPackageCommand::PathLabel
  40. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  41. struct StrverscmpGreater
  42. {
  43. bool operator()(const std::string& lhs, const std::string& rhs) const
  44. {
  45. return cmSystemTools::strverscmp(lhs, rhs) > 0;
  46. }
  47. };
  48. struct StrverscmpLesser
  49. {
  50. bool operator()(const std::string& lhs, const std::string& rhs) const
  51. {
  52. return cmSystemTools::strverscmp(lhs, rhs) < 0;
  53. }
  54. };
  55. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  56. std::vector<std::string>::iterator end,
  57. SortOrderType order, SortDirectionType dir)
  58. {
  59. if (order == Name_order) {
  60. if (dir == Dec) {
  61. std::sort(begin, end, std::greater<std::string>());
  62. } else {
  63. std::sort(begin, end);
  64. }
  65. } else if (order == Natural)
  66. // natural order uses letters and numbers (contiguous numbers digit are
  67. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  68. {
  69. if (dir == Dec) {
  70. std::sort(begin, end, StrverscmpGreater());
  71. } else {
  72. std::sort(begin, end, StrverscmpLesser());
  73. }
  74. }
  75. // else do not sort
  76. }
  77. cmFindPackageCommand::cmFindPackageCommand()
  78. {
  79. this->CMakePathName = "PACKAGE";
  80. this->Quiet = false;
  81. this->Required = false;
  82. this->NoUserRegistry = false;
  83. this->NoSystemRegistry = false;
  84. this->UseConfigFiles = true;
  85. this->UseFindModules = true;
  86. this->DebugMode = false;
  87. this->UseLib32Paths = false;
  88. this->UseLib64Paths = false;
  89. this->UseLibx32Paths = false;
  90. this->UseRealPath = false;
  91. this->PolicyScope = true;
  92. this->VersionMajor = 0;
  93. this->VersionMinor = 0;
  94. this->VersionPatch = 0;
  95. this->VersionTweak = 0;
  96. this->VersionCount = 0;
  97. this->VersionExact = false;
  98. this->VersionFoundMajor = 0;
  99. this->VersionFoundMinor = 0;
  100. this->VersionFoundPatch = 0;
  101. this->VersionFoundTweak = 0;
  102. this->VersionFoundCount = 0;
  103. this->RequiredCMakeVersion = 0;
  104. this->SortOrder = None;
  105. this->SortDirection = Asc;
  106. this->AppendSearchPathGroups();
  107. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  108. }
  109. void cmFindPackageCommand::AppendSearchPathGroups()
  110. {
  111. std::vector<cmFindCommon::PathLabel>* labels;
  112. // Update the All group with new paths
  113. labels = &this->PathGroupLabelMap[PathGroup::All];
  114. labels->insert(
  115. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  116. PathLabel::UserRegistry);
  117. labels->insert(
  118. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  119. PathLabel::Builds);
  120. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  121. PathLabel::SystemRegistry);
  122. // Create the new path objects
  123. this->LabeledPaths.insert(
  124. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  125. this->LabeledPaths.insert(
  126. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  127. this->LabeledPaths.insert(
  128. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  129. }
  130. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
  131. cmExecutionStatus&)
  132. {
  133. if (args.empty()) {
  134. this->SetError("called with incorrect number of arguments");
  135. return false;
  136. }
  137. // Lookup required version of CMake.
  138. if (const char* rv =
  139. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  140. unsigned int v[3] = { 0, 0, 0 };
  141. sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
  142. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  143. }
  144. // Check for debug mode.
  145. this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
  146. // Lookup target architecture, if any.
  147. if (const char* arch =
  148. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  149. this->LibraryArchitecture = arch;
  150. }
  151. // Lookup whether lib32 paths should be used.
  152. if (this->Makefile->PlatformIs32Bit() &&
  153. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  154. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  155. this->UseLib32Paths = true;
  156. }
  157. // Lookup whether lib64 paths should be used.
  158. if (this->Makefile->PlatformIs64Bit() &&
  159. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  160. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  161. this->UseLib64Paths = true;
  162. }
  163. // Lookup whether libx32 paths should be used.
  164. if (this->Makefile->PlatformIsx32() &&
  165. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  166. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  167. this->UseLibx32Paths = true;
  168. }
  169. // Check if User Package Registry should be disabled
  170. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  171. this->NoUserRegistry = true;
  172. }
  173. // Check if System Package Registry should be disabled
  174. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  175. this->NoSystemRegistry = true;
  176. }
  177. // Check whether we should resolve symlinks when finding packages
  178. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  179. this->UseRealPath = true;
  180. }
  181. // Check if Sorting should be enabled
  182. if (const char* so =
  183. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  184. if (strcmp(so, "NAME") == 0) {
  185. this->SortOrder = Name_order;
  186. } else if (strcmp(so, "NATURAL") == 0) {
  187. this->SortOrder = Natural;
  188. } else {
  189. this->SortOrder = None;
  190. }
  191. }
  192. if (const char* sd =
  193. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  194. this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec;
  195. }
  196. // Find the current root path mode.
  197. this->SelectDefaultRootPathMode();
  198. // Find the current bundle/framework search policy.
  199. this->SelectDefaultMacMode();
  200. // Record options.
  201. this->Name = args[0];
  202. std::string components;
  203. const char* components_sep = "";
  204. std::set<std::string> requiredComponents;
  205. std::set<std::string> optionalComponents;
  206. // Always search directly in a generated path.
  207. this->SearchPathSuffixes.emplace_back();
  208. // Parse the arguments.
  209. enum Doing
  210. {
  211. DoingNone,
  212. DoingComponents,
  213. DoingOptionalComponents,
  214. DoingNames,
  215. DoingPaths,
  216. DoingPathSuffixes,
  217. DoingConfigs,
  218. DoingHints
  219. };
  220. Doing doing = DoingNone;
  221. cmsys::RegularExpression version("^[0-9.]+$");
  222. bool haveVersion = false;
  223. std::set<unsigned int> configArgs;
  224. std::set<unsigned int> moduleArgs;
  225. for (unsigned int i = 1; i < args.size(); ++i) {
  226. if (args[i] == "QUIET") {
  227. this->Quiet = true;
  228. doing = DoingNone;
  229. } else if (args[i] == "EXACT") {
  230. this->VersionExact = true;
  231. doing = DoingNone;
  232. } else if (args[i] == "MODULE") {
  233. moduleArgs.insert(i);
  234. doing = DoingNone;
  235. } else if (args[i] == "CONFIG") {
  236. configArgs.insert(i);
  237. doing = DoingNone;
  238. } else if (args[i] == "NO_MODULE") {
  239. configArgs.insert(i);
  240. doing = DoingNone;
  241. } else if (args[i] == "REQUIRED") {
  242. this->Required = true;
  243. doing = DoingComponents;
  244. } else if (args[i] == "COMPONENTS") {
  245. doing = DoingComponents;
  246. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  247. doing = DoingOptionalComponents;
  248. } else if (args[i] == "NAMES") {
  249. configArgs.insert(i);
  250. doing = DoingNames;
  251. } else if (args[i] == "PATHS") {
  252. configArgs.insert(i);
  253. doing = DoingPaths;
  254. } else if (args[i] == "HINTS") {
  255. configArgs.insert(i);
  256. doing = DoingHints;
  257. } else if (args[i] == "PATH_SUFFIXES") {
  258. configArgs.insert(i);
  259. doing = DoingPathSuffixes;
  260. } else if (args[i] == "CONFIGS") {
  261. configArgs.insert(i);
  262. doing = DoingConfigs;
  263. } else if (args[i] == "NO_POLICY_SCOPE") {
  264. this->PolicyScope = false;
  265. doing = DoingNone;
  266. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  267. this->NoUserRegistry = true;
  268. configArgs.insert(i);
  269. doing = DoingNone;
  270. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  271. this->NoSystemRegistry = true;
  272. configArgs.insert(i);
  273. doing = DoingNone;
  274. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  275. // Ignore legacy option.
  276. configArgs.insert(i);
  277. doing = DoingNone;
  278. } else if (this->CheckCommonArgument(args[i])) {
  279. configArgs.insert(i);
  280. doing = DoingNone;
  281. } else if ((doing == DoingComponents) ||
  282. (doing == DoingOptionalComponents)) {
  283. // Set a variable telling the find script whether this component
  284. // is required.
  285. const char* isRequired = "1";
  286. if (doing == DoingOptionalComponents) {
  287. isRequired = "0";
  288. optionalComponents.insert(args[i]);
  289. } else {
  290. requiredComponents.insert(args[i]);
  291. }
  292. std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
  293. this->AddFindDefinition(req_var, isRequired);
  294. // Append to the list of required components.
  295. components += components_sep;
  296. components += args[i];
  297. components_sep = ";";
  298. } else if (doing == DoingNames) {
  299. this->Names.push_back(args[i]);
  300. } else if (doing == DoingPaths) {
  301. this->UserGuessArgs.push_back(args[i]);
  302. } else if (doing == DoingHints) {
  303. this->UserHintsArgs.push_back(args[i]);
  304. } else if (doing == DoingPathSuffixes) {
  305. this->AddPathSuffix(args[i]);
  306. } else if (doing == DoingConfigs) {
  307. if (args[i].find_first_of(":/\\") != std::string::npos ||
  308. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  309. std::ostringstream e;
  310. e << "given CONFIGS option followed by invalid file name \"" << args[i]
  311. << "\". The names given must be file names without "
  312. << "a path and with a \".cmake\" extension.";
  313. this->SetError(e.str());
  314. return false;
  315. }
  316. this->Configs.push_back(args[i]);
  317. } else if (!haveVersion && version.find(args[i])) {
  318. haveVersion = true;
  319. this->Version = args[i];
  320. } else {
  321. std::ostringstream e;
  322. e << "called with invalid argument \"" << args[i] << "\"";
  323. this->SetError(e.str());
  324. return false;
  325. }
  326. }
  327. std::vector<std::string> doubledComponents;
  328. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  329. optionalComponents.begin(), optionalComponents.end(),
  330. std::back_inserter(doubledComponents));
  331. if (!doubledComponents.empty()) {
  332. std::ostringstream e;
  333. e << "called with components that are both required and optional:\n";
  334. e << cmWrap(" ", doubledComponents, "", "\n") << "\n";
  335. this->SetError(e.str());
  336. return false;
  337. }
  338. // Maybe choose one mode exclusively.
  339. this->UseFindModules = configArgs.empty();
  340. this->UseConfigFiles = moduleArgs.empty();
  341. if (!this->UseFindModules && !this->UseConfigFiles) {
  342. std::ostringstream e;
  343. e << "given options exclusive to Module mode:\n";
  344. for (unsigned int si : moduleArgs) {
  345. e << " " << args[si] << "\n";
  346. }
  347. e << "and options exclusive to Config mode:\n";
  348. for (unsigned int si : configArgs) {
  349. e << " " << args[si] << "\n";
  350. }
  351. e << "The options are incompatible.";
  352. this->SetError(e.str());
  353. return false;
  354. }
  355. // Ignore EXACT with no version.
  356. if (this->Version.empty() && this->VersionExact) {
  357. this->VersionExact = false;
  358. this->Makefile->IssueMessage(
  359. MessageType::AUTHOR_WARNING,
  360. "Ignoring EXACT since no version is requested.");
  361. }
  362. if (this->Version.empty() || components.empty()) {
  363. // Check whether we are recursing inside "Find<name>.cmake" within
  364. // another find_package(<name>) call.
  365. std::string mod = this->Name;
  366. mod += "_FIND_MODULE";
  367. if (this->Makefile->IsOn(mod)) {
  368. if (this->Version.empty()) {
  369. // Get version information from the outer call if necessary.
  370. // Requested version string.
  371. std::string ver = this->Name;
  372. ver += "_FIND_VERSION";
  373. this->Version = this->Makefile->GetSafeDefinition(ver);
  374. // Whether an exact version is required.
  375. std::string exact = this->Name;
  376. exact += "_FIND_VERSION_EXACT";
  377. this->VersionExact = this->Makefile->IsOn(exact);
  378. }
  379. if (components.empty()) {
  380. std::string components_var = this->Name + "_FIND_COMPONENTS";
  381. components = this->Makefile->GetSafeDefinition(components_var);
  382. }
  383. }
  384. }
  385. if (!this->Version.empty()) {
  386. // Try to parse the version number and store the results that were
  387. // successfully parsed.
  388. unsigned int parsed_major;
  389. unsigned int parsed_minor;
  390. unsigned int parsed_patch;
  391. unsigned int parsed_tweak;
  392. this->VersionCount =
  393. sscanf(this->Version.c_str(), "%u.%u.%u.%u", &parsed_major,
  394. &parsed_minor, &parsed_patch, &parsed_tweak);
  395. switch (this->VersionCount) {
  396. case 4:
  397. this->VersionTweak = parsed_tweak;
  398. CM_FALLTHROUGH;
  399. case 3:
  400. this->VersionPatch = parsed_patch;
  401. CM_FALLTHROUGH;
  402. case 2:
  403. this->VersionMinor = parsed_minor;
  404. CM_FALLTHROUGH;
  405. case 1:
  406. this->VersionMajor = parsed_major;
  407. CM_FALLTHROUGH;
  408. default:
  409. break;
  410. }
  411. }
  412. std::string disableFindPackageVar = "CMAKE_DISABLE_FIND_PACKAGE_";
  413. disableFindPackageVar += this->Name;
  414. if (this->Makefile->IsOn(disableFindPackageVar)) {
  415. if (this->Required) {
  416. std::ostringstream e;
  417. e << "for module " << this->Name << " called with REQUIRED, but "
  418. << disableFindPackageVar
  419. << " is enabled. A REQUIRED package cannot be disabled.";
  420. this->SetError(e.str());
  421. return false;
  422. }
  423. return true;
  424. }
  425. {
  426. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  427. this->Makefile->FindPackageRootPathStack.emplace_back();
  428. std::vector<std::string>& rootPaths =
  429. this->Makefile->FindPackageRootPathStack.back();
  430. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  431. // subject to CMP0074.
  432. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  433. case cmPolicies::WARN:
  434. this->Makefile->MaybeWarnCMP0074(this->Name);
  435. CM_FALLTHROUGH;
  436. case cmPolicies::OLD:
  437. // OLD behavior is to ignore the <pkg>_ROOT variables.
  438. break;
  439. case cmPolicies::REQUIRED_IF_USED:
  440. case cmPolicies::REQUIRED_ALWAYS:
  441. this->Makefile->IssueMessage(
  442. MessageType::FATAL_ERROR,
  443. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  444. break;
  445. case cmPolicies::NEW: {
  446. // NEW behavior is to honor the <pkg>_ROOT variables.
  447. std::string const rootVar = this->Name + "_ROOT";
  448. if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) {
  449. cmSystemTools::ExpandListArgument(pkgRoot, rootPaths, false);
  450. }
  451. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  452. } break;
  453. }
  454. }
  455. this->SetModuleVariables(components);
  456. // See if there is a Find<PackageName>.cmake module.
  457. bool loadedPackage = false;
  458. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  459. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  460. loadedPackage = true;
  461. } else {
  462. if (this->FindPackageUsingModuleMode()) {
  463. loadedPackage = true;
  464. } else {
  465. // The package was not loaded. Report errors.
  466. HandlePackageMode(HandlePackageModeType::Module);
  467. }
  468. }
  469. } else {
  470. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  471. loadedPackage = true;
  472. } else {
  473. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  474. // implicitly assumed)
  475. if (this->UseFindModules && this->UseConfigFiles &&
  476. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  477. std::ostringstream aw;
  478. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  479. aw << "find_package called without either MODULE or CONFIG option "
  480. "and "
  481. "no Find"
  482. << this->Name
  483. << ".cmake module is in CMAKE_MODULE_PATH. "
  484. "Add MODULE to exclusively request Module mode and fail if "
  485. "Find"
  486. << this->Name
  487. << ".cmake is missing. "
  488. "Add CONFIG to exclusively request Config mode and search for "
  489. "a "
  490. "package configuration file provided by "
  491. << this->Name << " (" << this->Name << "Config.cmake or "
  492. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  493. } else {
  494. aw << "find_package called without NO_MODULE option and no "
  495. "Find"
  496. << this->Name
  497. << ".cmake module is in CMAKE_MODULE_PATH. "
  498. "Add NO_MODULE to exclusively request Config mode and search "
  499. "for a "
  500. "package configuration file provided by "
  501. << this->Name << " (" << this->Name << "Config.cmake or "
  502. << cmSystemTools::LowerCase(this->Name)
  503. << "-config.cmake). "
  504. "Otherwise make Find"
  505. << this->Name
  506. << ".cmake available in "
  507. "CMAKE_MODULE_PATH.";
  508. }
  509. aw << "\n"
  510. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  511. "warning.)";
  512. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  513. }
  514. if (this->FindPackageUsingConfigMode()) {
  515. loadedPackage = true;
  516. }
  517. }
  518. }
  519. this->AppendSuccessInformation();
  520. return loadedPackage;
  521. }
  522. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  523. {
  524. bool foundModule = false;
  525. if (!this->FindModule(foundModule)) {
  526. return false;
  527. }
  528. return foundModule;
  529. }
  530. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  531. {
  532. this->Variable = this->Name;
  533. this->Variable += "_DIR";
  534. // Add the default name.
  535. if (this->Names.empty()) {
  536. this->Names.push_back(this->Name);
  537. }
  538. // Add the default configs.
  539. if (this->Configs.empty()) {
  540. for (std::string const& n : this->Names) {
  541. std::string config = n;
  542. config += "Config.cmake";
  543. this->Configs.push_back(config);
  544. config = cmSystemTools::LowerCase(n);
  545. config += "-config.cmake";
  546. this->Configs.push_back(std::move(config));
  547. }
  548. }
  549. // get igonored paths from vars and reroot them.
  550. std::vector<std::string> ignored;
  551. this->GetIgnoredPaths(ignored);
  552. this->RerootPaths(ignored);
  553. // Construct a set of ignored paths
  554. this->IgnoredPaths.clear();
  555. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  556. // Find and load the package.
  557. return this->HandlePackageMode(HandlePackageModeType::Config);
  558. }
  559. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  560. {
  561. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
  562. // Store the list of components.
  563. std::string components_var = this->Name + "_FIND_COMPONENTS";
  564. this->AddFindDefinition(components_var, components.c_str());
  565. if (this->Quiet) {
  566. // Tell the module that is about to be read that it should find
  567. // quietly.
  568. std::string quietly = this->Name;
  569. quietly += "_FIND_QUIETLY";
  570. this->AddFindDefinition(quietly, "1");
  571. }
  572. if (this->Required) {
  573. // Tell the module that is about to be read that it should report
  574. // a fatal error if the package is not found.
  575. std::string req = this->Name;
  576. req += "_FIND_REQUIRED";
  577. this->AddFindDefinition(req, "1");
  578. }
  579. if (!this->Version.empty()) {
  580. // Tell the module that is about to be read what version of the
  581. // package has been requested.
  582. std::string ver = this->Name;
  583. ver += "_FIND_VERSION";
  584. this->AddFindDefinition(ver, this->Version.c_str());
  585. char buf[64];
  586. sprintf(buf, "%u", this->VersionMajor);
  587. this->AddFindDefinition(ver + "_MAJOR", buf);
  588. sprintf(buf, "%u", this->VersionMinor);
  589. this->AddFindDefinition(ver + "_MINOR", buf);
  590. sprintf(buf, "%u", this->VersionPatch);
  591. this->AddFindDefinition(ver + "_PATCH", buf);
  592. sprintf(buf, "%u", this->VersionTweak);
  593. this->AddFindDefinition(ver + "_TWEAK", buf);
  594. sprintf(buf, "%u", this->VersionCount);
  595. this->AddFindDefinition(ver + "_COUNT", buf);
  596. // Tell the module whether an exact version has been requested.
  597. std::string exact = this->Name;
  598. exact += "_FIND_VERSION_EXACT";
  599. this->AddFindDefinition(exact, this->VersionExact ? "1" : "0");
  600. }
  601. }
  602. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  603. const char* val)
  604. {
  605. if (const char* old = this->Makefile->GetDefinition(var)) {
  606. this->OriginalDefs[var].exists = true;
  607. this->OriginalDefs[var].value = old;
  608. } else {
  609. this->OriginalDefs[var].exists = false;
  610. }
  611. this->Makefile->AddDefinition(var, val);
  612. }
  613. void cmFindPackageCommand::RestoreFindDefinitions()
  614. {
  615. for (auto const& i : this->OriginalDefs) {
  616. OriginalDef const& od = i.second;
  617. if (od.exists) {
  618. this->Makefile->AddDefinition(i.first, od.value.c_str());
  619. } else {
  620. this->Makefile->RemoveDefinition(i.first);
  621. }
  622. }
  623. }
  624. bool cmFindPackageCommand::FindModule(bool& found)
  625. {
  626. std::string module = "Find";
  627. module += this->Name;
  628. module += ".cmake";
  629. bool system = false;
  630. std::string mfile = this->Makefile->GetModulesFile(module, system);
  631. if (!mfile.empty()) {
  632. if (system) {
  633. auto it = this->DeprecatedFindModules.find(this->Name);
  634. if (it != this->DeprecatedFindModules.end()) {
  635. cmPolicies::PolicyStatus status =
  636. this->Makefile->GetPolicyStatus(it->second);
  637. switch (status) {
  638. case cmPolicies::WARN: {
  639. std::ostringstream e;
  640. e << cmPolicies::GetPolicyWarning(it->second) << "\n";
  641. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  642. CM_FALLTHROUGH;
  643. }
  644. case cmPolicies::OLD:
  645. break;
  646. case cmPolicies::REQUIRED_IF_USED:
  647. case cmPolicies::REQUIRED_ALWAYS:
  648. case cmPolicies::NEW:
  649. return true;
  650. }
  651. }
  652. }
  653. // Load the module we found, and set "<name>_FIND_MODULE" to true
  654. // while inside it.
  655. found = true;
  656. std::string var = this->Name;
  657. var += "_FIND_MODULE";
  658. this->Makefile->AddDefinition(var, "1");
  659. bool result = this->ReadListFile(mfile, DoPolicyScope);
  660. this->Makefile->RemoveDefinition(var);
  661. return result;
  662. }
  663. return true;
  664. }
  665. bool cmFindPackageCommand::HandlePackageMode(
  666. HandlePackageModeType handlePackageModeType)
  667. {
  668. this->ConsideredConfigs.clear();
  669. // Support old capitalization behavior.
  670. std::string upperDir = cmSystemTools::UpperCase(this->Name);
  671. std::string upperFound = cmSystemTools::UpperCase(this->Name);
  672. upperDir += "_DIR";
  673. upperFound += "_FOUND";
  674. // Try to find the config file.
  675. const char* def = this->Makefile->GetDefinition(this->Variable);
  676. // Try to load the config file if the directory is known
  677. bool fileFound = false;
  678. if (this->UseConfigFiles) {
  679. if (!cmSystemTools::IsOff(def)) {
  680. // Get the directory from the variable value.
  681. std::string dir = def;
  682. cmSystemTools::ConvertToUnixSlashes(dir);
  683. // Treat relative paths with respect to the current source dir.
  684. if (!cmSystemTools::FileIsFullPath(dir)) {
  685. dir = "/" + dir;
  686. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  687. }
  688. // The file location was cached. Look for the correct file.
  689. std::string file;
  690. if (this->FindConfigFile(dir, file)) {
  691. this->FileFound = file;
  692. fileFound = true;
  693. }
  694. def = this->Makefile->GetDefinition(this->Variable);
  695. }
  696. // Search for the config file if it is not already found.
  697. if (cmSystemTools::IsOff(def) || !fileFound) {
  698. fileFound = this->FindConfig();
  699. }
  700. // Sanity check.
  701. if (fileFound && this->FileFound.empty()) {
  702. this->Makefile->IssueMessage(
  703. MessageType::INTERNAL_ERROR,
  704. "fileFound is true but FileFound is empty!");
  705. fileFound = false;
  706. }
  707. }
  708. std::string foundVar = this->Name;
  709. foundVar += "_FOUND";
  710. std::string notFoundMessageVar = this->Name;
  711. notFoundMessageVar += "_NOT_FOUND_MESSAGE";
  712. std::string notFoundMessage;
  713. // If the directory for the config file was found, try to read the file.
  714. bool result = true;
  715. bool found = false;
  716. bool configFileSetFOUNDFalse = false;
  717. if (fileFound) {
  718. if (this->Makefile->IsDefinitionSet(foundVar) &&
  719. !this->Makefile->IsOn(foundVar)) {
  720. // by removing Foo_FOUND here if it is FALSE, we don't really change
  721. // the situation for the Config file which is about to be included,
  722. // but we make it possible to detect later on whether the Config file
  723. // has set Foo_FOUND to FALSE itself:
  724. this->Makefile->RemoveDefinition(foundVar);
  725. }
  726. this->Makefile->RemoveDefinition(notFoundMessageVar);
  727. // Set the version variables before loading the config file.
  728. // It may override them.
  729. this->StoreVersionFound();
  730. // Parse the configuration file.
  731. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  732. // The package has been found.
  733. found = true;
  734. // Check whether the Config file has set Foo_FOUND to FALSE:
  735. if (this->Makefile->IsDefinitionSet(foundVar) &&
  736. !this->Makefile->IsOn(foundVar)) {
  737. // we get here if the Config file has set Foo_FOUND actively to FALSE
  738. found = false;
  739. configFileSetFOUNDFalse = true;
  740. notFoundMessage =
  741. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  742. }
  743. } else {
  744. // The configuration file is invalid.
  745. result = false;
  746. }
  747. }
  748. if (this->UseFindModules && !found &&
  749. handlePackageModeType == HandlePackageModeType::Config &&
  750. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  751. // Config mode failed. Allow Module case.
  752. result = false;
  753. }
  754. // package not found
  755. if (result && !found) {
  756. // warn if package required or neither quiet nor in config mode
  757. if (this->Required ||
  758. !(this->Quiet ||
  759. (this->UseConfigFiles && !this->UseFindModules &&
  760. this->ConsideredConfigs.empty()))) {
  761. // The variable is not set.
  762. std::ostringstream e;
  763. std::ostringstream aw;
  764. if (configFileSetFOUNDFalse) {
  765. /* clang-format off */
  766. e << "Found package configuration file:\n"
  767. " " << this->FileFound << "\n"
  768. "but it set " << foundVar << " to FALSE so package \"" <<
  769. this->Name << "\" is considered to be NOT FOUND.";
  770. /* clang-format on */
  771. if (!notFoundMessage.empty()) {
  772. e << " Reason given by package: \n" << notFoundMessage << "\n";
  773. }
  774. }
  775. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  776. // have been found, but they didn't have appropriate versions.
  777. else if (!this->ConsideredConfigs.empty()) {
  778. std::vector<ConfigFileInfo>::const_iterator duplicate_end =
  779. cmRemoveDuplicates(this->ConsideredConfigs);
  780. e << "Could not find a configuration file for package \"" << this->Name
  781. << "\" that "
  782. << (this->VersionExact ? "exactly matches" : "is compatible with")
  783. << " requested version \"" << this->Version << "\".\n"
  784. << "The following configuration files were considered but not "
  785. "accepted:\n";
  786. for (ConfigFileInfo const& info :
  787. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  788. e << " " << info.filename << ", version: " << info.version << "\n";
  789. }
  790. } else {
  791. std::string requestedVersionString;
  792. if (!this->Version.empty()) {
  793. requestedVersionString = " (requested version ";
  794. requestedVersionString += this->Version;
  795. requestedVersionString += ")";
  796. }
  797. if (this->UseConfigFiles) {
  798. if (this->UseFindModules) {
  799. e << "By not providing \"Find" << this->Name
  800. << ".cmake\" in "
  801. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  802. "package configuration file provided by \""
  803. << this->Name
  804. << "\", "
  805. "but CMake did not find one.\n";
  806. }
  807. if (this->Configs.size() == 1) {
  808. e << "Could not find a package configuration file named \""
  809. << this->Configs[0] << "\" provided by package \"" << this->Name
  810. << "\"" << requestedVersionString << ".\n";
  811. } else {
  812. e << "Could not find a package configuration file provided by \""
  813. << this->Name << "\"" << requestedVersionString
  814. << " with any of the following names:\n"
  815. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  816. }
  817. e << "Add the installation prefix of \"" << this->Name
  818. << "\" to "
  819. "CMAKE_PREFIX_PATH or set \""
  820. << this->Variable
  821. << "\" to a "
  822. "directory containing one of the above files. "
  823. "If \""
  824. << this->Name
  825. << "\" provides a separate development "
  826. "package or SDK, be sure it has been installed.";
  827. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  828. {
  829. e << "No \"Find" << this->Name << ".cmake\" found in "
  830. << "CMAKE_MODULE_PATH.";
  831. aw
  832. << "Find" << this->Name
  833. << ".cmake must either be part of this "
  834. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  835. "it points to the correct location inside its source tree.\n"
  836. "Or it must be installed by a package which has already been "
  837. "found via find_package(). In this case make sure that "
  838. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  839. "contain the location where that package has installed "
  840. "Find"
  841. << this->Name
  842. << ".cmake. This must be a location "
  843. "provided by that package. This error in general means that "
  844. "the buildsystem of this project is relying on a Find-module "
  845. "without ensuring that it is actually available.\n";
  846. }
  847. }
  848. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  849. : MessageType::WARNING,
  850. e.str());
  851. if (this->Required) {
  852. cmSystemTools::SetFatalErrorOccured();
  853. }
  854. if (!aw.str().empty()) {
  855. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  856. }
  857. }
  858. // output result if in config mode but not in quiet mode
  859. else if (!this->Quiet) {
  860. std::ostringstream aw;
  861. aw << "Could NOT find " << this->Name << " (missing: " << this->Name
  862. << "_DIR)";
  863. this->Makefile->DisplayStatus(aw.str(), -1);
  864. }
  865. }
  866. // Set a variable marking whether the package was found.
  867. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  868. // Set a variable naming the configuration file that was found.
  869. std::string fileVar = this->Name;
  870. fileVar += "_CONFIG";
  871. if (found) {
  872. this->Makefile->AddDefinition(fileVar, this->FileFound.c_str());
  873. } else {
  874. this->Makefile->RemoveDefinition(fileVar);
  875. }
  876. std::string consideredConfigsVar = this->Name;
  877. consideredConfigsVar += "_CONSIDERED_CONFIGS";
  878. std::string consideredVersionsVar = this->Name;
  879. consideredVersionsVar += "_CONSIDERED_VERSIONS";
  880. std::string consideredConfigFiles;
  881. std::string consideredVersions;
  882. const char* sep = "";
  883. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  884. consideredConfigFiles += sep;
  885. consideredVersions += sep;
  886. consideredConfigFiles += i.filename;
  887. consideredVersions += i.version;
  888. sep = ";";
  889. }
  890. this->Makefile->AddDefinition(consideredConfigsVar,
  891. consideredConfigFiles.c_str());
  892. this->Makefile->AddDefinition(consideredVersionsVar,
  893. consideredVersions.c_str());
  894. return result;
  895. }
  896. bool cmFindPackageCommand::FindConfig()
  897. {
  898. // Compute the set of search prefixes.
  899. this->ComputePrefixes();
  900. // Look for the project's configuration file.
  901. bool found = false;
  902. // Search for frameworks.
  903. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  904. found = this->FindFrameworkConfig();
  905. }
  906. // Search for apps.
  907. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  908. found = this->FindAppBundleConfig();
  909. }
  910. // Search prefixes.
  911. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  912. found = this->FindPrefixedConfig();
  913. }
  914. // Search for frameworks.
  915. if (!found && this->SearchFrameworkLast) {
  916. found = this->FindFrameworkConfig();
  917. }
  918. // Search for apps.
  919. if (!found && this->SearchAppBundleLast) {
  920. found = this->FindAppBundleConfig();
  921. }
  922. // Store the entry in the cache so it can be set by the user.
  923. std::string init;
  924. if (found) {
  925. init = cmSystemTools::GetFilenamePath(this->FileFound);
  926. } else {
  927. init = this->Variable + "-NOTFOUND";
  928. }
  929. std::string help =
  930. "The directory containing a CMake configuration file for ";
  931. help += this->Name;
  932. help += ".";
  933. // We force the value since we do not get here if it was already set.
  934. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
  935. help.c_str(), cmStateEnums::PATH, true);
  936. return found;
  937. }
  938. bool cmFindPackageCommand::FindPrefixedConfig()
  939. {
  940. std::vector<std::string> const& prefixes = this->SearchPaths;
  941. for (std::string const& p : prefixes) {
  942. if (this->SearchPrefix(p)) {
  943. return true;
  944. }
  945. }
  946. return false;
  947. }
  948. bool cmFindPackageCommand::FindFrameworkConfig()
  949. {
  950. std::vector<std::string> const& prefixes = this->SearchPaths;
  951. for (std::string const& p : prefixes) {
  952. if (this->SearchFrameworkPrefix(p)) {
  953. return true;
  954. }
  955. }
  956. return false;
  957. }
  958. bool cmFindPackageCommand::FindAppBundleConfig()
  959. {
  960. std::vector<std::string> const& prefixes = this->SearchPaths;
  961. for (std::string const& p : prefixes) {
  962. if (this->SearchAppBundlePrefix(p)) {
  963. return true;
  964. }
  965. }
  966. return false;
  967. }
  968. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  969. PolicyScopeRule psr)
  970. {
  971. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  972. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  973. return true;
  974. }
  975. std::string e = "Error reading CMake code from \"";
  976. e += f;
  977. e += "\".";
  978. this->SetError(e);
  979. return false;
  980. }
  981. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  982. {
  983. std::vector<std::string> foundContents;
  984. const char* foundProp =
  985. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  986. if (foundProp && *foundProp) {
  987. std::string tmp = foundProp;
  988. cmSystemTools::ExpandListArgument(tmp, foundContents, false);
  989. std::vector<std::string>::iterator nameIt =
  990. std::find(foundContents.begin(), foundContents.end(), this->Name);
  991. if (nameIt != foundContents.end()) {
  992. foundContents.erase(nameIt);
  993. }
  994. }
  995. std::vector<std::string> notFoundContents;
  996. const char* notFoundProp =
  997. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  998. if (notFoundProp && *notFoundProp) {
  999. std::string tmp = notFoundProp;
  1000. cmSystemTools::ExpandListArgument(tmp, notFoundContents, false);
  1001. std::vector<std::string>::iterator nameIt =
  1002. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  1003. if (nameIt != notFoundContents.end()) {
  1004. notFoundContents.erase(nameIt);
  1005. }
  1006. }
  1007. if (found) {
  1008. foundContents.push_back(this->Name);
  1009. } else {
  1010. notFoundContents.push_back(this->Name);
  1011. }
  1012. std::string tmp = cmJoin(foundContents, ";");
  1013. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  1014. tmp = cmJoin(notFoundContents, ";");
  1015. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1016. tmp.c_str());
  1017. }
  1018. void cmFindPackageCommand::AppendSuccessInformation()
  1019. {
  1020. {
  1021. std::string transitivePropName = "_CMAKE_";
  1022. transitivePropName += this->Name + "_TRANSITIVE_DEPENDENCY";
  1023. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1024. }
  1025. std::string found = this->Name;
  1026. found += "_FOUND";
  1027. std::string upperFound = cmSystemTools::UpperCase(found);
  1028. const char* upperResult = this->Makefile->GetDefinition(upperFound);
  1029. const char* result = this->Makefile->GetDefinition(found);
  1030. bool packageFound =
  1031. ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult)));
  1032. this->AppendToFoundProperty(packageFound);
  1033. // Record whether the find was quiet or not, so this can be used
  1034. // e.g. in FeatureSummary.cmake
  1035. std::string quietInfoPropName = "_CMAKE_";
  1036. quietInfoPropName += this->Name;
  1037. quietInfoPropName += "_QUIET";
  1038. this->Makefile->GetState()->SetGlobalProperty(
  1039. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1040. // set a global property to record the required version of this package
  1041. std::string versionInfoPropName = "_CMAKE_";
  1042. versionInfoPropName += this->Name;
  1043. versionInfoPropName += "_REQUIRED_VERSION";
  1044. std::string versionInfo;
  1045. if (!this->Version.empty()) {
  1046. versionInfo = this->VersionExact ? "==" : ">=";
  1047. versionInfo += " ";
  1048. versionInfo += this->Version;
  1049. }
  1050. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1051. versionInfo.c_str());
  1052. if (this->Required) {
  1053. std::string requiredInfoPropName = "_CMAKE_";
  1054. requiredInfoPropName += this->Name;
  1055. requiredInfoPropName += "_TYPE";
  1056. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1057. "REQUIRED");
  1058. }
  1059. // Restore original state of "_FIND_" variables we set.
  1060. this->RestoreFindDefinitions();
  1061. // Pop the package stack
  1062. this->Makefile->FindPackageRootPathStack.pop_back();
  1063. }
  1064. void cmFindPackageCommand::ComputePrefixes()
  1065. {
  1066. if (!this->NoDefaultPath) {
  1067. if (!this->NoPackageRootPath) {
  1068. this->FillPrefixesPackageRoot();
  1069. }
  1070. if (!this->NoCMakePath) {
  1071. this->FillPrefixesCMakeVariable();
  1072. }
  1073. if (!this->NoCMakeEnvironmentPath) {
  1074. this->FillPrefixesCMakeEnvironment();
  1075. }
  1076. }
  1077. this->FillPrefixesUserHints();
  1078. if (!this->NoDefaultPath) {
  1079. if (!this->NoSystemEnvironmentPath) {
  1080. this->FillPrefixesSystemEnvironment();
  1081. }
  1082. if (!this->NoUserRegistry) {
  1083. this->FillPrefixesUserRegistry();
  1084. }
  1085. if (!this->NoCMakeSystemPath) {
  1086. this->FillPrefixesCMakeSystemVariable();
  1087. }
  1088. if (!this->NoSystemRegistry) {
  1089. this->FillPrefixesSystemRegistry();
  1090. }
  1091. }
  1092. this->FillPrefixesUserGuess();
  1093. this->ComputeFinalPaths();
  1094. }
  1095. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1096. {
  1097. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1098. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1099. for (std::deque<std::vector<std::string>>::const_reverse_iterator pkgPaths =
  1100. this->Makefile->FindPackageRootPathStack.rbegin();
  1101. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1102. ++pkgPaths) {
  1103. for (std::string const& path : *pkgPaths) {
  1104. paths.AddPath(path);
  1105. }
  1106. }
  1107. }
  1108. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1109. {
  1110. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1111. // Check the environment variable with the same name as the cache
  1112. // entry.
  1113. paths.AddEnvPath(this->Variable);
  1114. // And now the general CMake environment variables
  1115. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1116. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1117. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1118. }
  1119. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1120. {
  1121. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1122. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1123. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1124. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1125. }
  1126. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1127. {
  1128. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1129. // Use the system search path to generate prefixes.
  1130. // Relative paths are interpreted with respect to the current
  1131. // working directory.
  1132. std::vector<std::string> tmp;
  1133. cmSystemTools::GetPath(tmp);
  1134. for (std::string const& i : tmp) {
  1135. // If the path is a PREFIX/bin case then add its parent instead.
  1136. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1137. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1138. } else {
  1139. paths.AddPath(i);
  1140. }
  1141. }
  1142. }
  1143. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1144. {
  1145. #if defined(_WIN32) && !defined(__CYGWIN__)
  1146. this->LoadPackageRegistryWinUser();
  1147. #elif defined(__HAIKU__)
  1148. char dir[B_PATH_NAME_LENGTH];
  1149. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1150. B_OK) {
  1151. std::string fname = dir;
  1152. fname += "/cmake/packages/";
  1153. fname += Name;
  1154. this->LoadPackageRegistryDir(fname,
  1155. this->LabeledPaths[PathLabel::UserRegistry]);
  1156. }
  1157. #else
  1158. std::string dir;
  1159. if (cmSystemTools::GetEnv("HOME", dir)) {
  1160. dir += "/.cmake/packages/";
  1161. dir += this->Name;
  1162. this->LoadPackageRegistryDir(dir,
  1163. this->LabeledPaths[PathLabel::UserRegistry]);
  1164. }
  1165. #endif
  1166. }
  1167. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1168. {
  1169. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1170. return;
  1171. }
  1172. #if defined(_WIN32) && !defined(__CYGWIN__)
  1173. this->LoadPackageRegistryWinSystem();
  1174. #endif
  1175. }
  1176. #if defined(_WIN32) && !defined(__CYGWIN__)
  1177. # include <windows.h>
  1178. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1179. # if !defined(KEY_WOW64_32KEY)
  1180. # define KEY_WOW64_32KEY 0x0200
  1181. # endif
  1182. # if !defined(KEY_WOW64_64KEY)
  1183. # define KEY_WOW64_64KEY 0x0100
  1184. # endif
  1185. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1186. {
  1187. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1188. this->LoadPackageRegistryWin(true, 0,
  1189. this->LabeledPaths[PathLabel::UserRegistry]);
  1190. }
  1191. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1192. {
  1193. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1194. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1195. // Prefer the target platform view first.
  1196. if (this->Makefile->PlatformIs64Bit()) {
  1197. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1198. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1199. } else {
  1200. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1201. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1202. }
  1203. }
  1204. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1205. cmSearchPath& outPaths)
  1206. {
  1207. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1208. key += cmsys::Encoding::ToWide(this->Name);
  1209. std::set<std::wstring> bad;
  1210. HKEY hKey;
  1211. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1212. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1213. DWORD valueType = REG_NONE;
  1214. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1215. std::vector<wchar_t> data(512);
  1216. bool done = false;
  1217. DWORD index = 0;
  1218. while (!done) {
  1219. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1220. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1221. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1222. (BYTE*)&data[0], &dataSize)) {
  1223. case ERROR_SUCCESS:
  1224. ++index;
  1225. if (valueType == REG_SZ) {
  1226. data[dataSize] = 0;
  1227. if (!this->CheckPackageRegistryEntry(
  1228. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1229. // The entry is invalid.
  1230. bad.insert(name);
  1231. }
  1232. }
  1233. break;
  1234. case ERROR_MORE_DATA:
  1235. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1236. break;
  1237. case ERROR_NO_MORE_ITEMS:
  1238. default:
  1239. done = true;
  1240. break;
  1241. }
  1242. }
  1243. RegCloseKey(hKey);
  1244. }
  1245. // Remove bad values if possible.
  1246. if (user && !bad.empty() &&
  1247. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1248. &hKey) == ERROR_SUCCESS) {
  1249. for (std::wstring const& v : bad) {
  1250. RegDeleteValueW(hKey, v.c_str());
  1251. }
  1252. RegCloseKey(hKey);
  1253. }
  1254. }
  1255. #else
  1256. class cmFindPackageCommandHoldFile
  1257. {
  1258. const char* File;
  1259. public:
  1260. cmFindPackageCommandHoldFile(const char* f)
  1261. : File(f)
  1262. {
  1263. }
  1264. ~cmFindPackageCommandHoldFile()
  1265. {
  1266. if (this->File) {
  1267. cmSystemTools::RemoveFile(this->File);
  1268. }
  1269. }
  1270. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  1271. cmFindPackageCommandHoldFile& operator=(
  1272. const cmFindPackageCommandHoldFile&) = delete;
  1273. void Release() { this->File = nullptr; }
  1274. };
  1275. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1276. cmSearchPath& outPaths)
  1277. {
  1278. cmsys::Directory files;
  1279. if (!files.Load(dir)) {
  1280. return;
  1281. }
  1282. std::string fname;
  1283. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1284. fname = dir;
  1285. fname += "/";
  1286. fname += files.GetFile(i);
  1287. if (!cmSystemTools::FileIsDirectory(fname)) {
  1288. // Hold this file hostage until it behaves.
  1289. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1290. // Load the file.
  1291. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1292. std::string fentry;
  1293. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1294. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1295. // The file references an existing package, so release it.
  1296. holdFile.Release();
  1297. }
  1298. }
  1299. }
  1300. // TODO: Wipe out the directory if it is empty.
  1301. }
  1302. #endif
  1303. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1304. cmSearchPath& outPaths)
  1305. {
  1306. // Parse the content of one package registry entry.
  1307. if (cmSystemTools::FileIsFullPath(fname)) {
  1308. // The first line in the stream is the full path to a file or
  1309. // directory containing the package.
  1310. if (cmSystemTools::FileExists(fname)) {
  1311. // The path exists. Look for the package here.
  1312. if (!cmSystemTools::FileIsDirectory(fname)) {
  1313. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1314. } else {
  1315. outPaths.AddPath(fname);
  1316. }
  1317. return true;
  1318. }
  1319. // The path does not exist. Assume the stream content is
  1320. // associated with an old package that no longer exists, and
  1321. // delete it to keep the package registry clean.
  1322. return false;
  1323. }
  1324. // The first line in the stream is not the full path to a file or
  1325. // directory. Assume the stream content was created by a future
  1326. // version of CMake that uses a different format, and leave it.
  1327. return true;
  1328. }
  1329. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1330. {
  1331. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1332. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1333. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1334. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1335. }
  1336. void cmFindPackageCommand::FillPrefixesUserGuess()
  1337. {
  1338. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1339. for (std::string const& p : this->UserGuessArgs) {
  1340. paths.AddUserPath(p);
  1341. }
  1342. }
  1343. void cmFindPackageCommand::FillPrefixesUserHints()
  1344. {
  1345. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1346. for (std::string const& p : this->UserHintsArgs) {
  1347. paths.AddUserPath(p);
  1348. }
  1349. }
  1350. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1351. {
  1352. assert(!dir.empty() && dir.back() == '/');
  1353. // Check each path suffix on this directory.
  1354. for (std::string const& s : this->SearchPathSuffixes) {
  1355. std::string d = dir;
  1356. if (!s.empty()) {
  1357. d += s;
  1358. d += "/";
  1359. }
  1360. if (this->CheckDirectory(d)) {
  1361. return true;
  1362. }
  1363. }
  1364. return false;
  1365. }
  1366. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1367. {
  1368. assert(!dir.empty() && dir.back() == '/');
  1369. // Look for the file in this directory.
  1370. std::string d = dir.substr(0, dir.size() - 1);
  1371. if (this->FindConfigFile(d, this->FileFound)) {
  1372. // Remove duplicate slashes.
  1373. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1374. return true;
  1375. }
  1376. return false;
  1377. }
  1378. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1379. std::string& file)
  1380. {
  1381. if (this->IgnoredPaths.count(dir)) {
  1382. return false;
  1383. }
  1384. for (std::string const& c : this->Configs) {
  1385. file = dir;
  1386. file += "/";
  1387. file += c;
  1388. if (this->DebugMode) {
  1389. fprintf(stderr, "Checking file [%s]\n", file.c_str());
  1390. }
  1391. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1392. // Allow resolving symlinks when the config file is found through a link
  1393. if (this->UseRealPath) {
  1394. file = cmSystemTools::GetRealPath(file);
  1395. }
  1396. return true;
  1397. }
  1398. }
  1399. return false;
  1400. }
  1401. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1402. {
  1403. bool result = false; // by default, assume the version is not ok.
  1404. bool haveResult = false;
  1405. std::string version = "unknown";
  1406. // Get the filename without the .cmake extension.
  1407. std::string::size_type pos = config_file.rfind('.');
  1408. std::string version_file_base = config_file.substr(0, pos);
  1409. // Look for foo-config-version.cmake
  1410. std::string version_file = version_file_base;
  1411. version_file += "-version.cmake";
  1412. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1413. result = this->CheckVersionFile(version_file, version);
  1414. haveResult = true;
  1415. }
  1416. // Look for fooConfigVersion.cmake
  1417. version_file = version_file_base;
  1418. version_file += "Version.cmake";
  1419. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1420. result = this->CheckVersionFile(version_file, version);
  1421. haveResult = true;
  1422. }
  1423. // If no version was requested a versionless package is acceptable.
  1424. if (!haveResult && this->Version.empty()) {
  1425. result = true;
  1426. }
  1427. ConfigFileInfo configFileInfo;
  1428. configFileInfo.filename = config_file;
  1429. configFileInfo.version = version;
  1430. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1431. return result;
  1432. }
  1433. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1434. std::string& result_version)
  1435. {
  1436. // The version file will be loaded in an isolated scope.
  1437. cmMakefile::ScopePushPop varScope(this->Makefile);
  1438. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1439. static_cast<void>(varScope);
  1440. static_cast<void>(polScope);
  1441. // Clear the output variables.
  1442. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1443. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1444. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1445. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1446. // Set the input variables.
  1447. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
  1448. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION", this->Version.c_str());
  1449. char buf[64];
  1450. sprintf(buf, "%u", this->VersionMajor);
  1451. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
  1452. sprintf(buf, "%u", this->VersionMinor);
  1453. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
  1454. sprintf(buf, "%u", this->VersionPatch);
  1455. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
  1456. sprintf(buf, "%u", this->VersionTweak);
  1457. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
  1458. sprintf(buf, "%u", this->VersionCount);
  1459. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
  1460. // Load the version check file. Pass NoPolicyScope because we do
  1461. // our own policy push/pop independent of CMP0011.
  1462. bool suitable = false;
  1463. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1464. // Check the output variables.
  1465. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1466. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1467. if (!okay && !this->VersionExact) {
  1468. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1469. }
  1470. // The package is suitable if the version is okay and not
  1471. // explicitly unsuitable.
  1472. suitable = !unsuitable && (okay || this->Version.empty());
  1473. if (suitable) {
  1474. // Get the version found.
  1475. this->VersionFound =
  1476. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1477. // Try to parse the version number and store the results that were
  1478. // successfully parsed.
  1479. unsigned int parsed_major;
  1480. unsigned int parsed_minor;
  1481. unsigned int parsed_patch;
  1482. unsigned int parsed_tweak;
  1483. this->VersionFoundCount =
  1484. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1485. &parsed_minor, &parsed_patch, &parsed_tweak);
  1486. switch (this->VersionFoundCount) {
  1487. case 4:
  1488. this->VersionFoundTweak = parsed_tweak;
  1489. CM_FALLTHROUGH;
  1490. case 3:
  1491. this->VersionFoundPatch = parsed_patch;
  1492. CM_FALLTHROUGH;
  1493. case 2:
  1494. this->VersionFoundMinor = parsed_minor;
  1495. CM_FALLTHROUGH;
  1496. case 1:
  1497. this->VersionFoundMajor = parsed_major;
  1498. CM_FALLTHROUGH;
  1499. default:
  1500. break;
  1501. }
  1502. }
  1503. }
  1504. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1505. if (result_version.empty()) {
  1506. result_version = "unknown";
  1507. }
  1508. // Succeed if the version is suitable.
  1509. return suitable;
  1510. }
  1511. void cmFindPackageCommand::StoreVersionFound()
  1512. {
  1513. // Store the whole version string.
  1514. std::string ver = this->Name;
  1515. ver += "_VERSION";
  1516. if (this->VersionFound.empty()) {
  1517. this->Makefile->RemoveDefinition(ver);
  1518. } else {
  1519. this->Makefile->AddDefinition(ver, this->VersionFound.c_str());
  1520. }
  1521. // Store the version components.
  1522. char buf[64];
  1523. sprintf(buf, "%u", this->VersionFoundMajor);
  1524. this->Makefile->AddDefinition(ver + "_MAJOR", buf);
  1525. sprintf(buf, "%u", this->VersionFoundMinor);
  1526. this->Makefile->AddDefinition(ver + "_MINOR", buf);
  1527. sprintf(buf, "%u", this->VersionFoundPatch);
  1528. this->Makefile->AddDefinition(ver + "_PATCH", buf);
  1529. sprintf(buf, "%u", this->VersionFoundTweak);
  1530. this->Makefile->AddDefinition(ver + "_TWEAK", buf);
  1531. sprintf(buf, "%u", this->VersionFoundCount);
  1532. this->Makefile->AddDefinition(ver + "_COUNT", buf);
  1533. }
  1534. class cmFileListGeneratorBase
  1535. {
  1536. public:
  1537. virtual ~cmFileListGeneratorBase() = default;
  1538. protected:
  1539. bool Consider(std::string const& fullPath, cmFileList& listing);
  1540. private:
  1541. bool Search(cmFileList&);
  1542. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1543. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1544. friend class cmFileList;
  1545. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1546. std::unique_ptr<cmFileListGeneratorBase> Next;
  1547. };
  1548. class cmFileList
  1549. {
  1550. public:
  1551. virtual ~cmFileList() = default;
  1552. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1553. {
  1554. if (this->Last) {
  1555. this->Last = this->Last->SetNext(rhs);
  1556. } else {
  1557. this->First = rhs.Clone();
  1558. this->Last = this->First.get();
  1559. }
  1560. return *this;
  1561. }
  1562. bool Search()
  1563. {
  1564. if (this->First) {
  1565. return this->First->Search(*this);
  1566. }
  1567. return false;
  1568. }
  1569. private:
  1570. virtual bool Visit(std::string const& fullPath) = 0;
  1571. friend class cmFileListGeneratorBase;
  1572. std::unique_ptr<cmFileListGeneratorBase> First;
  1573. cmFileListGeneratorBase* Last = nullptr;
  1574. };
  1575. class cmFindPackageFileList : public cmFileList
  1576. {
  1577. public:
  1578. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1579. : FPC(fpc)
  1580. , UseSuffixes(use_suffixes)
  1581. {
  1582. }
  1583. private:
  1584. bool Visit(std::string const& fullPath) override
  1585. {
  1586. if (this->UseSuffixes) {
  1587. return this->FPC->SearchDirectory(fullPath);
  1588. }
  1589. return this->FPC->CheckDirectory(fullPath);
  1590. }
  1591. cmFindPackageCommand* FPC;
  1592. bool UseSuffixes;
  1593. };
  1594. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1595. {
  1596. return this->Search("", listing);
  1597. }
  1598. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1599. cmFileListGeneratorBase const& next)
  1600. {
  1601. this->Next = next.Clone();
  1602. return this->Next.get();
  1603. }
  1604. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1605. cmFileList& listing)
  1606. {
  1607. if (this->Next) {
  1608. return this->Next->Search(fullPath + "/", listing);
  1609. }
  1610. return listing.Visit(fullPath + "/");
  1611. }
  1612. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1613. {
  1614. public:
  1615. cmFileListGeneratorFixed(std::string str)
  1616. : String(std::move(str))
  1617. {
  1618. }
  1619. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1620. : String(r.String)
  1621. {
  1622. }
  1623. private:
  1624. std::string String;
  1625. bool Search(std::string const& parent, cmFileList& lister) override
  1626. {
  1627. std::string fullPath = parent + this->String;
  1628. return this->Consider(fullPath, lister);
  1629. }
  1630. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1631. {
  1632. std::unique_ptr<cmFileListGeneratorBase> g(
  1633. new cmFileListGeneratorFixed(*this));
  1634. return g;
  1635. }
  1636. };
  1637. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1638. {
  1639. public:
  1640. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1641. : Vector(v)
  1642. {
  1643. }
  1644. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1645. : Vector(r.Vector)
  1646. {
  1647. }
  1648. private:
  1649. std::vector<std::string> const& Vector;
  1650. bool Search(std::string const& parent, cmFileList& lister) override
  1651. {
  1652. for (std::string const& i : this->Vector) {
  1653. if (this->Consider(parent + i, lister)) {
  1654. return true;
  1655. }
  1656. }
  1657. return false;
  1658. }
  1659. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1660. {
  1661. std::unique_ptr<cmFileListGeneratorBase> g(
  1662. new cmFileListGeneratorEnumerate(*this));
  1663. return g;
  1664. }
  1665. };
  1666. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1667. {
  1668. public:
  1669. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1670. cmFindPackageCommand::SortOrderType so,
  1671. cmFindPackageCommand::SortDirectionType sd)
  1672. : Names(names)
  1673. {
  1674. this->SetSort(so, sd);
  1675. }
  1676. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1677. : Names(r.Names)
  1678. {
  1679. this->SetSort(r.SortOrder, r.SortDirection);
  1680. }
  1681. void SetSort(cmFindPackageCommand::SortOrderType o,
  1682. cmFindPackageCommand::SortDirectionType d)
  1683. {
  1684. SortOrder = o;
  1685. SortDirection = d;
  1686. }
  1687. protected:
  1688. // sort parameters
  1689. cmFindPackageCommand::SortOrderType SortOrder;
  1690. cmFindPackageCommand::SortDirectionType SortDirection;
  1691. private:
  1692. std::vector<std::string> const& Names;
  1693. bool Search(std::string const& parent, cmFileList& lister) override
  1694. {
  1695. // Construct a list of matches.
  1696. std::vector<std::string> matches;
  1697. cmsys::Directory d;
  1698. d.Load(parent);
  1699. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1700. const char* fname = d.GetFile(i);
  1701. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1702. continue;
  1703. }
  1704. for (std::string const& n : this->Names) {
  1705. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1706. matches.emplace_back(fname);
  1707. }
  1708. }
  1709. }
  1710. // before testing the matches check if there is a specific sorting order to
  1711. // perform
  1712. if (this->SortOrder != cmFindPackageCommand::None) {
  1713. cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
  1714. SortDirection);
  1715. }
  1716. for (std::string const& i : matches) {
  1717. if (this->Consider(parent + i, lister)) {
  1718. return true;
  1719. }
  1720. }
  1721. return false;
  1722. }
  1723. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1724. {
  1725. std::unique_ptr<cmFileListGeneratorBase> g(
  1726. new cmFileListGeneratorProject(*this));
  1727. return g;
  1728. }
  1729. };
  1730. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1731. {
  1732. public:
  1733. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1734. const char* ext)
  1735. : Names(names)
  1736. , Extension(ext)
  1737. {
  1738. }
  1739. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1740. : Names(r.Names)
  1741. , Extension(r.Extension)
  1742. {
  1743. }
  1744. private:
  1745. std::vector<std::string> const& Names;
  1746. std::string Extension;
  1747. bool Search(std::string const& parent, cmFileList& lister) override
  1748. {
  1749. // Construct a list of matches.
  1750. std::vector<std::string> matches;
  1751. cmsys::Directory d;
  1752. d.Load(parent);
  1753. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1754. const char* fname = d.GetFile(i);
  1755. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1756. continue;
  1757. }
  1758. for (std::string name : this->Names) {
  1759. name += this->Extension;
  1760. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1761. matches.emplace_back(fname);
  1762. }
  1763. }
  1764. }
  1765. for (std::string const& i : matches) {
  1766. if (this->Consider(parent + i, lister)) {
  1767. return true;
  1768. }
  1769. }
  1770. return false;
  1771. }
  1772. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1773. {
  1774. std::unique_ptr<cmFileListGeneratorBase> g(
  1775. new cmFileListGeneratorMacProject(*this));
  1776. return g;
  1777. }
  1778. };
  1779. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1780. {
  1781. public:
  1782. cmFileListGeneratorCaseInsensitive(std::string str)
  1783. : String(std::move(str))
  1784. {
  1785. }
  1786. cmFileListGeneratorCaseInsensitive(
  1787. cmFileListGeneratorCaseInsensitive const& r)
  1788. : String(r.String)
  1789. {
  1790. }
  1791. private:
  1792. std::string String;
  1793. bool Search(std::string const& parent, cmFileList& lister) override
  1794. {
  1795. // Look for matching files.
  1796. std::vector<std::string> matches;
  1797. cmsys::Directory d;
  1798. d.Load(parent);
  1799. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1800. const char* fname = d.GetFile(i);
  1801. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1802. continue;
  1803. }
  1804. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1805. if (this->Consider(parent + fname, lister)) {
  1806. return true;
  1807. }
  1808. }
  1809. }
  1810. return false;
  1811. }
  1812. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1813. {
  1814. std::unique_ptr<cmFileListGeneratorBase> g(
  1815. new cmFileListGeneratorCaseInsensitive(*this));
  1816. return g;
  1817. }
  1818. };
  1819. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  1820. {
  1821. public:
  1822. cmFileListGeneratorGlob(std::string str)
  1823. : Pattern(std::move(str))
  1824. {
  1825. }
  1826. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  1827. : Pattern(r.Pattern)
  1828. {
  1829. }
  1830. private:
  1831. std::string Pattern;
  1832. bool Search(std::string const& parent, cmFileList& lister) override
  1833. {
  1834. // Glob the set of matching files.
  1835. std::string expr = parent;
  1836. expr += this->Pattern;
  1837. cmsys::Glob g;
  1838. if (!g.FindFiles(expr)) {
  1839. return false;
  1840. }
  1841. std::vector<std::string> const& files = g.GetFiles();
  1842. // Look for directories among the matches.
  1843. for (std::string const& f : files) {
  1844. if (cmSystemTools::FileIsDirectory(f)) {
  1845. if (this->Consider(f, lister)) {
  1846. return true;
  1847. }
  1848. }
  1849. }
  1850. return false;
  1851. }
  1852. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1853. {
  1854. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  1855. }
  1856. };
  1857. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  1858. {
  1859. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1860. if (this->DebugMode) {
  1861. fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
  1862. }
  1863. // Skip this if the prefix does not exist.
  1864. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  1865. return false;
  1866. }
  1867. // PREFIX/ (useful on windows or in build trees)
  1868. if (this->SearchDirectory(prefix_in)) {
  1869. return true;
  1870. }
  1871. // Strip the trailing slash because the path generator is about to
  1872. // add one.
  1873. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1874. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  1875. {
  1876. cmFindPackageFileList lister(this);
  1877. lister / cmFileListGeneratorFixed(prefix) /
  1878. cmFileListGeneratorCaseInsensitive("cmake");
  1879. if (lister.Search()) {
  1880. return true;
  1881. }
  1882. }
  1883. // PREFIX/(Foo|foo|FOO).*/
  1884. {
  1885. cmFindPackageFileList lister(this);
  1886. lister / cmFileListGeneratorFixed(prefix) /
  1887. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1888. this->SortDirection);
  1889. if (lister.Search()) {
  1890. return true;
  1891. }
  1892. }
  1893. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  1894. {
  1895. cmFindPackageFileList lister(this);
  1896. lister / cmFileListGeneratorFixed(prefix) /
  1897. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1898. this->SortDirection) /
  1899. cmFileListGeneratorCaseInsensitive("cmake");
  1900. if (lister.Search()) {
  1901. return true;
  1902. }
  1903. }
  1904. // Construct list of common install locations (lib and share).
  1905. std::vector<std::string> common;
  1906. if (!this->LibraryArchitecture.empty()) {
  1907. common.push_back("lib/" + this->LibraryArchitecture);
  1908. }
  1909. if (this->UseLib32Paths) {
  1910. common.emplace_back("lib32");
  1911. }
  1912. if (this->UseLib64Paths) {
  1913. common.emplace_back("lib64");
  1914. }
  1915. if (this->UseLibx32Paths) {
  1916. common.emplace_back("libx32");
  1917. }
  1918. common.emplace_back("lib");
  1919. common.emplace_back("share");
  1920. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1921. {
  1922. cmFindPackageFileList lister(this);
  1923. lister / cmFileListGeneratorFixed(prefix) /
  1924. cmFileListGeneratorEnumerate(common) /
  1925. cmFileListGeneratorFixed("cmake") /
  1926. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1927. this->SortDirection);
  1928. if (lister.Search()) {
  1929. return true;
  1930. }
  1931. }
  1932. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1933. {
  1934. cmFindPackageFileList lister(this);
  1935. lister / cmFileListGeneratorFixed(prefix) /
  1936. cmFileListGeneratorEnumerate(common) /
  1937. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1938. this->SortDirection);
  1939. if (lister.Search()) {
  1940. return true;
  1941. }
  1942. }
  1943. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1944. {
  1945. cmFindPackageFileList lister(this);
  1946. lister / cmFileListGeneratorFixed(prefix) /
  1947. cmFileListGeneratorEnumerate(common) /
  1948. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1949. this->SortDirection) /
  1950. cmFileListGeneratorCaseInsensitive("cmake");
  1951. if (lister.Search()) {
  1952. return true;
  1953. }
  1954. }
  1955. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1956. {
  1957. cmFindPackageFileList lister(this);
  1958. lister / cmFileListGeneratorFixed(prefix) /
  1959. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1960. this->SortDirection) /
  1961. cmFileListGeneratorEnumerate(common) /
  1962. cmFileListGeneratorFixed("cmake") /
  1963. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1964. this->SortDirection);
  1965. if (lister.Search()) {
  1966. return true;
  1967. }
  1968. }
  1969. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1970. {
  1971. cmFindPackageFileList lister(this);
  1972. lister / cmFileListGeneratorFixed(prefix) /
  1973. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1974. this->SortDirection) /
  1975. cmFileListGeneratorEnumerate(common) /
  1976. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1977. this->SortDirection);
  1978. if (lister.Search()) {
  1979. return true;
  1980. }
  1981. }
  1982. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1983. {
  1984. cmFindPackageFileList lister(this);
  1985. lister / cmFileListGeneratorFixed(prefix) /
  1986. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1987. this->SortDirection) /
  1988. cmFileListGeneratorEnumerate(common) /
  1989. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1990. this->SortDirection) /
  1991. cmFileListGeneratorCaseInsensitive("cmake");
  1992. if (lister.Search()) {
  1993. return true;
  1994. }
  1995. }
  1996. return false;
  1997. }
  1998. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  1999. {
  2000. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2001. if (this->DebugMode) {
  2002. fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
  2003. }
  2004. // Strip the trailing slash because the path generator is about to
  2005. // add one.
  2006. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2007. // <prefix>/Foo.framework/Resources/
  2008. {
  2009. cmFindPackageFileList lister(this);
  2010. lister / cmFileListGeneratorFixed(prefix) /
  2011. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2012. cmFileListGeneratorFixed("Resources");
  2013. if (lister.Search()) {
  2014. return true;
  2015. }
  2016. }
  2017. // <prefix>/Foo.framework/Resources/CMake/
  2018. {
  2019. cmFindPackageFileList lister(this);
  2020. lister / cmFileListGeneratorFixed(prefix) /
  2021. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2022. cmFileListGeneratorFixed("Resources") /
  2023. cmFileListGeneratorCaseInsensitive("cmake");
  2024. if (lister.Search()) {
  2025. return true;
  2026. }
  2027. }
  2028. // <prefix>/Foo.framework/Versions/*/Resources/
  2029. {
  2030. cmFindPackageFileList lister(this);
  2031. lister / cmFileListGeneratorFixed(prefix) /
  2032. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2033. cmFileListGeneratorFixed("Versions") /
  2034. cmFileListGeneratorGlob("*/Resources");
  2035. if (lister.Search()) {
  2036. return true;
  2037. }
  2038. }
  2039. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2040. {
  2041. cmFindPackageFileList lister(this);
  2042. lister / cmFileListGeneratorFixed(prefix) /
  2043. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2044. cmFileListGeneratorFixed("Versions") /
  2045. cmFileListGeneratorGlob("*/Resources") /
  2046. cmFileListGeneratorCaseInsensitive("cmake");
  2047. if (lister.Search()) {
  2048. return true;
  2049. }
  2050. }
  2051. return false;
  2052. }
  2053. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2054. {
  2055. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2056. if (this->DebugMode) {
  2057. fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
  2058. }
  2059. // Strip the trailing slash because the path generator is about to
  2060. // add one.
  2061. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2062. // <prefix>/Foo.app/Contents/Resources
  2063. {
  2064. cmFindPackageFileList lister(this);
  2065. lister / cmFileListGeneratorFixed(prefix) /
  2066. cmFileListGeneratorMacProject(this->Names, ".app") /
  2067. cmFileListGeneratorFixed("Contents/Resources");
  2068. if (lister.Search()) {
  2069. return true;
  2070. }
  2071. }
  2072. // <prefix>/Foo.app/Contents/Resources/CMake
  2073. {
  2074. cmFindPackageFileList lister(this);
  2075. lister / cmFileListGeneratorFixed(prefix) /
  2076. cmFileListGeneratorMacProject(this->Names, ".app") /
  2077. cmFileListGeneratorFixed("Contents/Resources") /
  2078. cmFileListGeneratorCaseInsensitive("cmake");
  2079. if (lister.Search()) {
  2080. return true;
  2081. }
  2082. }
  2083. return false;
  2084. }
  2085. // TODO: Debug cmsys::Glob double slash problem.