cmFindPackageCommand.cxx 71 KB

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