cmFindPackageCommand.cxx 71 KB

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