GetPrerequisites.cmake 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. GetPrerequisites
  5. ----------------
  6. .. deprecated:: 3.16
  7. Use :command:`file(GET_RUNTIME_DEPENDENCIES)` instead.
  8. Functions to analyze and list executable file prerequisites.
  9. This module provides functions to list the .dll, .dylib or .so files
  10. that an executable or shared library file depends on. (Its
  11. prerequisites.)
  12. It uses various tools to obtain the list of required shared library
  13. files:
  14. ::
  15. dumpbin (Windows)
  16. objdump (MinGW on Windows)
  17. ldd (Linux/Unix)
  18. otool (Mac OSX)
  19. .. versionchanged:: 3.16
  20. The tool specified by ``CMAKE_OBJDUMP`` will be used, if set.
  21. The following functions are provided by this module:
  22. ::
  23. get_prerequisites
  24. list_prerequisites
  25. list_prerequisites_by_glob
  26. gp_append_unique
  27. is_file_executable
  28. gp_item_default_embedded_path
  29. (projects can override with gp_item_default_embedded_path_override)
  30. gp_resolve_item
  31. (projects can override with gp_resolve_item_override)
  32. gp_resolved_file_type
  33. (projects can override with gp_resolved_file_type_override)
  34. gp_file_type
  35. ::
  36. GET_PREREQUISITES(<target> <prerequisites_var> <exclude_system> <recurse>
  37. <exepath> <dirs> [<rpaths>])
  38. Get the list of shared library files required by <target>. The list
  39. in the variable named <prerequisites_var> should be empty on first
  40. entry to this function. On exit, <prerequisites_var> will contain the
  41. list of required shared library files.
  42. <target> is the full path to an executable file. <prerequisites_var>
  43. is the name of a CMake variable to contain the results.
  44. <exclude_system> must be 0 or 1 indicating whether to include or
  45. exclude "system" prerequisites. If <recurse> is set to 1 all
  46. prerequisites will be found recursively, if set to 0 only direct
  47. prerequisites are listed. <exepath> is the path to the top level
  48. executable used for @executable_path replacement on the Mac. <dirs> is
  49. a list of paths where libraries might be found: these paths are
  50. searched first when a target without any path info is given. Then
  51. standard system locations are also searched: PATH, Framework
  52. locations, /usr/lib...
  53. .. versionadded:: 3.14
  54. The variable GET_PREREQUISITES_VERBOSE can be set to true to enable verbose
  55. output.
  56. ::
  57. LIST_PREREQUISITES(<target> [<recurse> [<exclude_system> [<verbose>]]])
  58. Print a message listing the prerequisites of <target>.
  59. <target> is the name of a shared library or executable target or the
  60. full path to a shared library or executable file. If <recurse> is set
  61. to 1 all prerequisites will be found recursively, if set to 0 only
  62. direct prerequisites are listed. <exclude_system> must be 0 or 1
  63. indicating whether to include or exclude "system" prerequisites. With
  64. <verbose> set to 0 only the full path names of the prerequisites are
  65. printed, set to 1 extra information will be displayed.
  66. ::
  67. LIST_PREREQUISITES_BY_GLOB(<glob_arg> <glob_exp>)
  68. Print the prerequisites of shared library and executable files
  69. matching a globbing pattern. <glob_arg> is GLOB or GLOB_RECURSE and
  70. <glob_exp> is a globbing expression used with "file(GLOB" or
  71. "file(GLOB_RECURSE" to retrieve a list of matching files. If a
  72. matching file is executable, its prerequisites are listed.
  73. Any additional (optional) arguments provided are passed along as the
  74. optional arguments to the list_prerequisites calls.
  75. ::
  76. GP_APPEND_UNIQUE(<list_var> <value>)
  77. Append <value> to the list variable <list_var> only if the value is
  78. not already in the list.
  79. ::
  80. IS_FILE_EXECUTABLE(<file> <result_var>)
  81. Return 1 in <result_var> if <file> is a binary executable, 0
  82. otherwise.
  83. ::
  84. GP_ITEM_DEFAULT_EMBEDDED_PATH(<item> <default_embedded_path_var>)
  85. Return the path that others should refer to the item by when the item
  86. is embedded inside a bundle.
  87. Override on a per-project basis by providing a project-specific
  88. gp_item_default_embedded_path_override function.
  89. ::
  90. GP_RESOLVE_ITEM(<context> <item> <exepath> <dirs> <resolved_item_var>
  91. [<rpaths>])
  92. Resolve an item into an existing full path file.
  93. Override on a per-project basis by providing a project-specific
  94. gp_resolve_item_override function.
  95. ::
  96. GP_RESOLVED_FILE_TYPE(<original_file> <file> <exepath> <dirs> <type_var>
  97. [<rpaths>])
  98. Return the type of <file> with respect to <original_file>. String
  99. describing type of prerequisite is returned in variable named
  100. <type_var>.
  101. Use <exepath> and <dirs> if necessary to resolve non-absolute <file>
  102. values -- but only for non-embedded items.
  103. Possible types are:
  104. ::
  105. system
  106. local
  107. embedded
  108. other
  109. Override on a per-project basis by providing a project-specific
  110. gp_resolved_file_type_override function.
  111. ::
  112. GP_FILE_TYPE(<original_file> <file> <type_var>)
  113. Return the type of <file> with respect to <original_file>. String
  114. describing type of prerequisite is returned in variable named
  115. <type_var>.
  116. Possible types are:
  117. ::
  118. system
  119. local
  120. embedded
  121. other
  122. #]=======================================================================]
  123. cmake_policy(PUSH)
  124. cmake_policy(SET CMP0057 NEW) # if IN_LIST
  125. function(gp_append_unique list_var value)
  126. if(NOT value IN_LIST ${list_var})
  127. set(${list_var} ${${list_var}} "${value}" PARENT_SCOPE)
  128. endif()
  129. endfunction()
  130. function(is_file_executable file result_var)
  131. #
  132. # A file is not executable until proven otherwise:
  133. #
  134. set(${result_var} 0 PARENT_SCOPE)
  135. get_filename_component(file_full "${file}" ABSOLUTE)
  136. string(TOLOWER "${file_full}" file_full_lower)
  137. # If file name ends in .exe on Windows, *assume* executable:
  138. #
  139. if(WIN32 AND NOT UNIX)
  140. if("${file_full_lower}" MATCHES "\\.exe$")
  141. set(${result_var} 1 PARENT_SCOPE)
  142. return()
  143. endif()
  144. # A clause could be added here that uses output or return value of dumpbin
  145. # to determine ${result_var}. In 99%+? practical cases, the exe name
  146. # match will be sufficient...
  147. #
  148. endif()
  149. # Use the information returned from the Unix shell command "file" to
  150. # determine if ${file_full} should be considered an executable file...
  151. #
  152. # If the file command's output contains "executable" and does *not* contain
  153. # "text" then it is likely an executable suitable for prerequisite analysis
  154. # via the get_prerequisites macro.
  155. #
  156. if(UNIX)
  157. if(NOT file_cmd)
  158. find_program(file_cmd "file")
  159. mark_as_advanced(file_cmd)
  160. endif()
  161. if(file_cmd)
  162. execute_process(COMMAND "${file_cmd}" "${file_full}"
  163. RESULT_VARIABLE file_rv
  164. OUTPUT_VARIABLE file_ov
  165. ERROR_VARIABLE file_ev
  166. OUTPUT_STRIP_TRAILING_WHITESPACE
  167. )
  168. if(NOT file_rv STREQUAL "0")
  169. message(FATAL_ERROR "${file_cmd} failed: ${file_rv}\n${file_ev}")
  170. endif()
  171. # Replace the name of the file in the output with a placeholder token
  172. # (the string " _file_full_ ") so that just in case the path name of
  173. # the file contains the word "text" or "executable" we are not fooled
  174. # into thinking "the wrong thing" because the file name matches the
  175. # other 'file' command output we are looking for...
  176. #
  177. string(REPLACE "${file_full}" " _file_full_ " file_ov "${file_ov}")
  178. string(TOLOWER "${file_ov}" file_ov)
  179. #message(STATUS "file_ov='${file_ov}'")
  180. if("${file_ov}" MATCHES "executable")
  181. #message(STATUS "executable!")
  182. if("${file_ov}" MATCHES "text")
  183. #message(STATUS "but text, so *not* a binary executable!")
  184. else()
  185. set(${result_var} 1 PARENT_SCOPE)
  186. return()
  187. endif()
  188. endif()
  189. # Also detect position independent executables on Linux,
  190. # where "file" gives "shared object ... (uses shared libraries)"
  191. if("${file_ov}" MATCHES "shared object.*\(uses shared libs\)")
  192. set(${result_var} 1 PARENT_SCOPE)
  193. return()
  194. endif()
  195. # "file" version 5.22 does not print "(used shared libraries)"
  196. # but uses "interpreter"
  197. if("${file_ov}" MATCHES "shared object.*interpreter")
  198. set(${result_var} 1 PARENT_SCOPE)
  199. return()
  200. endif()
  201. else()
  202. message(STATUS "warning: No 'file' command, skipping execute_process...")
  203. endif()
  204. endif()
  205. endfunction()
  206. function(gp_item_default_embedded_path item default_embedded_path_var)
  207. # On Windows and Linux, "embed" prerequisites in the same directory
  208. # as the executable by default:
  209. #
  210. set(path "@executable_path")
  211. # On the Mac, relative to the executable depending on the type
  212. # of the thing we are embedding:
  213. #
  214. if(APPLE)
  215. #
  216. # The assumption here is that all executables in the bundle will be
  217. # in same-level-directories inside the bundle. The parent directory
  218. # of an executable inside the bundle should be MacOS or a sibling of
  219. # MacOS and all embedded paths returned from here will begin with
  220. # "@executable_path/../" and will work from all executables in all
  221. # such same-level-directories inside the bundle.
  222. #
  223. # By default, embed things right next to the main bundle executable:
  224. #
  225. set(path "@executable_path/../../Contents/MacOS")
  226. # Embed frameworks and .dylibs in the embedded "Frameworks" directory
  227. # (sibling of MacOS):
  228. #
  229. if(item MATCHES "[^/]+\\.framework/" OR item MATCHES "\\.dylib$")
  230. set(path "@executable_path/../Frameworks")
  231. endif()
  232. endif()
  233. # Provide a hook so that projects can override the default embedded location
  234. # of any given library by whatever logic they choose:
  235. #
  236. if(COMMAND gp_item_default_embedded_path_override)
  237. gp_item_default_embedded_path_override("${item}" path)
  238. endif()
  239. set(${default_embedded_path_var} "${path}" PARENT_SCOPE)
  240. endfunction()
  241. function(gp_resolve_item context item exepath dirs resolved_item_var)
  242. set(resolved 0)
  243. set(resolved_item "${item}")
  244. if(ARGC GREATER 5)
  245. set(rpaths "${ARGV5}")
  246. else()
  247. set(rpaths "")
  248. endif()
  249. # Is it already resolved?
  250. #
  251. if(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
  252. set(resolved 1)
  253. endif()
  254. if(NOT resolved)
  255. if(item MATCHES "^@executable_path")
  256. #
  257. # @executable_path references are assumed relative to exepath
  258. #
  259. string(REPLACE "@executable_path" "${exepath}" ri "${item}")
  260. get_filename_component(ri "${ri}" ABSOLUTE)
  261. if(EXISTS "${ri}")
  262. #message(STATUS "info: embedded item exists (${ri})")
  263. set(resolved 1)
  264. set(resolved_item "${ri}")
  265. else()
  266. message(STATUS "warning: embedded item does not exist '${ri}'")
  267. endif()
  268. endif()
  269. endif()
  270. if(NOT resolved)
  271. if(item MATCHES "^@loader_path")
  272. #
  273. # @loader_path references are assumed relative to the
  274. # PATH of the given "context" (presumably another library)
  275. #
  276. get_filename_component(contextpath "${context}" PATH)
  277. string(REPLACE "@loader_path" "${contextpath}" ri "${item}")
  278. get_filename_component(ri "${ri}" ABSOLUTE)
  279. if(EXISTS "${ri}")
  280. #message(STATUS "info: embedded item exists (${ri})")
  281. set(resolved 1)
  282. set(resolved_item "${ri}")
  283. else()
  284. message(STATUS "warning: embedded item does not exist '${ri}'")
  285. endif()
  286. endif()
  287. endif()
  288. if(NOT resolved)
  289. if(item MATCHES "^@rpath")
  290. #
  291. # @rpath references are relative to the paths built into the binaries with -rpath
  292. # We handle this case like we do for other Unixes
  293. #
  294. string(REPLACE "@rpath/" "" norpath_item "${item}")
  295. set(ri "ri-NOTFOUND")
  296. find_file(ri "${norpath_item}" ${exepath} ${dirs} ${rpaths} NO_DEFAULT_PATH)
  297. if(ri)
  298. #message(STATUS "info: 'find_file' in exepath/dirs/rpaths (${ri})")
  299. set(resolved 1)
  300. set(resolved_item "${ri}")
  301. set(ri "ri-NOTFOUND")
  302. endif()
  303. endif()
  304. endif()
  305. if(NOT resolved)
  306. set(ri "ri-NOTFOUND")
  307. find_file(ri "${item}" ${exepath} ${dirs} NO_DEFAULT_PATH)
  308. find_file(ri "${item}" ${exepath} ${dirs} /usr/lib)
  309. get_filename_component(basename_item "${item}" NAME)
  310. find_file(ri "${basename_item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
  311. find_file(ri "${basename_item}" PATHS /usr/lib)
  312. if(ri)
  313. #message(STATUS "info: 'find_file' in exepath/dirs (${ri})")
  314. set(resolved 1)
  315. set(resolved_item "${ri}")
  316. set(ri "ri-NOTFOUND")
  317. endif()
  318. endif()
  319. if(NOT resolved)
  320. if(item MATCHES "[^/]+\\.framework/")
  321. set(fw "fw-NOTFOUND")
  322. find_file(fw "${item}"
  323. "~/Library/Frameworks"
  324. "/Library/Frameworks"
  325. "/System/Library/Frameworks"
  326. )
  327. if(fw)
  328. #message(STATUS "info: 'find_file' found framework (${fw})")
  329. set(resolved 1)
  330. set(resolved_item "${fw}")
  331. set(fw "fw-NOTFOUND")
  332. endif()
  333. endif()
  334. endif()
  335. # Using find_program on Windows will find dll files that are in the PATH.
  336. # (Converting simple file names into full path names if found.)
  337. #
  338. if(WIN32 AND NOT UNIX)
  339. if(NOT resolved)
  340. set(ri "ri-NOTFOUND")
  341. find_program(ri "${item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
  342. find_program(ri "${item}" PATHS ${exepath} ${dirs})
  343. if(ri)
  344. #message(STATUS "info: 'find_program' in exepath/dirs (${ri})")
  345. set(resolved 1)
  346. set(resolved_item "${ri}")
  347. set(ri "ri-NOTFOUND")
  348. endif()
  349. endif()
  350. endif()
  351. # Provide a hook so that projects can override item resolution
  352. # by whatever logic they choose:
  353. #
  354. if(COMMAND gp_resolve_item_override)
  355. gp_resolve_item_override("${context}" "${item}" "${exepath}" "${dirs}" resolved_item resolved)
  356. endif()
  357. if(NOT resolved)
  358. message(STATUS "
  359. warning: cannot resolve item '${item}'
  360. possible problems:
  361. need more directories?
  362. need to use InstallRequiredSystemLibraries?
  363. run in install tree instead of build tree?
  364. ")
  365. # message(STATUS "
  366. #******************************************************************************
  367. #warning: cannot resolve item '${item}'
  368. #
  369. # possible problems:
  370. # need more directories?
  371. # need to use InstallRequiredSystemLibraries?
  372. # run in install tree instead of build tree?
  373. #
  374. # context='${context}'
  375. # item='${item}'
  376. # exepath='${exepath}'
  377. # dirs='${dirs}'
  378. # resolved_item_var='${resolved_item_var}'
  379. #******************************************************************************
  380. #")
  381. endif()
  382. set(${resolved_item_var} "${resolved_item}" PARENT_SCOPE)
  383. endfunction()
  384. function(gp_resolved_file_type original_file file exepath dirs type_var)
  385. if(ARGC GREATER 5)
  386. set(rpaths "${ARGV5}")
  387. else()
  388. set(rpaths "")
  389. endif()
  390. #message(STATUS "**")
  391. if(NOT IS_ABSOLUTE "${original_file}")
  392. message(STATUS "warning: gp_resolved_file_type expects absolute full path for first arg original_file")
  393. endif()
  394. if(IS_ABSOLUTE "${original_file}")
  395. get_filename_component(original_file "${original_file}" ABSOLUTE) # canonicalize path
  396. endif()
  397. set(is_embedded 0)
  398. set(is_local 0)
  399. set(is_system 0)
  400. set(resolved_file "${file}")
  401. if("${file}" MATCHES "^@(executable|loader)_path")
  402. set(is_embedded 1)
  403. endif()
  404. if(NOT is_embedded)
  405. if(NOT IS_ABSOLUTE "${file}")
  406. gp_resolve_item("${original_file}" "${file}" "${exepath}" "${dirs}" resolved_file "${rpaths}")
  407. endif()
  408. if(IS_ABSOLUTE "${resolved_file}")
  409. get_filename_component(resolved_file "${resolved_file}" ABSOLUTE) # canonicalize path
  410. endif()
  411. string(TOLOWER "${original_file}" original_lower)
  412. string(TOLOWER "${resolved_file}" lower)
  413. if(UNIX)
  414. if(resolved_file MATCHES "^/*(/lib/|/lib32/|/libx32/|/lib64/|/usr/lib/|/usr/lib32/|/usr/libx32/|/usr/lib64/|/usr/X11R6/|/usr/bin/)")
  415. set(is_system 1)
  416. endif()
  417. endif()
  418. if(APPLE)
  419. if(resolved_file MATCHES "^(/System/Library/|/usr/lib/)")
  420. set(is_system 1)
  421. endif()
  422. endif()
  423. if(WIN32)
  424. string(TOLOWER "$ENV{SystemRoot}" sysroot)
  425. file(TO_CMAKE_PATH "${sysroot}" sysroot)
  426. string(TOLOWER "$ENV{windir}" windir)
  427. file(TO_CMAKE_PATH "${windir}" windir)
  428. if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-|vcruntime)[^/]+dll)")
  429. set(is_system 1)
  430. endif()
  431. if(UNIX)
  432. # if cygwin, we can get the properly formed windows paths from cygpath
  433. find_program(CYGPATH_EXECUTABLE cygpath)
  434. if(CYGPATH_EXECUTABLE)
  435. execute_process(COMMAND ${CYGPATH_EXECUTABLE} -W
  436. RESULT_VARIABLE env_rv
  437. OUTPUT_VARIABLE env_windir
  438. ERROR_VARIABLE env_ev
  439. OUTPUT_STRIP_TRAILING_WHITESPACE)
  440. if(NOT env_rv STREQUAL "0")
  441. message(FATAL_ERROR "${CYGPATH_EXECUTABLE} -W failed: ${env_rv}\n${env_ev}")
  442. endif()
  443. execute_process(COMMAND ${CYGPATH_EXECUTABLE} -S
  444. RESULT_VARIABLE env_rv
  445. OUTPUT_VARIABLE env_sysdir
  446. ERROR_VARIABLE env_ev
  447. OUTPUT_STRIP_TRAILING_WHITESPACE)
  448. if(NOT env_rv STREQUAL "0")
  449. message(FATAL_ERROR "${CYGPATH_EXECUTABLE} -S failed: ${env_rv}\n${env_ev}")
  450. endif()
  451. string(TOLOWER "${env_windir}" windir)
  452. string(TOLOWER "${env_sysdir}" sysroot)
  453. if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-|vcruntime)[^/]+dll)")
  454. set(is_system 1)
  455. endif()
  456. endif()
  457. endif()
  458. endif()
  459. if(NOT is_system)
  460. get_filename_component(original_path "${original_lower}" PATH)
  461. get_filename_component(path "${lower}" PATH)
  462. if(original_path STREQUAL path)
  463. set(is_local 1)
  464. else()
  465. string(LENGTH "${original_path}/" original_length)
  466. string(LENGTH "${lower}" path_length)
  467. if(${path_length} GREATER ${original_length})
  468. string(SUBSTRING "${lower}" 0 ${original_length} path)
  469. if("${original_path}/" STREQUAL path)
  470. set(is_embedded 1)
  471. endif()
  472. endif()
  473. endif()
  474. endif()
  475. endif()
  476. # Return type string based on computed booleans:
  477. #
  478. set(type "other")
  479. if(is_system)
  480. set(type "system")
  481. elseif(is_embedded)
  482. set(type "embedded")
  483. elseif(is_local)
  484. set(type "local")
  485. endif()
  486. #message(STATUS "gp_resolved_file_type: '${file}' '${resolved_file}'")
  487. #message(STATUS " type: '${type}'")
  488. if(NOT is_embedded)
  489. if(NOT IS_ABSOLUTE "${resolved_file}")
  490. if(lower MATCHES "^(msvc|api-ms-win-|vcruntime)[^/]+dll" AND is_system)
  491. message(STATUS "info: non-absolute msvc file '${file}' returning type '${type}'")
  492. else()
  493. message(STATUS "warning: gp_resolved_file_type non-absolute file '${file}' returning type '${type}' -- possibly incorrect")
  494. endif()
  495. endif()
  496. endif()
  497. # Provide a hook so that projects can override the decision on whether a
  498. # library belongs to the system or not by whatever logic they choose:
  499. #
  500. if(COMMAND gp_resolved_file_type_override)
  501. gp_resolved_file_type_override("${resolved_file}" type)
  502. endif()
  503. set(${type_var} "${type}" PARENT_SCOPE)
  504. #message(STATUS "**")
  505. endfunction()
  506. function(gp_file_type original_file file type_var)
  507. if(NOT IS_ABSOLUTE "${original_file}")
  508. message(STATUS "warning: gp_file_type expects absolute full path for first arg original_file")
  509. endif()
  510. get_filename_component(exepath "${original_file}" PATH)
  511. set(type "")
  512. gp_resolved_file_type("${original_file}" "${file}" "${exepath}" "" type)
  513. set(${type_var} "${type}" PARENT_SCOPE)
  514. endfunction()
  515. function(get_prerequisites target prerequisites_var exclude_system recurse exepath dirs)
  516. set(verbose 0)
  517. set(eol_char "E")
  518. if(ARGC GREATER 6)
  519. set(rpaths "${ARGV6}")
  520. else()
  521. set(rpaths "")
  522. endif()
  523. if(GET_PREREQUISITES_VERBOSE)
  524. set(verbose 1)
  525. endif()
  526. if(NOT IS_ABSOLUTE "${target}")
  527. message("warning: target '${target}' is not absolute...")
  528. endif()
  529. if(NOT EXISTS "${target}")
  530. message("warning: target '${target}' does not exist...")
  531. return()
  532. endif()
  533. # Check for a script by extension (.bat,.sh,...) or if the file starts with "#!" (shebang)
  534. file(READ ${target} file_contents LIMIT 5)
  535. if(target MATCHES "\\.(bat|c?sh|bash|ksh|cmd)$" OR file_contents MATCHES "^#!")
  536. message(STATUS "GetPrerequisites(${target}) : ignoring script file")
  537. # Clear var
  538. set(${prerequisites_var} "" PARENT_SCOPE)
  539. return()
  540. endif()
  541. set(gp_cmd_paths ${gp_cmd_paths}
  542. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\14.0;InstallDir]/../../VC/bin"
  543. "$ENV{VS140COMNTOOLS}/../../VC/bin"
  544. "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin"
  545. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\12.0;InstallDir]/../../VC/bin"
  546. "$ENV{VS120COMNTOOLS}/../../VC/bin"
  547. "C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin"
  548. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\11.0;InstallDir]/../../VC/bin"
  549. "$ENV{VS110COMNTOOLS}/../../VC/bin"
  550. "C:/Program Files (x86)/Microsoft Visual Studio 11.0/VC/bin"
  551. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\10.0;InstallDir]/../../VC/bin"
  552. "$ENV{VS100COMNTOOLS}/../../VC/bin"
  553. "C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/bin"
  554. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0;InstallDir]/../../VC/bin"
  555. "$ENV{VS90COMNTOOLS}/../../VC/bin"
  556. "C:/Program Files/Microsoft Visual Studio 9.0/VC/bin"
  557. "C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/bin"
  558. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0;InstallDir]/../../VC/bin"
  559. "$ENV{VS80COMNTOOLS}/../../VC/bin"
  560. "C:/Program Files/Microsoft Visual Studio 8/VC/BIN"
  561. "C:/Program Files (x86)/Microsoft Visual Studio 8/VC/BIN"
  562. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\7.1;InstallDir]/../../VC7/bin"
  563. "$ENV{VS71COMNTOOLS}/../../VC7/bin"
  564. "C:/Program Files/Microsoft Visual Studio .NET 2003/VC7/BIN"
  565. "C:/Program Files (x86)/Microsoft Visual Studio .NET 2003/VC7/BIN"
  566. )
  567. # <setup-gp_tool-vars>
  568. #
  569. # Try to choose the right tool by default. Caller can set gp_tool prior to
  570. # calling this function to force using a different tool.
  571. #
  572. if(NOT gp_tool)
  573. set(gp_tool "ldd")
  574. if(APPLE)
  575. set(gp_tool "otool")
  576. endif()
  577. if(WIN32 AND NOT UNIX) # This is how to check for cygwin, har!
  578. find_program(gp_dumpbin "dumpbin" PATHS ${gp_cmd_paths})
  579. if(gp_dumpbin)
  580. set(gp_tool "dumpbin")
  581. elseif(CMAKE_OBJDUMP) # Try harder. Maybe we're on MinGW
  582. set(gp_tool "${CMAKE_OBJDUMP}")
  583. else()
  584. set(gp_tool "objdump")
  585. endif()
  586. endif()
  587. endif()
  588. find_program(gp_cmd ${gp_tool} PATHS ${gp_cmd_paths})
  589. if(NOT gp_cmd)
  590. message(STATUS "warning: could not find '${gp_tool}' - cannot analyze prerequisites...")
  591. return()
  592. endif()
  593. set(gp_cmd_maybe_filter) # optional command to pre-filter gp_tool results
  594. if(gp_tool MATCHES "ldd$")
  595. set(gp_cmd_args "")
  596. set(gp_regex "^[\t ]*[^\t ]+ =>[\t ]+([^\t\(]+)( \(.+\))?${eol_char}$")
  597. set(gp_regex_error "not found${eol_char}$")
  598. set(gp_regex_fallback "^[\t ]*([^\t ]+) => ([^\t ]+).*${eol_char}$")
  599. set(gp_regex_cmp_count 1)
  600. elseif(gp_tool MATCHES "otool$")
  601. set(gp_cmd_args "-L")
  602. set(gp_regex "^\t([^\t]+) \\(compatibility version ([0-9]+.[0-9]+.[0-9]+), current version ([0-9]+.[0-9]+.[0-9]+)(, weak)?\\)${eol_char}$")
  603. set(gp_regex_error "")
  604. set(gp_regex_fallback "")
  605. set(gp_regex_cmp_count 3)
  606. elseif(gp_tool MATCHES "dumpbin$")
  607. set(gp_cmd_args "/dependents")
  608. set(gp_regex "^ ([^ ].*[Dd][Ll][Ll])${eol_char}$")
  609. set(gp_regex_error "")
  610. set(gp_regex_fallback "")
  611. set(gp_regex_cmp_count 1)
  612. elseif(gp_tool MATCHES "objdump(\\.exe)?$")
  613. set(gp_cmd_args "-p")
  614. set(gp_regex "^[\t ]*DLL Name: (.*\\.[Dd][Ll][Ll])${eol_char}$")
  615. set(gp_regex_error "")
  616. set(gp_regex_fallback "")
  617. set(gp_regex_cmp_count 1)
  618. # objdump generates copious output so we create a grep filter to pre-filter results
  619. if(WIN32)
  620. find_program(gp_grep_cmd findstr)
  621. set(gp_grep_cmd_arg "")
  622. else()
  623. find_program(gp_grep_cmd grep)
  624. set(gp_grep_cmd_arg "-a")
  625. endif()
  626. if(gp_grep_cmd)
  627. set(gp_cmd_maybe_filter COMMAND ${gp_grep_cmd} "${gp_grep_cmd_arg}" "^[[:blank:]]*DLL Name: ")
  628. endif()
  629. else()
  630. message(STATUS "warning: gp_tool='${gp_tool}' is an unknown tool...")
  631. message(STATUS "CMake function get_prerequisites needs more code to handle '${gp_tool}'")
  632. message(STATUS "Valid gp_tool values are dumpbin, ldd, objdump and otool.")
  633. return()
  634. endif()
  635. if(gp_tool MATCHES "dumpbin$")
  636. # When running dumpbin, it also needs the "Common7/IDE" directory in the
  637. # PATH. It will already be in the PATH if being run from a Visual Studio
  638. # command prompt. Add it to the PATH here in case we are running from a
  639. # different command prompt.
  640. #
  641. get_filename_component(gp_cmd_dir "${gp_cmd}" PATH)
  642. get_filename_component(gp_cmd_dlls_dir "${gp_cmd_dir}/../../Common7/IDE" ABSOLUTE)
  643. # Use cmake paths as a user may have a PATH element ending with a backslash.
  644. # This will escape the list delimiter and create havoc!
  645. if(EXISTS "${gp_cmd_dlls_dir}")
  646. # only add to the path if it is not already in the path
  647. set(gp_found_cmd_dlls_dir 0)
  648. file(TO_CMAKE_PATH "$ENV{PATH}" env_path)
  649. foreach(gp_env_path_element ${env_path})
  650. if(gp_env_path_element STREQUAL gp_cmd_dlls_dir)
  651. set(gp_found_cmd_dlls_dir 1)
  652. endif()
  653. endforeach()
  654. if(NOT gp_found_cmd_dlls_dir)
  655. file(TO_NATIVE_PATH "${gp_cmd_dlls_dir}" gp_cmd_dlls_dir)
  656. set(ENV{PATH} "$ENV{PATH};${gp_cmd_dlls_dir}")
  657. endif()
  658. endif()
  659. endif()
  660. #
  661. # </setup-gp_tool-vars>
  662. if(gp_tool MATCHES "ldd$")
  663. set(old_ld_env "$ENV{LD_LIBRARY_PATH}")
  664. set(new_ld_env "${exepath}")
  665. foreach(dir ${dirs})
  666. string(APPEND new_ld_env ":${dir}")
  667. endforeach()
  668. set(ENV{LD_LIBRARY_PATH} "${new_ld_env}:$ENV{LD_LIBRARY_PATH}")
  669. endif()
  670. # Track new prerequisites at each new level of recursion. Start with an
  671. # empty list at each level:
  672. #
  673. set(unseen_prereqs)
  674. # Run gp_cmd on the target:
  675. #
  676. execute_process(
  677. COMMAND ${gp_cmd} ${gp_cmd_args} ${target}
  678. ${gp_cmd_maybe_filter}
  679. RESULT_VARIABLE gp_rv
  680. OUTPUT_VARIABLE gp_cmd_ov
  681. ERROR_VARIABLE gp_ev
  682. )
  683. if(gp_tool MATCHES "dumpbin$")
  684. # Exclude delay load dependencies under windows (they are listed in dumpbin output after the message below)
  685. string(FIND "${gp_cmd_ov}" "Image has the following delay load dependencies" gp_delayload_pos)
  686. if (${gp_delayload_pos} GREATER -1)
  687. string(SUBSTRING "${gp_cmd_ov}" 0 ${gp_delayload_pos} gp_cmd_ov_no_delayload_deps)
  688. string(SUBSTRING "${gp_cmd_ov}" ${gp_delayload_pos} -1 gp_cmd_ov_delayload_deps)
  689. if (verbose)
  690. message(STATUS "GetPrerequisites(${target}) : ignoring the following delay load dependencies :\n ${gp_cmd_ov_delayload_deps}")
  691. endif()
  692. set(gp_cmd_ov ${gp_cmd_ov_no_delayload_deps})
  693. endif()
  694. endif()
  695. if(NOT gp_rv STREQUAL "0")
  696. if(gp_tool MATCHES "dumpbin$")
  697. # dumpbin error messages seem to go to stdout
  698. message(FATAL_ERROR "${gp_cmd} failed: ${gp_rv}\n${gp_ev}\n${gp_cmd_ov}")
  699. else()
  700. message(FATAL_ERROR "${gp_cmd} failed: ${gp_rv}\n${gp_ev}")
  701. endif()
  702. endif()
  703. if(gp_tool MATCHES "ldd$")
  704. set(ENV{LD_LIBRARY_PATH} "${old_ld_env}")
  705. endif()
  706. if(verbose)
  707. message(STATUS "<RawOutput cmd='${gp_cmd} ${gp_cmd_args} ${target}'>")
  708. message(STATUS "gp_cmd_ov='${gp_cmd_ov}'")
  709. message(STATUS "</RawOutput>")
  710. endif()
  711. get_filename_component(target_dir "${target}" PATH)
  712. # Convert to a list of lines:
  713. #
  714. string(REPLACE ";" "\\;" candidates "${gp_cmd_ov}")
  715. string(REPLACE "\n" "${eol_char};" candidates "${candidates}")
  716. # check for install id and remove it from list, since otool -L can include a
  717. # reference to itself
  718. set(gp_install_id)
  719. if(gp_tool MATCHES "otool$")
  720. execute_process(
  721. COMMAND ${gp_cmd} -D ${target}
  722. RESULT_VARIABLE otool_rv
  723. OUTPUT_VARIABLE gp_install_id_ov
  724. ERROR_VARIABLE otool_ev
  725. )
  726. if(NOT otool_rv STREQUAL "0")
  727. message(FATAL_ERROR "otool -D failed: ${otool_rv}\n${otool_ev}")
  728. endif()
  729. # second line is install name
  730. string(REGEX REPLACE ".*:\n" "" gp_install_id "${gp_install_id_ov}")
  731. if(gp_install_id)
  732. # trim
  733. string(REGEX MATCH "[^\n ].*[^\n ]" gp_install_id "${gp_install_id}")
  734. #message("INSTALL ID is \"${gp_install_id}\"")
  735. endif()
  736. endif()
  737. # Analyze each line for file names that match the regular expression:
  738. #
  739. foreach(candidate ${candidates})
  740. if("${candidate}" MATCHES "${gp_regex}")
  741. # Extract information from each candidate:
  742. if(gp_regex_error AND "${candidate}" MATCHES "${gp_regex_error}")
  743. string(REGEX REPLACE "${gp_regex_fallback}" "\\1" raw_item "${candidate}")
  744. else()
  745. string(REGEX REPLACE "${gp_regex}" "\\1" raw_item "${candidate}")
  746. endif()
  747. if(gp_regex_cmp_count GREATER 1)
  748. string(REGEX REPLACE "${gp_regex}" "\\2" raw_compat_version "${candidate}")
  749. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" compat_major_version "${raw_compat_version}")
  750. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" compat_minor_version "${raw_compat_version}")
  751. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" compat_patch_version "${raw_compat_version}")
  752. endif()
  753. if(gp_regex_cmp_count GREATER 2)
  754. string(REGEX REPLACE "${gp_regex}" "\\3" raw_current_version "${candidate}")
  755. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" current_major_version "${raw_current_version}")
  756. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" current_minor_version "${raw_current_version}")
  757. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" current_patch_version "${raw_current_version}")
  758. endif()
  759. # Use the raw_item as the list entries returned by this function. Use the
  760. # gp_resolve_item function to resolve it to an actual full path file if
  761. # necessary.
  762. #
  763. set(item "${raw_item}")
  764. # Add each item unless it is excluded:
  765. #
  766. set(add_item 1)
  767. if(item STREQUAL gp_install_id)
  768. set(add_item 0)
  769. endif()
  770. if(add_item AND ${exclude_system})
  771. set(type "")
  772. gp_resolved_file_type("${target}" "${item}" "${exepath}" "${dirs}" type "${rpaths}")
  773. if(type STREQUAL "system")
  774. set(add_item 0)
  775. endif()
  776. endif()
  777. if(add_item)
  778. list(LENGTH ${prerequisites_var} list_length_before_append)
  779. gp_append_unique(${prerequisites_var} "${item}")
  780. list(LENGTH ${prerequisites_var} list_length_after_append)
  781. if(${recurse})
  782. # If item was really added, this is the first time we have seen it.
  783. # Add it to unseen_prereqs so that we can recursively add *its*
  784. # prerequisites...
  785. #
  786. # But first: resolve its name to an absolute full path name such
  787. # that the analysis tools can simply accept it as input.
  788. #
  789. if(NOT list_length_before_append EQUAL list_length_after_append)
  790. gp_resolve_item("${target}" "${item}" "${exepath}" "${dirs}" resolved_item "${rpaths}")
  791. if(EXISTS "${resolved_item}")
  792. # Recurse only if we could resolve the item.
  793. # Otherwise the prerequisites_var list will be cleared
  794. set(unseen_prereqs ${unseen_prereqs} "${resolved_item}")
  795. endif()
  796. endif()
  797. endif()
  798. endif()
  799. else()
  800. if(verbose)
  801. message(STATUS "ignoring non-matching line: '${candidate}'")
  802. endif()
  803. endif()
  804. endforeach()
  805. list(LENGTH ${prerequisites_var} prerequisites_var_length)
  806. if(prerequisites_var_length GREATER 0)
  807. list(SORT ${prerequisites_var})
  808. endif()
  809. if(${recurse})
  810. set(more_inputs ${unseen_prereqs})
  811. foreach(input ${more_inputs})
  812. get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse} "${exepath}" "${dirs}" "${rpaths}")
  813. endforeach()
  814. endif()
  815. set(${prerequisites_var} ${${prerequisites_var}} PARENT_SCOPE)
  816. endfunction()
  817. function(list_prerequisites target)
  818. if(ARGC GREATER 1 AND NOT "${ARGV1}" STREQUAL "")
  819. set(all "${ARGV1}")
  820. else()
  821. set(all 1)
  822. endif()
  823. if(ARGC GREATER 2 AND NOT "${ARGV2}" STREQUAL "")
  824. set(exclude_system "${ARGV2}")
  825. else()
  826. set(exclude_system 0)
  827. endif()
  828. if(ARGC GREATER 3 AND NOT "${ARGV3}" STREQUAL "")
  829. set(verbose "${ARGV3}")
  830. else()
  831. set(verbose 0)
  832. endif()
  833. set(count 0)
  834. set(count_str "")
  835. set(print_count "${verbose}")
  836. set(print_prerequisite_type "${verbose}")
  837. set(print_target "${verbose}")
  838. set(type_str "")
  839. get_filename_component(exepath "${target}" PATH)
  840. set(prereqs "")
  841. get_prerequisites("${target}" prereqs ${exclude_system} ${all} "${exepath}" "")
  842. if(print_target)
  843. message(STATUS "File '${target}' depends on:")
  844. endif()
  845. foreach(d ${prereqs})
  846. math(EXPR count "${count} + 1")
  847. if(print_count)
  848. set(count_str "${count}. ")
  849. endif()
  850. if(print_prerequisite_type)
  851. gp_file_type("${target}" "${d}" type)
  852. set(type_str " (${type})")
  853. endif()
  854. message(STATUS "${count_str}${d}${type_str}")
  855. endforeach()
  856. endfunction()
  857. function(list_prerequisites_by_glob glob_arg glob_exp)
  858. message(STATUS "=============================================================================")
  859. message(STATUS "List prerequisites of executables matching ${glob_arg} '${glob_exp}'")
  860. message(STATUS "")
  861. file(${glob_arg} file_list ${glob_exp})
  862. foreach(f ${file_list})
  863. is_file_executable("${f}" is_f_executable)
  864. if(is_f_executable)
  865. message(STATUS "=============================================================================")
  866. list_prerequisites("${f}" ${ARGN})
  867. message(STATUS "")
  868. endif()
  869. endforeach()
  870. endfunction()
  871. cmake_policy(POP)