1 # GetPrerequisites.cmake
3 # This script provides functions to list the .dll, .dylib or .so files that an
4 # executable or shared library file depends on. (Its prerequisites.)
6 # It uses various tools to obtain the list of required shared library files:
11 # The following functions are provided by this script:
18 # Requires CMake 2.5 or greater because it uses function, break, return and
21 cmake_minimum_required(VERSION 2.5 FATAL_ERROR)
24 # gp_append_unique list_var value
26 # Append value to the list variable ${list_var} only if the value is not
27 # already in the list.
29 function(gp_append_unique list_var value)
32 foreach(item ${${list_var}})
33 if("${item}" STREQUAL "${value}")
36 endif("${item}" STREQUAL "${value}")
40 set(${list_var} ${${list_var}} "${value}" PARENT_SCOPE)
42 endfunction(gp_append_unique)
45 # gp_file_type original_file file type_var
47 # Return the type of ${file} with respect to ${original_file}. String
48 # describing type of prerequisite is returned in variable named ${type_var}.
56 function(gp_file_type original_file file type_var)
61 string(TOLOWER "${original_file}" original_lower)
62 string(TOLOWER "${file}" lower)
64 if("${file}" MATCHES "^@(executable|loader)_path")
66 endif("${file}" MATCHES "^@(executable|loader)_path")
69 if("${file}" MATCHES "^(/System/Library/|/usr/lib/)")
71 endif("${file}" MATCHES "^(/System/Library/|/usr/lib/)")
74 string(TOLOWER "$ENV{SystemRoot}" sysroot)
75 string(REGEX REPLACE "\\\\" "/" sysroot "${sysroot}")
77 string(TOLOWER "$ENV{windir}" windir)
78 string(REGEX REPLACE "\\\\" "/" windir "${windir}")
80 if("${lower}" MATCHES "^(${sysroot}/system|${windir}/system|msvc[^/]+dll)")
82 endif("${lower}" MATCHES "^(${sysroot}/system|${windir}/system|msvc[^/]+dll)")
86 get_filename_component(original_path "${original_lower}" PATH)
87 get_filename_component(path "${lower}" PATH)
88 if("${original_path}" STREQUAL "${path}")
90 endif("${original_path}" STREQUAL "${path}")
92 endif(NOT is_embedded)
94 # Return type string based on computed booleans:
110 set(${type_var} "${type}" PARENT_SCOPE)
111 endfunction(gp_file_type)
114 # is_file_executable file result_var
116 # Return 1 in ${result_var} if ${file} is a binary executable.
118 # Return 0 in ${result_var} otherwise.
120 function(is_file_executable file result_var)
122 # A file is not executable until proven otherwise:
124 set(${result_var} 0 PARENT_SCOPE)
126 get_filename_component(file_full "${file}" ABSOLUTE)
127 string(TOLOWER "${file_full}" file_full_lower)
129 # If file name ends in .exe or .dll on Windows, *assume* executable:
132 if("${file_full_lower}" MATCHES "\\.(exe|dll)$")
133 set(${result_var} 1 PARENT_SCOPE)
135 endif("${file_full_lower}" MATCHES "\\.(exe|dll)$")
137 # A clause could be added here that uses output or return value of dumpbin
138 # to determine ${result_var}. In 95%+ practical cases, the exe|dll name
139 # match will be sufficient...
143 # Use the information returned from the Unix shell command "file" to
144 # determine if ${file_full} should be considered an executable file...
146 # If the file command's output contains "executable" and does *not* contain
147 # "text" then it is likely an executable suitable for prerequisite analysis
148 # via the get_prerequisites macro.
152 find_program(file_cmd "file")
156 execute_process(COMMAND "${file_cmd}" "${file_full}"
157 OUTPUT_VARIABLE file_ov
158 OUTPUT_STRIP_TRAILING_WHITESPACE
161 # Replace the name of the file in the output with a placeholder token
162 # (the string " _file_full_ ") so that just in case the path name of
163 # the file contains the word "text" or "executable" we are not fooled
164 # into thinking "the wrong thing" because the file name matches the
165 # other 'file' command output we are looking for...
167 string(REPLACE "${file_full}" " _file_full_ " file_ov "${file_ov}")
168 string(TOLOWER "${file_ov}" file_ov)
170 #message(STATUS "file_ov='${file_ov}'")
171 if("${file_ov}" MATCHES "executable")
172 #message(STATUS "executable!")
173 if("${file_ov}" MATCHES "text")
174 #message(STATUS "but text, so *not* a binary executable!")
175 else("${file_ov}" MATCHES "text")
176 set(${result_var} 1 PARENT_SCOPE)
178 endif("${file_ov}" MATCHES "text")
179 endif("${file_ov}" MATCHES "executable")
181 message(STATUS "warning: No 'file' command, skipping execute_process...")
184 endfunction(is_file_executable)
187 # get_prerequisites target prerequisites_var exclude_system recurse
189 # Get the list of shared library files required by ${target}. The list in
190 # the variable named ${prerequisites_var} should be empty on first entry to
191 # this function. On exit, ${prerequisites_var} will contain the list of
192 # required shared library files.
194 # target is the full path to an executable file
196 # prerequisites_var is the name of a CMake variable to contain the results
198 # exclude_system is 0 or 1: 0 to include "system" prerequisites , 1 to
201 # recurse is 0 or 1: 0 for direct prerequisites only, 1 for all prerequisites
204 # optional ARGV4 (verbose) is 0 or 1: 0 to skip informational message output,
207 function(get_prerequisites target prerequisites_var exclude_system recurse)
209 # if(NOT "${ARGV4}" STREQUAL "")
210 # message(STATUS "ARGV4='${ARGV4}'")
211 # set(verbose "${ARGV4}")
212 # endif(NOT "${ARGV4}" STREQUAL "")
213 # message(STATUS "verbose='${verbose}'")
218 # <setup-gp_tool-vars>
220 # Try to choose the right tool by default. Caller can set gp_tool prior to
221 # calling this function to force using a different tool.
223 if("${gp_tool}" STREQUAL "")
229 set(gp_tool "dumpbin")
231 endif("${gp_tool}" STREQUAL "")
235 if("${gp_tool}" STREQUAL "ldd")
237 set(gp_regex "^\t([\t ]+)[\t ].*${eol_char}$")
238 set(gp_regex_cmp_count 1)
240 endif("${gp_tool}" STREQUAL "ldd")
242 if("${gp_tool}" STREQUAL "otool")
243 set(gp_cmd_args "-L")
244 set(gp_regex "^\t([^\t]+) \\(compatibility version ([0-9]+.[0-9]+.[0-9]+), current version ([0-9]+.[0-9]+.[0-9]+)\\)${eol_char}$")
245 set(gp_regex_cmp_count 3)
247 endif("${gp_tool}" STREQUAL "otool")
249 if("${gp_tool}" STREQUAL "dumpbin")
250 set(gp_cmd_args "/dependents")
251 set(gp_regex "^ ([^ ].*[Dd][Ll][Ll])${eol_char}$")
252 set(gp_regex_cmp_count 1)
254 endif("${gp_tool}" STREQUAL "dumpbin")
256 if(NOT gp_tool_known)
257 message(STATUS "warning: gp_tool='${gp_tool}' is an unknown tool...")
258 message(STATUS "CMake function get_prerequisites needs more code to handle '${gp_tool}'")
259 message(STATUS "Valid gp_tool values are dumpbin, ldd and otool.")
261 endif(NOT gp_tool_known)
263 set(gp_cmd_paths ${gp_cmd_paths}
264 "C:/Program Files/Microsoft Visual Studio 9.0/VC/bin"
265 "C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/bin"
266 "C:/Program Files/Microsoft Visual Studio 8/VC/BIN"
267 "C:/Program Files (x86)/Microsoft Visual Studio 8/VC/BIN"
268 "C:/Program Files/Microsoft Visual Studio .NET 2003/VC7/BIN"
269 "C:/Program Files (x86)/Microsoft Visual Studio .NET 2003/VC7/BIN"
274 find_program(gp_cmd ${gp_tool} PATHS ${gp_cmd_paths})
277 message(STATUS "warning: could not find '${gp_tool}' - cannot analyze prerequisites...")
281 if("${gp_tool}" STREQUAL "dumpbin")
282 # When running dumpbin, it also needs the "Common7/IDE" directory in the
283 # PATH. It will already be in the PATH if being run from a Visual Studio
284 # command prompt. Add it to the PATH here in case we are running from a
285 # different command prompt.
287 get_filename_component(gp_cmd_dir "${gp_cmd}" PATH)
288 get_filename_component(gp_cmd_dlls_dir "${gp_cmd_dir}/../../Common7/IDE" ABSOLUTE)
289 if(EXISTS "${gp_cmd_dlls_dir}")
290 set(ENV{PATH} "$ENV{PATH};${gp_cmd_dlls_dir}")
291 endif(EXISTS "${gp_cmd_dlls_dir}")
292 endif("${gp_tool}" STREQUAL "dumpbin")
294 # </setup-gp_tool-vars>
296 # Track new prerequisites at each new level of recursion. Start with an
297 # empty list at each level:
301 # Run gp_cmd on the target:
304 COMMAND ${gp_cmd} ${gp_cmd_args} ${target}
305 OUTPUT_VARIABLE gp_cmd_ov
309 message(STATUS "<RawOutput cmd='${gp_cmd} ${gp_cmd_args} ${target}'>")
310 message(STATUS "gp_cmd_ov='${gp_cmd_ov}'")
311 message(STATUS "</RawOutput>")
314 get_filename_component(target_dir "${target}" PATH)
316 # Convert to a list of lines:
318 string(REGEX REPLACE ";" "\\\\;" candidates "${gp_cmd_ov}")
319 string(REGEX REPLACE "\n" "${eol_char};" candidates "${candidates}")
321 # Analyze each line for file names that match the regular expression:
323 foreach(candidate ${candidates})
324 if("${candidate}" MATCHES "${gp_regex}")
325 # Extract information from each candidate:
326 string(REGEX REPLACE "${gp_regex}" "\\1" raw_item "${candidate}")
328 if(gp_regex_cmp_count GREATER 1)
329 string(REGEX REPLACE "${gp_regex}" "\\2" raw_compat_version "${candidate}")
330 string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" compat_major_version "${raw_compat_version}")
331 string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" compat_minor_version "${raw_compat_version}")
332 string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" compat_patch_version "${raw_compat_version}")
333 endif(gp_regex_cmp_count GREATER 1)
335 if(gp_regex_cmp_count GREATER 2)
336 string(REGEX REPLACE "${gp_regex}" "\\3" raw_current_version "${candidate}")
337 string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" current_major_version "${raw_current_version}")
338 string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" current_minor_version "${raw_current_version}")
339 string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" current_patch_version "${raw_current_version}")
340 endif(gp_regex_cmp_count GREATER 2)
342 # Using find_program on Windows will find dll files that are in the PATH.
343 # (Converting simple file names into full path names if found.)
345 set(item "item-NOTFOUND")
346 find_program(item "${raw_item}" PATHS "${target_dir}")
348 set(item "${raw_item}")
352 message(STATUS "raw_item='${raw_item}'")
353 message(STATUS "item='${item}'")
356 # Add each item unless it is excluded:
360 if(${exclude_system})
362 gp_file_type("${target}" "${item}" type)
364 if("${type}" STREQUAL "system")
366 endif("${type}" STREQUAL "system")
367 endif(${exclude_system})
370 list(LENGTH ${prerequisites_var} list_length_before_append)
371 gp_append_unique(${prerequisites_var} "${item}")
372 list(LENGTH ${prerequisites_var} list_length_after_append)
375 # If item was really added, this is the first time we have seen it.
376 # Add it to unseen_prereqs so that we can recursively add *its*
379 if(NOT list_length_before_append EQUAL list_length_after_append)
380 set(unseen_prereqs ${unseen_prereqs} "${item}")
381 endif(NOT list_length_before_append EQUAL list_length_after_append)
384 else("${candidate}" MATCHES "${gp_regex}")
386 message(STATUS "ignoring non-matching line: '${candidate}'")
388 endif("${candidate}" MATCHES "${gp_regex}")
389 endforeach(candidate)
391 list(SORT ${prerequisites_var})
394 set(more_inputs ${unseen_prereqs})
395 foreach(input ${more_inputs})
396 get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse})
400 set(${prerequisites_var} ${${prerequisites_var}} PARENT_SCOPE)
401 endfunction(get_prerequisites)
404 # list_prerequisites target all exclude_system verbose
406 # ARGV0 (target) is the full path to an executable file
408 # optional ARGV1 (all) is 0 or 1: 0 for direct prerequisites only,
409 # 1 for all prerequisites recursively
411 # optional ARGV2 (exclude_system) is 0 or 1: 0 to include "system"
412 # prerequisites , 1 to exclude them
414 # optional ARGV3 (verbose) is 0 or 1: 0 to print only full path
415 # names of prerequisites, 1 to print extra information
417 function(list_prerequisites target)
418 if("${ARGV1}" STREQUAL "")
420 else("${ARGV1}" STREQUAL "")
422 endif("${ARGV1}" STREQUAL "")
424 if("${ARGV2}" STREQUAL "")
425 set(exclude_system 0)
426 else("${ARGV2}" STREQUAL "")
427 set(exclude_system "${ARGV2}")
428 endif("${ARGV2}" STREQUAL "")
430 if("${ARGV3}" STREQUAL "")
432 else("${ARGV3}" STREQUAL "")
433 set(verbose "${ARGV3}")
434 endif("${ARGV3}" STREQUAL "")
438 set(print_count "${verbose}")
439 set(print_prerequisite_type "${verbose}")
440 set(print_target "${verbose}")
444 get_prerequisites("${target}" prereqs ${exclude_system} ${all})
447 message(STATUS "File '${target}' depends on:")
450 foreach(d ${prereqs})
451 math(EXPR count "${count} + 1")
454 set(count_str "${count}. ")
457 if(print_prerequisite_type)
458 gp_file_type("${target}" "${d}" type)
459 set(type_str " (${type})")
460 endif(print_prerequisite_type)
462 message(STATUS "${count_str}${d}${type_str}")
464 endfunction(list_prerequisites)
467 # list_prerequisites_by_glob glob_arg glob_exp
469 # glob_arg is GLOB or GLOB_RECURSE
471 # glob_exp is a globbing expression used with "file(GLOB" to retrieve a list
472 # of matching files. If a matching file is executable, its prerequisites are
475 # Any additional (optional) arguments provided are passed along as the
476 # optional arguments to the list_prerequisites calls.
478 function(list_prerequisites_by_glob glob_arg glob_exp)
479 message(STATUS "=============================================================================")
480 message(STATUS "List prerequisites of executables matching ${glob_arg} '${glob_exp}'")
482 file(${glob_arg} file_list ${glob_exp})
483 foreach(f ${file_list})
484 is_file_executable("${f}" is_f_executable)
486 message(STATUS "=============================================================================")
487 list_prerequisites("${f}" ${ARGN})
489 endif(is_f_executable)
491 endfunction(list_prerequisites_by_glob)