Resync (forgot to add new files?)
[CMakeLuaTailorHgBridge.git] / CMakeLua / Modules / GetPrerequisites.cmake
blob364943dac9180217351c3f98b5a3393bf3666424
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:
7 #   dumpbin (Windows)
8 #   ldd (Linux/Unix)
9 #   otool (Mac OSX)
11 # The following functions are provided by this script:
12 #   gp_append_unique
13 #   gp_file_type
14 #   is_file_executable
15 #   get_prerequisites
16 #   list_prerequisites
18 # Requires CMake 2.5 or greater because it uses function, break, return and
19 # PARENT_SCOPE.
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)
30   set(contains 0)
32   foreach(item ${${list_var}})
33     if("${item}" STREQUAL "${value}")
34       set(contains 1)
35       break()
36     endif("${item}" STREQUAL "${value}")
37   endforeach(item)
39   if(NOT contains)
40     set(${list_var} ${${list_var}} "${value}" PARENT_SCOPE)
41   endif(NOT contains)
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}.
50 # Possible types are:
51 #   system
52 #   local
53 #   embedded
54 #   other
56 function(gp_file_type original_file file type_var)
57   set(is_embedded 0)
58   set(is_local 0)
59   set(is_system 0)
61   string(TOLOWER "${original_file}" original_lower)
62   string(TOLOWER "${file}" lower)
64   if("${file}" MATCHES "^@(executable|loader)_path")
65     set(is_embedded 1)
66   endif("${file}" MATCHES "^@(executable|loader)_path")
68   if(NOT is_embedded)
69     if("${file}" MATCHES "^(/System/Library/|/usr/lib/)")
70       set(is_system 1)
71     endif("${file}" MATCHES "^(/System/Library/|/usr/lib/)")
73     if(WIN32)
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)")
81         set(is_system 1)
82       endif("${lower}" MATCHES "^(${sysroot}/system|${windir}/system|msvc[^/]+dll)")
83     endif(WIN32)
85     if(NOT is_system)
86       get_filename_component(original_path "${original_lower}" PATH)
87       get_filename_component(path "${lower}" PATH)
88       if("${original_path}" STREQUAL "${path}")
89         set(is_local 1)
90       endif("${original_path}" STREQUAL "${path}")
91     endif(NOT is_system)
92   endif(NOT is_embedded)
94   # Return type string based on computed booleans:
95   #
96   set(type "other")
98   if(is_system)
99     set(type "system")
100   else(is_system)
101     if(is_embedded)
102       set(type "embedded")
103     else(is_embedded)
104       if(is_local)
105         set(type "local")
106       endif(is_local)
107     endif(is_embedded)
108   endif(is_system)
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)
121   #
122   # A file is not executable until proven otherwise:
123   #
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:
130   #
131   if(WIN32)
132     if("${file_full_lower}" MATCHES "\\.(exe|dll)$")
133       set(${result_var} 1 PARENT_SCOPE)
134       return()
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...
140     #
141   endif(WIN32)
143   # Use the information returned from the Unix shell command "file" to
144   # determine if ${file_full} should be considered an executable file...
145   #
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.
149   #
150   if(UNIX)
151     if(NOT file_cmd)
152       find_program(file_cmd "file")
153     endif(NOT file_cmd)
155     if(file_cmd)
156       execute_process(COMMAND "${file_cmd}" "${file_full}"
157         OUTPUT_VARIABLE file_ov
158         OUTPUT_STRIP_TRAILING_WHITESPACE
159         )
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...
166       #
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)
177           return()
178         endif("${file_ov}" MATCHES "text")
179       endif("${file_ov}" MATCHES "executable")
180     else(file_cmd)
181       message(STATUS "warning: No 'file' command, skipping execute_process...")
182     endif(file_cmd)
183   endif(UNIX)
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
199 #   exclude them
201 #  recurse is 0 or 1: 0 for direct prerequisites only, 1 for all prerequisites
202 #   recursively
204 #  optional ARGV4 (verbose) is 0 or 1: 0 to skip informational message output,
205 #   1 to print it
207 function(get_prerequisites target prerequisites_var exclude_system recurse)
208 #  set(verbose 0)
209 #  if(NOT "${ARGV4}" STREQUAL "")
210 #    message(STATUS "ARGV4='${ARGV4}'")
211 #    set(verbose "${ARGV4}")
212 #  endif(NOT "${ARGV4}" STREQUAL "")
213 #  message(STATUS "verbose='${verbose}'")
214   set(verbose 0)
216   set(eol_char "E")
218   # <setup-gp_tool-vars>
219   #
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.
222   #
223   if("${gp_tool}" STREQUAL "")
224     set(gp_tool "ldd")
225     if(APPLE)
226       set(gp_tool "otool")
227     endif(APPLE)
228     if(WIN32)
229       set(gp_tool "dumpbin")
230     endif(WIN32)
231   endif("${gp_tool}" STREQUAL "")
233   set(gp_tool_known 0)
235   if("${gp_tool}" STREQUAL "ldd")
236     set(gp_cmd_args "")
237     set(gp_regex "^\t([\t ]+)[\t ].*${eol_char}$")
238     set(gp_regex_cmp_count 1)
239     set(gp_tool_known 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)
246     set(gp_tool_known 1)
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)
253     set(gp_tool_known 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.")
260     return()
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"
270     "/usr/local/bin"
271     "/usr/bin"
272     )
274   find_program(gp_cmd ${gp_tool} PATHS ${gp_cmd_paths})
276   if(NOT gp_cmd)
277     message(STATUS "warning: could not find '${gp_tool}' - cannot analyze prerequisites...")
278     return()
279   endif(NOT gp_cmd)
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.
286     #
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")
293   #
294   # </setup-gp_tool-vars>
296   # Track new prerequisites at each new level of recursion. Start with an
297   # empty list at each level:
298   #
299   set(unseen_prereqs)
301   # Run gp_cmd on the target:
302   #
303   execute_process(
304     COMMAND ${gp_cmd} ${gp_cmd_args} ${target}
305     OUTPUT_VARIABLE gp_cmd_ov
306     )
308   if(verbose)
309     message(STATUS "<RawOutput cmd='${gp_cmd} ${gp_cmd_args} ${target}'>")
310     message(STATUS "gp_cmd_ov='${gp_cmd_ov}'")
311     message(STATUS "</RawOutput>")
312   endif(verbose)
314   get_filename_component(target_dir "${target}" PATH)
316   # Convert to a list of lines:
317   #
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:
322   #
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.)
344     #
345     set(item "item-NOTFOUND")
346     find_program(item "${raw_item}" PATHS "${target_dir}")
347     if(NOT item)
348       set(item "${raw_item}")
349     endif(NOT item)
351     if(verbose)
352       message(STATUS "raw_item='${raw_item}'")
353       message(STATUS "item='${item}'")
354     endif(verbose)
356     # Add each item unless it is excluded:
357     #
358     set(add_item 1)
360     if(${exclude_system})
361       set(type "")
362       gp_file_type("${target}" "${item}" type)
364       if("${type}" STREQUAL "system")
365         set(add_item 0)
366       endif("${type}" STREQUAL "system")
367     endif(${exclude_system})
369     if(add_item)
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)
374       if(${recurse})
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*
377         # prerequisites...
378         #
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)
382       endif(${recurse})
383     endif(add_item)
384   else("${candidate}" MATCHES "${gp_regex}")
385     if(verbose)
386       message(STATUS "ignoring non-matching line: '${candidate}'")
387     endif(verbose)
388   endif("${candidate}" MATCHES "${gp_regex}")
389   endforeach(candidate)
391   list(SORT ${prerequisites_var})
393   if(${recurse})
394     set(more_inputs ${unseen_prereqs})
395     foreach(input ${more_inputs})
396       get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse})
397     endforeach(input)
398   endif(${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 "")
419     set(all 1)
420   else("${ARGV1}" STREQUAL "")
421     set(all "${ARGV1}")
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 "")
431     set(verbose 0)
432   else("${ARGV3}" STREQUAL "")
433     set(verbose "${ARGV3}")
434   endif("${ARGV3}" STREQUAL "")
436   set(count 0)
437   set(count_str "")
438   set(print_count "${verbose}")
439   set(print_prerequisite_type "${verbose}")
440   set(print_target "${verbose}")
441   set(type_str "")
443   set(prereqs "")
444   get_prerequisites("${target}" prereqs ${exclude_system} ${all})
446   if(print_target)
447     message(STATUS "File '${target}' depends on:")
448   endif(print_target)
450   foreach(d ${prereqs})
451     math(EXPR count "${count} + 1")
453     if(print_count)
454       set(count_str "${count}. ")
455     endif(print_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}")
463   endforeach(d)
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
473 #   listed.
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}'")
481   message(STATUS "")
482   file(${glob_arg} file_list ${glob_exp})
483   foreach(f ${file_list})
484     is_file_executable("${f}" is_f_executable)
485     if(is_f_executable)
486       message(STATUS "=============================================================================")
487       list_prerequisites("${f}" ${ARGN})
488       message(STATUS "")
489     endif(is_f_executable)
490   endforeach(f)
491 endfunction(list_prerequisites_by_glob)