module PhusionPassenger::PlatformInfo

This module autodetects various platform-specific information, and provides that information through constants.

Users can change the detection behavior by setting the environment variable APXS2 to the correct 'apxs' (or 'apxs2') binary, as provided by Apache.

Constants

GEM_HOME
GEM_PATH
RUBY_ENGINE

Public Class Methods

a2dismod(options = {}) click to toggle source

The absolute path to the 'a2enmod' executable.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 420
def self.a2dismod(options = {})
  apxs2 = options[:apxs2] || self.apxs2
  dir = File.dirname(apxs2)
  # a2dismod is supposed to be a Debian extension that only works
  # on the APT-installed Apache, so only return non-nil if we're
  # working against the APT-installed Apache.
  if dir == "/usr/bin" || dir == "/usr/sbin"
    if env_defined?('A2DISMOD')
      return ENV['A2DISMOD']
    else
      return find_apache2_executable("a2dismod", options)
    end
  end
end
a2enmod(options = {}) click to toggle source

The absolute path to the 'a2enmod' executable.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 401
def self.a2enmod(options = {})
  apxs2 = options[:apxs2] || self.apxs2
  dir = File.dirname(apxs2)
  # a2enmod is supposed to be a Debian extension that only works
  # on the APT-installed Apache, so only return non-nil if we're
  # working against the APT-installed Apache.
  if dir == "/usr/bin" || dir == "/usr/sbin"
    if env_defined?('A2ENMOD')
      return ENV['A2ENMOD']
    else
      return find_apache2_executable("a2enmod", options)
    end
  else
    return nil
  end
end
adress_sanitizer_flag() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 441
def self.adress_sanitizer_flag
  if cc_is_clang?
    if %x#{cc} --help` =~ /-fsanitize=/
      return "-fsanitize=address"
    else
      return "-faddress-sanitizer"
    end
  else
    return nil
  end
end
apache2_bindir(options = {}) click to toggle source

The absolute path to the Apache 2 'bin' directory, or nil if unknown.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 527
def self.apache2_bindir(options = {})
  apxs2 = options[:apxs2] || self.apxs2
  if apxs2.nil?
    return nil
  else
    return %x#{apxs2} -q BINDIR 2>/dev/null`.strip
  end
end
apache2_module_c_or_cxxflags(language, with_apr_flags = true) click to toggle source

The C compiler flags that are necessary to compile an Apache module. Also includes APR and APU compiler flags if with_apr_flags is true.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 563
def self.apache2_module_c_or_cxxflags(language, with_apr_flags = true)
  flags = [""]
  if (language == :c && cc_is_sun_studio?) || (language == :cxx && cxx_is_sun_studio?)
    flags << "-KPIC"
  else
    flags << "-fPIC"
  end
  if with_apr_flags
    if language == :c
      flags << apr_cflags
      flags << apu_cflags
    else
      flags << apr_cxxflags
      flags << apu_cxxflags
    end
  end
  if !apxs2.nil?
    apxs2_flags = %x#{apxs2} -q CFLAGS`.strip << " -I" << %x#{apxs2} -q INCLUDEDIR`.strip
    apxs2_flags.gsub!(/-O\d? /, '')

    if os_name =~ /solaris/
      if (language == :c && !cc_is_sun_studio?) || (language == :cxx && !cxx_is_sun_studio?)
        # Remove flags not supported by GCC
        # The big problem is Coolstack apxs includes a bunch of solaris -x directives.
        options = apxs2_flags.split
        options.reject! { |f| f =~ /^\-x/ }
        options.reject! { |f| f =~ /^\-Xa/ }
        options.reject! { |f| f =~ /^\-fast/ }
        options.reject! { |f| f =~ /^\-mt/ }
        options.reject! { |f| f =~ /^\-W2/ }
        apxs2_flags = options.join(' ')
        apxs2_flags.gsub!(/ ?-Qoption cg ?/, " ")
      end
    end

    if os_name == "linux" &&
       linux_distro_tags.include?(:redhat) &&
       apxs2 == "/usr/sbin/apxs" &&
       httpd_architecture_bits == 64
      # The Apache package in CentOS 5 x86_64 is broken.
      # 'apxs -q CFLAGS' contains directives for compiling
      # the module as 32-bit, even though httpd itself
      # is 64-bit. Fix this.
      apxs2_flags.gsub!('-m32 -march=i386 -mtune=generic', '')
    end

    apxs2_flags.strip!
    flags << apxs2_flags
  end
  if !httpd.nil? && os_name == "macosx"
    # The default Apache install on OS X is a universal binary.
    # Figure out which architectures it's compiled for and do the same
    # thing for mod_passenger. We use the 'file' utility to do this.
    #
    # Running 'file' on the Apache executable usually outputs something
    # like this:
    #
    #   /usr/sbin/httpd: Mach-O universal binary with 4 architectures
    #   /usr/sbin/httpd (for architecture ppc7400):     Mach-O executable ppc
    #   /usr/sbin/httpd (for architecture ppc64):       Mach-O 64-bit executable ppc64
    #   /usr/sbin/httpd (for architecture i386):        Mach-O executable i386
    #   /usr/sbin/httpd (for architecture x86_64):      Mach-O 64-bit executable x86_64
    #
    # But on some machines, it may output just:
    #
    #   /usr/sbin/httpd: Mach-O fat file with 4 architectures
    #
    # (http://code.google.com/p/phusion-passenger/issues/detail?id=236)
    output = %xfile "#{httpd}"`.strip
    if output =~ /Mach-O fat file/ && output !~ /for architecture/
      architectures = ["i386", "ppc", "x86_64", "ppc64"]
    else
      architectures = []
      output.split("\n").grep(/for architecture/).each do |line|
        line =~ /for architecture (.*?)\)/
        architectures << $1
      end
    end
    # The compiler may not support all architectures in the binary.
    # XCode 4 seems to have removed support for the PPC architecture
    # even though there are still plenty of Apache binaries around
    # containing PPC components.
    architectures.reject! do |arch|
      !compiler_supports_architecture?(arch)
    end
    architectures.map! do |arch|
      "-arch #{arch}"
    end
    flags << architectures.compact.join(' ')
  end
  return flags.compact.join(' ').strip
end
apache2_module_cflags(with_apr_flags = true) click to toggle source

Compiler and linker flags ################

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 551
def self.apache2_module_cflags(with_apr_flags = true)
  return apache2_module_c_or_cxxflags(:c, with_apr_flags)
end
apache2_module_cxx_ldflags() click to toggle source

Linker flags that are necessary for linking an Apache module. Already includes APR and APU linker flags.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 658
def self.apache2_module_cxx_ldflags
  flags = ""
  if !apxs2.nil?
    flags << %x#{apxs2} -q LDFLAGS`.strip
  end

  # We must include the cxxflags in the linker flags. On some multilib
  # Solaris systems, `apxs -q CFLAGS` outputs a flag that tells the compiler
  # which architecture to compile against, while `apxs -q LDFLAGS` doesn't.
  flags << " #{apache2_module_cxxflags} #{apr_cxx_ldflags} #{apu_cxx_ldflags}"

  if cxx_is_sun_studio?
    flags.gsub!("-fPIC", "-KPIC")
    flags << " -KPIC" if !flags.include?("-KPIC")
  else
    flags << " -fPIC" if !flags.include?("-fPIC")
  end

  flags.strip!
  flags
end
apache2_module_cxxflags(with_apr_flags = true) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 556
def self.apache2_module_cxxflags(with_apr_flags = true)
  return apache2_module_c_or_cxxflags(:cxx, with_apr_flags)
end
apache2_sbindir(options = {}) click to toggle source

The absolute path to the Apache 2 'sbin' directory, or nil if unknown.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 538
def self.apache2_sbindir(options = {})
  apxs2 = options[:apxs2] || self.apxs2
  if apxs2.nil?
    return nil
  else
    return %x#{apxs2} -q SBINDIR`.strip
  end
end
apache2ctl(options = {}) click to toggle source

The absolute path to the 'apachectl' or 'apache2ctl' binary, or nil if not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 63
def self.apache2ctl(options = {})
  return find_apache2_executable('apache2ctl', 'apachectl2', 'apachectl', options)
end
apache2ctl_V(options = nil) click to toggle source

Run `apache2ctl -V` and return its output, or nil on failure.

We used to run `httpd -V`, but on systems like Ubuntu it depends on various environment variables or directories, wich apache2ctl loads or initializes.

Because on some systems (mostly Ubuntu) `apache2ctl -V` attempts to parse and load the config file, this command can fail because of configuration file errors.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 112
def self.apache2ctl_V(options = nil)
  if options
    apache2ctl = options[:apache2ctl] || self.apache2ctl(options)
  else
    apache2ctl = self.apache2ctl
  end
  if os_name == "linux" &&
     linux_distro_tags.include?(:gentoo) &&
     apache2ctl == "/usr/sbin/apache2ctl"
    # On Gentoo, `apache2ctl -V` doesn't forward the command to `apache2 -V`,
    # but instead prints the OpenRC init system's version.
    # https://github.com/phusion/passenger/issues/1510
    if options
      httpd = options[:httpd] || self.httpd(options)
    else
      httpd = self.httpd
    end
    version_command = httpd
  else
    version_command = apache2ctl
  end

  if version_command
    create_temp_file("apache2ctl_V") do |filename, f|
      e_filename = Shellwords.escape(filename)
      output = %x#{version_command} -V 2>#{e_filename}`

      if $? && $?.exitstatus == 0
        stderr_text = File.open(filename, "rb") do |f2|
          f2.read
        end
        # This stderr message shows up on Ubuntu. We ignore it.
        stderr_text.sub!(/.*Could not reliably determine the server's fully qualified domain name.*\r?\n?/, "")
        # But we print the rest of stderr.
        STDERR.write(stderr_text)
        STDERR.flush

        output
      else
        nil
      end
    end
  else
    nil
  end
end
apr_c_ldflags() click to toggle source

The linker flags that are necessary for linking programs that use APR.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 692
def self.apr_c_ldflags
  determine_apr_c_info[1]
end
apr_cflags() click to toggle source

The C compiler flags that are necessary for programs that use APR.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 682
def self.apr_cflags
  determine_apr_c_info[0]
end
apr_config() click to toggle source

The absolute path to the 'apr-config' or 'apr-1-config' executable, or nil if not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 438
def self.apr_config
  if env_defined?('APR_CONFIG')
    return ENV['APR_CONFIG']
  elsif apxs2.nil?
    return nil
  else
    filename = %x#{apxs2} -q APR_CONFIG 2>/dev/null`.strip
    if filename.empty?
      apr_bindir = %x#{apxs2} -q APR_BINDIR 2>/dev/null`.strip
      if apr_bindir.empty?
        return nil
      else
        return select_executable(apr_bindir,
          "apr-1-config", "apr-config")
      end
    elsif File.exist?(filename)
      return filename
    else
      return nil
    end
  end
end
apr_config_needed_for_building_apache_modules?() click to toggle source

Returns whether it is necessary to use information outputted by 'apr-config' and 'apu-config' in order to compile an Apache module. When Apache is installed with –with-included-apr, the APR/APU headers are placed into the same directory as the Apache headers, and so 'apr-config' and 'apu-config' won't be necessary in that case.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 729
def self.apr_config_needed_for_building_apache_modules?
  return !try_compile("whether APR is needed for building Apache modules",
    :c, "#include <apr.h>\n", apache2_module_cflags(false))
end
apr_cxx_ldflags() click to toggle source

The linker flags that are necessary for linking C++ programs that use APR.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 697
def self.apr_cxx_ldflags
  determine_apr_cxx_info[1]
end
apr_cxxflags() click to toggle source

The C++ compiler flags that are necessary for programs that use APR.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 687
def self.apr_cxxflags
  determine_apr_c_info[0]
end
apu_c_ldflags() click to toggle source

The linker flags that are necessary for linking C programs that use APR-Util.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 712
def self.apu_c_ldflags
  determine_apu_c_info[1]
end
apu_cflags() click to toggle source

The C compiler flags that are necessary for programs that use APR-Util.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 702
def self.apu_cflags
  determine_apu_c_info[0]
end
apu_config() click to toggle source

The absolute path to the 'apu-config' or 'apu-1-config' executable, or nil if not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 464
def self.apu_config
  if env_defined?('APU_CONFIG')
    return ENV['APU_CONFIG']
  elsif apxs2.nil?
    return nil
  else
    filename = %x#{apxs2} -q APU_CONFIG 2>/dev/null`.strip
    if filename.empty?
      apu_bindir = %x#{apxs2} -q APU_BINDIR 2>/dev/null`.strip
      if apu_bindir.empty?
        return nil
      else
        return select_executable(apu_bindir,
          "apu-1-config", "apu-config")
      end
    elsif File.exist?(filename)
      return filename
    else
      return nil
    end
  end
end
apu_cxx_ldflags() click to toggle source

The linker flags that are necessary for linking C++ programs that use APR-Util.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 717
def self.apu_cxx_ldflags
  determine_apu_cxx_info[1]
end
apu_cxxflags() click to toggle source

The C++ compiler flags that are necessary for programs that use APR-Util.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 707
def self.apu_cxxflags
  determine_apu_cxx_info[0]
end
apxs2() click to toggle source

The absolute path to the 'apxs' or 'apxs2' executable, or nil if not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 47
def self.apxs2
  if env_defined?("APXS2")
    return ENV["APXS2"]
  end
  ['apxs2', 'apxs'].each do |name|
    command = find_command(name)
    if !command.nil?
      return command
    end
  end
  return nil
end
cache_dir() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 186
def self.cache_dir
  return @@cache_dir
end
cache_dir=(value) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 182
def self.cache_dir=(value)
  @@cache_dir = value
end
cc() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 144
def self.cc
  return string_env('CC', default_cc)
end
cc_is_clang?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 190
def self.cc_is_clang?
  %x#{cc} --version 2>&1` =~ /clang version/
end
cc_is_gcc?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 180
def self.cc_is_gcc?
  %x#{cc} -v 2>&1` =~ /gcc version/
end
cc_is_sun_studio?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 200
def self.cc_is_sun_studio?
  %x#{cc} -V 2>&1` =~ /Sun C/ || %x#{cc} -flags 2>&1` =~ /Sun C/
end
cc_supports_feliminate_unused_debug?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 407
def self.cc_supports_feliminate_unused_debug?
  return cc_or_cxx_supports_feliminate_unused_debug?(:c)
end
cc_supports_no_tls_direct_seg_refs_option?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 388
def self.cc_supports_no_tls_direct_seg_refs_option?
  return try_compile("Checking for C compiler '-mno-tls-direct-seg-refs' support",
    :c, '', '-mno-tls-direct-seg-refs')
end
cc_supports_visibility_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 339
def self.cc_supports_visibility_flag?
  return false if os_name =~ /aix/
  return try_compile("Checking for C compiler '-fvisibility' support",
    :c, '', '-fvisibility=hidden')
end
cc_supports_wno_attributes_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 353
def self.cc_supports_wno_attributes_flag?
  return try_compile_with_warning_flag(
    "Checking for C compiler '-Wno-attributes' support",
    :c, '', '-Wno-attributes')
end
cc_supports_wno_missing_field_initializers_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 367
def self.cc_supports_wno_missing_field_initializers_flag?
  return try_compile_with_warning_flag(
    "Checking for C compiler '-Wno-missing-field-initializers' support",
    :c, '', '-Wno-missing-field-initializers')
end
cc_visibility_flag_generates_warnings?() click to toggle source

Returns whether compiling C++ with -fvisibility=hidden might result in tons of useless warnings, like this: code.google.com/p/phusion-passenger/issues/detail?id=526 This appears to be a bug in older g++ versions: gcc.gnu.org/ml/gcc-patches/2006-07/msg00861.html Warnings should be suppressed with -Wno-attributes.

# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 423
def self.cc_visibility_flag_generates_warnings?
  if os_name =~ /linux/ && %x#{cc} -v 2>&1` =~ /gcc version (.*?)/
    return $1 <= "4.1.2"
  else
    return false
  end
end
clear_memoizations() click to toggle source

Clears all memoized values. However, the disk cache (if any is configured) is still used.

# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 230
def self.clear_memoizations
  class_variables.each do |name|
    if name.to_s =~ /^@@has_memoized_/
      class_variable_set(name, false)
    end
  end
end
compiler_supports_architecture?(arch) click to toggle source

Checks whether the compiler supports “-arch #{arch}”.

# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 334
def self.compiler_supports_architecture?(arch)
  return try_compile("Checking for C compiler '-arch' support",
    :c, '', "-arch #{arch}")
end
compiler_supports_wno_ambiguous_member_template?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 400
def self.compiler_supports_wno_ambiguous_member_template?
  try_compile_with_warning_flag(
    "Checking for C++ compiler '-Wno-ambiguous-member-template' support",
    :cxx, '', '-Wno-ambiguous-member-template')
end
cpu_architectures() click to toggle source

Returns a list of all CPU architecture names that the current machine CPU supports. If there are multiple such architectures then the first item in the result denotes that OS runtime's main/preferred architecture.

This function normalizes some names. For example x86 is always reported as “x86” regardless of whether the OS reports it as “i386” or “i686”. x86_64 is always reported as “x86_64” even if the OS reports it as “amd64”.

Please note that even if the CPU supports multiple architectures, the operating system might not. For example most x86 CPUs nowadays also support x86_64, but x86_64 Linux systems require various x86 compatibility libraries to be installed before x86 executables can be run. This function does not detect whether these compatibility libraries are installed. The only guarantee that you have is that the OS can run executables in the architecture denoted by the first item in the result.

For example, on x86_64 Linux this function can return [“x86_64”, “x86”]. This indicates that the CPU supports both of these architectures, and that the OS's main/preferred architecture is x86_64. Most executables on the system are thus be x86_64. It is guaranteed that the OS can run x86_64 executables, but not x86 executables per se.

Another example: on MacOS X this function can return either

“x86_64”, “x86”

or [“x86”, “x86_64”]. The former result indicates

OS X 10.6 (Snow Leopard) and beyond because starting from that version everything is 64-bit by default. The latter result indicates an OS X version older than 10.6.

# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 97
def self.cpu_architectures
  uname = uname_command
  raise "The 'uname' command cannot be found" if !uname
  if os_name == "macosx"
    arch = %x#{uname} -p`.strip
    if arch == "i386"
      # Macs have been x86 since around 2007. I think all of them come with
      # a recent enough Intel CPU that supports both x86 and x86_64, and I
      # think every OS X version has both the x86 and x86_64 runtime installed.
      major, minor, *rest = %xsw_vers -productVersion`.strip.split(".")
      major = major.to_i
      minor = minor.to_i
      if major >= 10 || (major == 10 && minor >= 6)
        # Since Snow Leopard x86_64 is the default.
        ["x86_64", "x86"]
      else
        # Before Snow Leopard x86 was the default.
        ["x86", "x86_64"]
      end
    else
      arch
    end
  else
    arch = %x#{uname} -p`.strip
    # On some systems 'uname -p' returns something like
    # 'Intel(R) Pentium(R) M processor 1400MHz' or
    # 'Intel(R)_Xeon(R)_CPU___________X7460__@_2.66GHz'.
    if arch == "unknown" || arch =~ / / || arch =~ /Hz$/
      arch = %x#{uname} -m`.strip
    end
    if arch =~ /^i.86$/
      arch = "x86"
    elsif arch == "amd64"
      arch = "x86_64"
    end

    if arch == "x86"
      # Most x86 operating systems nowadays are probably running on
      # a CPU that supports both x86 and x86_64, but we're not gonna
      # go through the trouble of checking that. The main architecture
      # is what we usually care about.
      ["x86"]
    elsif arch == "x86_64"
      # I don't think there's a single x86_64 CPU out there
      # that doesn't support x86 as well.
      ["x86_64", "x86"]
    else
      [arch]
    end
  end
end
curl_flags() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/curl.rb, line 29
def self.curl_flags
  result = %x(curl-config --cflags) 2>/dev/null`.strip
  if result.empty?
    return nil
  else
    version = %xcurl-config --vernum`.strip
    if version >= '070c01'
      # Curl >= 7.12.1 supports curl_easy_reset()
      result << " -DHAS_CURL_EASY_RESET"
    end
    return result
  end
end
curl_libs() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/curl.rb, line 44
def self.curl_libs
  result = %x(curl-config --libs) 2>/dev/null`.strip
  if result.empty?
    return nil
  else
    return result
  end
end
curl_supports_ssl?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/curl.rb, line 54
def self.curl_supports_ssl?
  features = %x(curl-config --feature) 2>/dev/null`
  return features =~ /SSL/
end
cxx() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 149
def self.cxx
  return string_env('CXX', default_cxx)
end
cxx_11_flag() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 454
def self.cxx_11_flag
  # C++11 support on FreeBSD 10.0 + Clang seems to be bugged.
  # http://llvm.org/bugs/show_bug.cgi?id=18310
  return nil if os_name =~ /freebsd/

  source = %Q{
    struct Foo {
      Foo(Foo &&f) { }
    };
  }
  if try_compile("Checking for C++ -std=gnu++11 compiler flag", :cxx, source, '-std=gnu++11')
    return "-std=gnu++11"
  elsif try_compile("Checking for C++ -std=c++11 compiler flag", :cxx, source, '-std=c++11')
    return "-std=c++11"
  else
    return nil
  end
end
cxx_binary_compatibility_id() click to toggle source

Returns an identifier string that describes the current platform's binary compatibility with regard to C/C++ binaries. Two systems with the same binary compatibility identifiers should be able to run the same C/C++ binaries.

The the string depends on the following factors:

  • The operating system name.

  • Operating system runtime identifier. This may include the kernel version, libc version, C++ ABI version, etc. Everything that is of interest for binary compatibility with regard to C/C++ binaries.

  • Operating system default runtime architecture. This is not the same as the CPU architecture; some CPUs support multiple architectures, e.g. Intel Core 2 Duo supports x86 and x86_64. Some operating systems actually support multiple runtime architectures: a lot of x86_64 Linux distributions also include 32-bit runtimes, and OS X Snow Leopard is x86_64 by default but all system libraries also support x86. This component identifies the architecture that is used when compiling a binary with the system's C++ compiler with its default options.

# File src/ruby_supportlib/phusion_passenger/platform_info/binary_compatibility.rb, line 110
def self.cxx_binary_compatibility_id
  if os_name == "macosx"
    # RUBY_PLATFORM gives us the kernel version, but we want
    # the OS X version.
    os_version_string = %xsw_vers -productVersion`.strip
    # sw_vers returns something like "10.6.2". We're only
    # interested in the first two digits (MAJOR.MINOR) since
    # tiny releases tend to be binary compatible with each
    # other.
    components = os_version_string.split(".")
    os_version = "#{components[0]}.#{components[1]}"
    os_runtime = os_version

    os_arch = cpu_architectures[0]
    if os_version >= "10.5" && os_arch =~ /^i.86$/
      # On Snow Leopard, 'uname -m' returns i386 but
      # we *know* that everything is x86_64 by default.
      os_arch = "x86_64"
    end
  else
    os_arch = cpu_architectures[0]
    os_runtime = nil
  end

  return [os_arch, os_name, os_runtime].compact.join("-")
end
cxx_is_clang?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 195
def self.cxx_is_clang?
  %x#{cxx} --version 2>&1` =~ /clang version/
end
cxx_is_gcc?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 185
def self.cxx_is_gcc?
  %x#{cxx} -v 2>&1` =~ /gcc version/
end
cxx_is_sun_studio?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 205
def self.cxx_is_sun_studio?
  %x#{cxx} -V 2>&1` =~ /Sun C/ || %x#{cxx} -flags 2>&1` =~ /Sun C/
end
cxx_supports_feliminate_unused_debug?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 412
def self.cxx_supports_feliminate_unused_debug?
  return cc_or_cxx_supports_feliminate_unused_debug?(:cxx)
end
cxx_supports_no_tls_direct_seg_refs_option?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 394
def self.cxx_supports_no_tls_direct_seg_refs_option?
  return try_compile("Checking for C++ compiler '-mno-tls-direct-seg-refs' support",
    :cxx, '', '-mno-tls-direct-seg-refs')
end
cxx_supports_visibility_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 346
def self.cxx_supports_visibility_flag?
  return false if os_name =~ /aix/
  return try_compile("Checking for C++ compiler '-fvisibility' support",
    :cxx, '', '-fvisibility=hidden')
end
cxx_supports_wno_attributes_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 360
def self.cxx_supports_wno_attributes_flag?
  return try_compile_with_warning_flag(
    "Checking for C++ compiler '-Wno-attributes' support",
    :cxx, '', '-Wno-attributes')
end
cxx_supports_wno_missing_field_initializers_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 374
def self.cxx_supports_wno_missing_field_initializers_flag?
  return try_compile_with_warning_flag(
    "Checking for C++ compiler '-Wno-missing-field-initializers' support",
    :cxx, '', '-Wno-missing-field-initializers')
end
cxx_supports_wno_unused_local_typedefs_flag?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 381
def self.cxx_supports_wno_unused_local_typedefs_flag?
  return try_compile_with_warning_flag(
    "Checking for C++ compiler '-Wno-unused-local-typedefs' support",
    :cxx, '', '-Wno-unused-local-typedefs')
end
cxx_visibility_flag_generates_warnings?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 432
def self.cxx_visibility_flag_generates_warnings?
  if os_name =~ /linux/ && %x#{cxx} -v 2>&1` =~ /gcc version (.*?)/
    return $1 <= "4.1.2"
  else
    return false
  end
end
debugging_cflags() click to toggle source

C compiler flags that should be passed in order to enable debugging information.

# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 502
def self.debugging_cflags
  # According to OpenBSD's pthreads man page, pthreads do not work
  # correctly when an app is compiled with -g. It recommends using
  # -ggdb instead.
  #
  # In any case we'll always want to use -ggdb for better GDB debugging.
  if cc_is_gcc?
    return '-ggdb'
  else
    return '-g'
  end
end
default_cc() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 154
def self.default_cc
  # On most platforms, we'll want to use the same compiler as what the rest
  # of the system uses, so that we generate compatible binaries. That's
  # most likely the 'cc' command. We used to use 'gcc' by default.
  #
  # See for example this issue with OS X Mavericks (10.9). They switched from
  # GCC to Clang as the default compiler. Since the Nginx by default uses 'cc'
  # as the compiler, we'll have to do that too. Otherwise we'll get C++ linker
  # errors because Nginx is compiled with Clang while Phusion Passenger is
  # compiled with GCC.
  # https://code.google.com/p/phusion-passenger/issues/detail?id=950
  if PlatformInfo.find_command('cc')
    return 'cc'
  else
    return 'gcc'
  end
end
default_cxx() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 172
def self.default_cxx
  if PlatformInfo.find_command('c++')
    return 'c++'
  else
    return 'g++'
  end
end
default_extra_cflags() click to toggle source

Extra compiler flags that should always be passed to the C compiler, last in the command string.

# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 47
def self.default_extra_cflags
  return default_extra_c_or_cxxflags(:cc)
end
default_extra_cxxflags() click to toggle source

Extra compiler flags that should always be passed to the C++ compiler, last in the command string.

# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 54
def self.default_extra_cxxflags
  return default_extra_c_or_cxxflags(:cxx)
end
dmalloc_ldflags() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 515
def self.dmalloc_ldflags
  if !ENV['DMALLOC_LIBS'].to_s.empty?
    return ENV['DMALLOC_LIBS']
  end
  if os_name == "macosx"
    ['/opt/local', '/usr/local', '/usr'].each do |prefix|
      filename = "#{prefix}/lib/libdmallocthcxx.a"
      if File.exist?(filename)
        return filename
      end
    end
    return nil
  else
    return "-ldmallocthcxx"
  end
end
electric_fence_ldflags() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 533
def self.electric_fence_ldflags
  if os_name == "macosx"
    ['/opt/local', '/usr/local', '/usr'].each do |prefix|
      filename = "#{prefix}/lib/libefence.a"
      if File.exist?(filename)
        return filename
      end
    end
    return nil
  else
    return "-lefence"
  end
end
env_defined?(name) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 207
def self.env_defined?(name)
  return !ENV[name].nil? && !ENV[name].empty?
end
export_dynamic_flags() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 548
def self.export_dynamic_flags
  if os_name == "linux"
    return '-rdynamic'
  else
    return nil
  end
end
find_all_commands(name) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 372
def self.find_all_commands(name)
  search_dirs = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
  search_dirs.concat(%w(/bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin))
  ["/opt/*/bin", "/opt/*/sbin", "/usr/local/*/bin", "/usr/local/*/sbin"].each do |glob|
    search_dirs.concat(Dir[glob])
  end

  # Solaris systems may have Apache installations in
  # /usr/apache2/2.2/bin/sparcv9/
  Dir["/usr/apache2/*/bin"].each do |bindir|
    search_dirs << bindir
    Dir["#{bindir}/*"].each do |binsubdir|
      if File.directory?(binsubdir)
        search_dirs << binsubdir
      end
    end
  end

  search_dirs.delete("")
  search_dirs.uniq!

  result = []
  search_dirs.each do |directory|
    path = File.join(directory, name)
    if !File.exist?(path)
      log "Looking for #{path}: not found"
    elsif !File.file?(path)
      log "Looking for #{path}: found, but is not a file"
    elsif !File.executable?(path)
      log "Looking for #{path}: found, but is not executable"
    else
      log "Looking for #{path}: found"
      result << path
    end
  end
  return result
end
find_apache2_executable(*possible_names) click to toggle source

Find an executable in the Apache 'bin' and 'sbin' directories. Returns nil if not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 490
def self.find_apache2_executable(*possible_names)
  if possible_names.last.is_a?(Hash)
    options = possible_names.pop
    options = nil if options.empty?
  end

  if options
    dirs = options[:dirs] || [apache2_bindir(options), apache2_sbindir(options)]
  else
    dirs = [apache2_bindir, apache2_sbindir]
  end

  dirs.each do |bindir|
    if bindir.nil?
      next
    end
    possible_names.each do |name|
      filename = "#{bindir}/#{name}"
      if !File.exist?(filename)
        log "Looking for #{filename}: not found"
      elsif !File.file?(filename)
        log "Looking for #{filename}: found, but is not a file"
      elsif !File.executable?(filename)
        log "Looking for #{filename}: found, but is not executable"
      else
        log "Looking for #{filename}: found"
        return filename
      end
    end
  end
  return nil
end
find_command(name, is_executable = true) click to toggle source

Check whether the specified command is in $PATH, and return its absolute filename. Returns nil if the command is not found.

This function exists because system('which') doesn't always behave correctly, for some weird reason.

When `is_executable` is true, this function checks whether there is an executable named `name` in $PATH. When false, it assumes that `name` is not an executable name but a command string (e.g. “ccache gcc”). It then infers the executable name (“ccache”) from the command string, and checks for that instead.

# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 349
def self.find_command(name, is_executable = true)
  name = name.to_s
  if !is_executable && name =~ / /
    name = name.sub(/ .*/, '')
  end
  if name =~ /^\//
    if File.executable?(name)
      return name
    else
      return nil
    end
  else
    ENV['PATH'].to_s.split(File::PATH_SEPARATOR).each do |directory|
      next if directory.empty?
      path = File.join(directory, name)
      if File.file?(path) && File.executable?(path)
        return path
      end
    end
    return nil
  end
end
find_header(header_name, language, flags = nil) click to toggle source

Looks for the given C or C++ header. This works by invoking the compiler and searching in the compiler's header search path. Returns its full filename, or true if this function knows that the header exists but can't find it (e.g. because the compiler cannot tell us what its header search path is). Returns nil if the header cannot be found.

# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 216
def self.find_header(header_name, language, flags = nil)
  extension = detect_language_extension(language)
  create_temp_file("passenger-compile-check.#{extension}") do |filename, f|
    source = %Q{
      #include <#{header_name}>
    }
    f.puts(source)
    f.close
    begin
      command = create_compiler_command(language,
        "-v -c '#{filename}' -o '#{filename}.o'",
        flags)
      if result = run_compiler("Checking for #{header_name}", command, filename, source, true)
        result[:output] =~ /^#include <...> search starts here:$(.+?)^End of search list\.$/m
        search_paths = $1.to_s.strip.split("\n").map{ |line| line.strip }
        search_paths.each do |dir|
          if File.file?("#{dir}/#{header_name}")
            return "#{dir}/#{header_name}"
          end
        end
        return true
      else
        return nil
      end
    ensure
      File.unlink("#{filename}.o") rescue nil
    end
  end
end
gem_command(options = {}) click to toggle source

Returns the correct 'gem' command for this Ruby interpreter. If `:sudo => true` is given, then the gem command is prefixed by a sudo command if filesystem permissions require this.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 161
def self.gem_command(options = {})
  command = ruby_tool_command('gem')
  if options[:sudo] && gem_install_requires_sudo?
    command = "#{ruby_sudo_command} #{command}"
  end
  return command
end
gem_install_requires_sudo?() click to toggle source

Returns whether running 'gem install' as the current user requires sudo.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 171
def self.gem_install_requires_sudo?
  %x#{gem_command} env` =~ /INSTALLATION DIRECTORY: (.+)/
  if install_dir = $1
    return !File.writable?(install_dir)
  else
    return nil
  end
end
gnu_make() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 562
def self.gnu_make
  if result = string_env('GMAKE')
    return result
  else
    result = find_command('gmake')
    if !result
      result = find_command('make')
      if result
        if %x#{result} --version 2>&1` =~ /GNU/
          return result
        else
          return nil
        end
      else
        return nil
      end
    else
      return result
    end
  end
end
has_accept4?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 492
def self.has_accept4?
  return try_compile("Checking for accept4()", :c, %Q{
    #define _GNU_SOURCE
    #include <sys/socket.h>
    static void *foo = accept4;
  })
end
has_alloca_h?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 486
def self.has_alloca_h?
  return try_compile("Checking for alloca.h",
    :c, '#include <alloca.h>')
end
has_math_library?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 480
def self.has_math_library?
  return try_link("Checking for -lmath support",
    :c, "int main() { return 0; }\n", '-lmath')
end
has_rt_library?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 474
def self.has_rt_library?
  return try_link("Checking for -lrt support",
    :c, "int main() { return 0; }\n", '-lrt')
end
httpd(options = {}) click to toggle source

The absolute path to the Apache binary (that is, 'httpd', 'httpd2', 'apache' or 'apache2'), or nil if not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 70
def self.httpd(options = {})
  apxs2 = options[:apxs2] || self.apxs2
  if env_defined?('HTTPD')
    return ENV['HTTPD']
  elsif apxs2.nil?
    ["apache2", "httpd2", "apache", "httpd"].each do |name|
      command = find_command(name)
      if !command.nil?
        return command
      end
    end
    return nil
  else
    return find_apache2_executable(%x#{apxs2} -q TARGET`.strip, options)
  end
end
httpd_actual_error_log(options = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 273
def self.httpd_actual_error_log(options = nil)
  if config_file = httpd_default_config_file(options)
    begin
      contents = File.open(config_file, "rb") { |f| f.read }
    rescue Errno::ENOENT
      log "#{config_file} does not exist"
      return nil
    rescue Errno::EACCES
      log "Unable to open #{config_file} for reading"
      return nil
    end
    # We don't want to match comments
    contents.gsub!(/^[ \t]*#.*/, '')
    if contents =~ /^[ \t]*ErrorLog[ \t]+(.+)[ \t]*$/i
      filename = unescape_apache_config_value($1, options)
      if filename && filename !~ /\A\//
        # Not an absolute path. Infer from root.
        if root = httpd_default_root(options)
          return "#{root}/#{filename}"
        else
          return nil
        end
      else
        return filename
      end
    elsif contents =~ /ErrorLog/i
      # The user apparently has ErrorLog set somewhere but
      # we can't parse it. The default error log location,
      # as reported by `apache2ctl -V`, may be wrong (it is on OS X).
      # So to be safe, let's assume that we don't know.
      log "Unable to parse ErrorLog directive in Apache configuration file"
      return nil
    else
      log "No ErrorLog directive in Apache configuration file"
      return httpd_default_error_log(options)
    end
  else
    return nil
  end
end
httpd_architecture_bits(options = nil) click to toggle source

The Apache executable's architectural bits. Returns 32 or 64, or nil if unable to detect.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 162
def self.httpd_architecture_bits(options = nil)
  if options
    info = apache2ctl_V(options)
  else
    info = apache2ctl_V
  end
  if info
    info =~ %r{Architecture:(.*)}
    text = $1
    if text =~ /32/
      32
    elsif text =~ /64/
      64
    else
      nil
    end
  else
    nil
  end
end
httpd_default_config_file(options = nil) click to toggle source

The default Apache configuration file, or nil if Apache is not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 202
def self.httpd_default_config_file(options = nil)
  if options
    info = apache2ctl_V(options)
  else
    info = apache2ctl_V
  end
  if info
    info =~ /-D SERVER_CONFIG_FILE="(.+)"$/
    filename = $1
    if filename =~ /\A\//
      return filename
    else
      # Not an absolute path. Infer from default root.
      if root = httpd_default_root(options)
        return "#{root}/#{filename}"
      else
        return nil
      end
    end
  else
    return nil
  end
end
httpd_default_error_log(options = nil) click to toggle source

The default Apache error log's filename, as it is compiled into the Apache main executable. This may not be the actual error log that is used. The actual error log depends on the configuration file.

Returns nil if Apache is not detected, or if the default error log filename cannot be detected.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 253
def self.httpd_default_error_log(options = nil)
  if info = apache2ctl_V(options)
    info =~ /-D DEFAULT_ERRORLOG="(.+)"$/
    filename = $1
    if filename =~ /\A\//
      return filename
    else
      # Not an absolute path. Infer from default root.
      if root = httpd_default_root(options)
        return "#{root}/#{filename}"
      else
        return nil
      end
    end
  else
    return nil
  end
end
httpd_default_root(options = nil) click to toggle source

The default Apache root directory, as specified by its compilation parameters. This may be different from the value of the ServerRoot directive.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 186
def self.httpd_default_root(options = nil)
  if options
    info = apache2ctl_V(options)
  else
    info = apache2ctl_V
  end
  if info
    info =~ / -D HTTPD_ROOT="(.+)"$/
    return $1
  else
    return nil
  end
end
httpd_envvars_file(options = nil) click to toggle source

The location of the Apache envvars file, which exists on some systems such as Ubuntu. Returns nil if Apache is not found or if the envvars file is not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 317
def self.httpd_envvars_file(options = nil)
  if options
    httpd = options[:httpd] || self.httpd(options)
  else
    httpd = self.httpd
  end

  httpd_dir = File.dirname(httpd)
  if httpd_dir == "/usr/bin" || httpd_dir == "/usr/sbin"
    if File.exist?("/etc/apache2/envvars")
      return "/etc/apache2/envvars"
    elsif File.exist?("/etc/httpd/envvars")
      return "/etc/httpd/envvars"
    end
  end

  conf_dir = File.expand_path(File.dirname(httpd) + "/../conf")
  if File.exist?("#{conf_dir}/envvars")
    return "#{conf_dir}/envvars"
  end

  return nil
end
httpd_included_config_files(config_file, options = nil) click to toggle source

Given an Apache config file, returns the a hash with the following elements:

* `:files` - An array containing `config_file`, as well as all config files
             included from that config file, including recursively included
             ones. Only filenames that actually exist are put here.
* `:unreadable_files` - All config files that this function was unable
                        to read.
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 234
def self.httpd_included_config_files(config_file, options = nil)
  state = {
    :files => { config_file => true },
    :unreadable_files => [],
    :root => httpd_default_root(options)
  }
  scan_for_included_apache2_config_files(config_file, state, options)
  return {
    :files => state[:files].keys,
    :unreadable_files => state[:unreadable_files]
  }
end
httpd_infer_envvar(varname, options = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 341
def self.httpd_infer_envvar(varname, options = nil)
  if envfile = httpd_envvars_file(options)
    result = %x. '#{envfile}' && echo $#{varname}`.strip
    if $? && $?.exitstatus == 0
      return result
    else
      return nil
    end
  else
    return nil
  end
end
httpd_mods_available_directory(options = nil) click to toggle source

Returns the path to the Apache `mods-available` subdirectory, or nil if it's not supported by this Apache.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 356
def self.httpd_mods_available_directory(options = nil)
  config_file = httpd_default_config_file(options)
  return nil if !config_file

  # mods-available is supposed to be a Debian extension that only works
  # on the APT-installed Apache, so only return non-nil if we're
  # working against the APT-installed Apache.
  config_dir = File.dirname(config_file)
  if config_dir == "/etc/httpd" || config_dir == "/etc/apache2"
    if File.exist?("#{config_dir}/mods-available") &&
       File.exist?("#{config_dir}/mods-enabled")
      return "#{config_dir}/mods-available"
    else
      return nil
    end
  else
    return nil
  end
end
httpd_mods_enabled_directory(options = nil) click to toggle source

Returns the path to the Apache `mods-enabled` subdirectory, or nil if it's not supported by this Apache.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 379
def self.httpd_mods_enabled_directory(options = nil)
  config_file = httpd_default_config_file(options)
  return nil if !config_file

  # mods-enabled is supposed to be a Debian extension that only works
  # on the APT-installed Apache, so only return non-nil if we're
  # working against the APT-installed Apache.
  config_dir = File.dirname(config_file)
  if config_dir == "/etc/httpd" || config_dir == "/etc/apache2"
    if File.exist?("#{config_dir}/mods-available") &&
       File.exist?("#{config_dir}/mods-enabled")
      return "#{config_dir}/mods-enabled"
    else
      return nil
    end
  else
    return nil
  end
end
httpd_version(options = nil) click to toggle source

The Apache version, or nil if Apache is not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 89
def self.httpd_version(options = nil)
  if options
    httpd = options[:httpd] || self.httpd(options)
  else
    httpd = self.httpd
  end
  if httpd
    %x#{httpd} -v` =~ %r{Apache/([\d\.]+)}
    return $1
  else
    return nil
  end
end
in_rvm?() click to toggle source

Returns whether the current Ruby interpreter is managed by RVM.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 209
def self.in_rvm?
  bindir = rb_config['bindir']
  return bindir.include?('/.rvm/') || bindir.include?('/rvm/')
end
library_extension() click to toggle source

The current platform's shared library extension ('so' on most Unices).

# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 46
def self.library_extension
  if os_name == "macosx"
    return "bundle"
  else
    return "so"
  end
end
linux_distro() click to toggle source

An identifier for the current Linux distribution. nil if the operating system is not Linux.

# File src/ruby_supportlib/phusion_passenger/platform_info/linux.rb, line 31
def self.linux_distro
  tags = linux_distro_tags
  if tags
    return tags.first
  else
    return nil
  end
end
linux_distro_tags() click to toggle source

Autodetects the current Linux distribution and return a number of identifier tags. The first tag identifies the distribution while the other tags indicate which distributions it is likely compatible with. Returns nil if the operating system is not Linux.

# File src/ruby_supportlib/phusion_passenger/platform_info/linux.rb, line 44
def self.linux_distro_tags
  if os_name != "linux"
    return nil
  end
  lsb_release = read_file("/etc/lsb-release")
  if lsb_release =~ /Ubuntu/
    return [:ubuntu, :debian]
  elsif File.exist?("/etc/debian_version")
    return [:debian]
  elsif File.exist?("/etc/redhat-release")
    redhat_release = read_file("/etc/redhat-release")
    if redhat_release =~ /CentOS/
      return [:centos, :redhat]
    elsif redhat_release =~ /Fedora/
      return [:fedora, :redhat]
    elsif redhat_release =~ /Mandriva/
      return [:mandriva, :redhat]
    else
      # On official RHEL distros, the content is in the form of
      # "Red Hat Enterprise Linux Server release 5.1 (Tikanga)"
      return [:rhel, :redhat]
    end
  elsif File.exist?("/etc/system-release")
    system_release = read_file("/etc/system-release")
    if system_release =~ /Amazon Linux/
      return [:amazon, :redhat]
    else
      return [:unknown]
    end
  elsif File.exist?("/etc/suse-release")
    return [:suse]
  elsif File.exist?("/etc/gentoo-release")
    return [:gentoo]
  else
    return [:unknown]
  end
  # TODO: Slackware
end
locate_ruby_tool(name) click to toggle source

Locates a Ruby tool, e.g. 'gem', 'rake', 'bundle', etc. Instead of naively looking in $PATH, this function uses a variety of search heuristics to find the tool that's really associated with the current Ruby interpreter. It should never locate a tool that's actually associated with a different Ruby interpreter. Returns nil when nothing's found.

This method only returns the path to the tool script. Running this script directly does not necessarily mean that it's run under the correct Ruby interpreter. You may have to prepend it with the Ruby command. Use `ruby_tool_command` if you want to get a command that you can execute.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 380
def self.locate_ruby_tool(name)
  result = locate_ruby_tool_by_basename(name)
  if !result
    exeext = rb_config['EXEEXT']
    exeext = nil if exeext.empty?
    if exeext
      result = locate_ruby_tool_by_basename("#{name}#{exeext}")
    end
    if !result
      result = locate_ruby_tool_by_basename(transform_according_to_ruby_exec_format(name))
    end
    if !result && exeext
      result = locate_ruby_tool_by_basename(transform_according_to_ruby_exec_format(name) + exeext)
    end
  end
  return result
end
log_implementation() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 202
def self.log_implementation
  return @@log_implementation
end
log_implementation=(impl) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 198
def self.log_implementation=(impl)
  @@log_implementation = impl
end
make() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 557
def self.make
  return string_env('MAKE', find_command('make'))
end
os_name() click to toggle source

Returns the operating system's name. This name is in lowercase and contains no spaces, and thus is suitable to be used in some kind of ID. It may contain a version number. Linux is always identified as “linux”. OS X is always identified as “macosx”. Identifiers for other operating systems may contain a version number, e.g. “freebsd10”.

# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 34
def self.os_name
  if rb_config['target_os'] =~ /darwin/ && (sw_vers = find_command('sw_vers'))
    return "macosx"
  elsif rb_config['target_os'] =~ /^linux-/
    return "linux"
  else
    return rb_config['target_os']
  end
end
passenger_needs_ruby_dev_header?() click to toggle source

Returns whether Phusion Passenger needs Ruby development headers to be available for the current Ruby implementation.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 153
def self.passenger_needs_ruby_dev_header?
  # Too much of a trouble for JRuby. We can do without it.
  return RUBY_ENGINE != "jruby"
end
portability_c_ldflags() click to toggle source

Extra flags that should always be passed to the C compiler when linking, to be included last in the command string.

# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 33
def self.portability_c_ldflags
  return portability_c_or_cxx_ldflags(:c)
end
portability_cxx_ldflags() click to toggle source

Extra flags that should always be passed to the C++ compiler when linking, to be included last in the command string.

# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 40
def self.portability_cxx_ldflags
  return portability_c_or_cxx_ldflags(:cxx)
end
rake() click to toggle source

Returns the absolute path to the Rake executable that belongs to the current Ruby interpreter. Returns nil if it doesn't exist.

The return value may not be the actual correct invocation for Rake. Use `rake_command` for that.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 187
def self.rake
  return locate_ruby_tool('rake')
end
rake_command() click to toggle source

Returns the correct command string for invoking the Rake executable that belongs to the current Ruby interpreter. Returns nil if Rake is not found.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 195
def self.rake_command
  ruby_tool_command('rake')
end
rb_config() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 330
def self.rb_config
  if defined?(::RbConfig)
    return ::RbConfig::CONFIG
  else
    return ::Config::CONFIG
  end
end
read_file(filename) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 220
def self.read_file(filename)
  return File.open(filename, "rb") do |f|
    f.read
  end
rescue
  return ""
end
requires_no_tls_direct_seg_refs?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 180
def self.requires_no_tls_direct_seg_refs?
  return File.exists?("/proc/xen/capabilities") && cpu_architectures[0] == "x86"
end
rspec() click to toggle source

Returns the absolute path to the RSpec runner program that belongs to the current Ruby interpreter. Returns nil if it doesn't exist.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 203
def self.rspec
  return locate_ruby_tool('rspec')
end
ruby_command() click to toggle source

Returns correct command for invoking the current Ruby interpreter. In case of RVM this function will return the path to the RVM wrapper script that executes the current Ruby interpreter in the currently active gem set.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 58
def self.ruby_command
  # Detect usage of gem-wrappers: https://github.com/rvm/gem-wrappers
  # This is currently used by RVM >= 1.25, although it's not exclusive to RVM.
  if GEM_HOME && File.exist?("#{GEM_HOME}/wrappers/ruby")
    return "#{GEM_HOME}/wrappers/ruby"
  end

  if in_rvm?
    # Detect old-school RVM wrapper script location.
    name = rvm_ruby_string
    dirs = rvm_paths
    if name && dirs
      dirs.each do |dir|
        filename = "#{dir}/wrappers/#{name}/ruby"
        if File.exist?(filename)
          contents = File.open(filename, 'rb') do |f|
            f.read
          end
          # Old wrapper scripts reference $HOME which causes
          # things to blow up when run by a different user.
          if contents.include?("$HOME")
            filename = nil
          end
        else
          filename = nil
        end
        if filename
          return filename
        end
      end

      # Correctness of these commands are confirmed by mpapis.
      # If we ever encounter a case for which this logic is not sufficient,
      # try mpapis' pseudo code:
      #
      #   rvm_update_prefix  = write_to rvm_path ? "" : "rvmsudo"
      #   rvm_gemhome_prefix  = write_to GEM_HOME ? "" : "rvmsudo"
      #   repair_command  = "#{rvm_update_prefix} rvm get stable && rvm reload && #{rvm_gemhome_prefix} rvm repair all"
      #   wrapper_command = "#{rvm_gemhome_prefix} rvm wrapper #{rvm_ruby_string} --no-prefix --all"
      case rvm_installation_mode
      when :single
        repair_command  = "rvm get stable && rvm reload && rvm repair all"
        wrapper_command = "rvm wrapper #{rvm_ruby_string} --no-prefix --all"
      when :multi
        repair_command  = "rvmsudo rvm get stable && rvm reload && rvmsudo rvm repair all"
        wrapper_command = "rvmsudo rvm wrapper #{rvm_ruby_string} --no-prefix --all"
      when :mixed
        repair_command  = "rvmsudo rvm get stable && rvm reload && rvm repair all"
        wrapper_command = "rvm wrapper #{rvm_ruby_string} --no-prefix --all"
      end

      STDERR.puts "Your RVM wrapper scripts are too old, or some " +
        "wrapper scripts are missing. Please update/regenerate " +
        "them first by running:\n\n" +
        "  #{repair_command}\n\n" +
        "If that doesn't seem to work, please run:\n\n" +
        "  #{wrapper_command}"
      exit 1
    else
      # Something's wrong with the user's RVM installation.
      # Raise an error so that the user knows this instead of
      # having things fail randomly later on.
      # 'name' is guaranteed to be non-nil because rvm_ruby_string
      # already raises an exception on error.
      STDERR.puts "Your RVM installation appears to be broken: the RVM " +
        "path cannot be found. Please fix your RVM installation " +
        "or contact the RVM developers for support."
      exit 1
    end
  else
    return ruby_executable
  end
end
ruby_executable() click to toggle source

Returns the full path to the current Ruby interpreter's executable file. This might not be the actual correct command to use for invoking the Ruby interpreter; use ::ruby_command instead.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 136
def self.ruby_executable
  @@ruby_executable ||=
    rb_config['bindir'] + '/' + rb_config['RUBY_INSTALL_NAME'] + rb_config['EXEEXT']
end
ruby_extension_binary_compatibility_id() click to toggle source

Returns a string that describes the current Ruby interpreter's extension binary compatibility. A Ruby extension compiled for a certain Ruby interpreter can also be loaded on a different Ruby interpreter with the same binary compatibility identifier.

The result depends on the following factors:

  • Ruby engine name.

  • Ruby extension version. This is not the same as the Ruby language version, which identifies language-level compatibility. This is rather about binary compatibility of extensions. MRI seems to break source compatibility between tiny releases, though patchlevel releases tend to be source and binary compatible.

  • Ruby extension architecture. This is not necessarily the same as the operating system runtime architecture or the CPU architecture. For example, in case of JRuby, the extension architecture is just “java” because all extensions target the Java platform; the architecture the JVM was compiled for has no effect on compatibility. On systems with universal binaries support there may be multiple architectures. In this case the architecture is “universal” because extensions must be able to support all of the Ruby executable's architectures.

  • The operating system for which the Ruby interpreter was compiled.

# File src/ruby_supportlib/phusion_passenger/platform_info/binary_compatibility.rb, line 59
def self.ruby_extension_binary_compatibility_id
  ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : "ruby"
  ruby_ext_version = RUBY_VERSION
  if RUBY_PLATFORM =~ /darwin/
    if RUBY_PLATFORM =~ /universal/
      ruby_arch = "universal"
    else
      # OS X <  10.8: something like:
      #   "/opt/ruby-enterprise/bin/ruby: Mach-O 64-bit executable x86_64"
      output = %xfile -L "#{ruby_executable}"`.strip
      ruby_arch = output.sub(/.* /, '')
      if ruby_arch == "executable"
        # OS X >= 10.8: something like:
        #   "/opt/ruby-enterprise/bin/ruby: Mach-O 64-bit executable"
        if output =~ /Mach-O 64-bit/
          ruby_arch = "x86_64"
        else
          raise "Cannot autodetect the Ruby interpreter's architecture"
        end
      end
    end
  elsif RUBY_PLATFORM == "java"
    ruby_arch = "java"
  else
    ruby_arch = cpu_architectures[0]
  end
  return "#{ruby_engine}-#{ruby_ext_version}-#{ruby_arch}-#{os_name}"
end
ruby_sudo_command() click to toggle source

Returns either 'sudo' or 'rvmsudo' depending on whether the current Ruby interpreter is managed by RVM.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 338
def self.ruby_sudo_command
  if in_rvm?
    return "rvmsudo"
  else
    return "sudo"
  end
end
ruby_sudo_shell_command(args = nil) click to toggle source

Returns a `sudo` or `rvmsudo` command that spawns a shell, depending on whether the current Ruby interpreter is managed by RVM.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 348
def self.ruby_sudo_shell_command(args = nil)
  if in_rvm?
    shell = ENV['SHELL'].to_s
    if shell.empty?
      begin
        user = Etc.getpwuid(0)
      rescue ArgumentError
        user = nil
      end
      shell = user.shell if user
      shell = "bash" if !shell || shell.empty?
    end
    result = "rvmsudo "
    result << "#{args} " if args
    result << shell
    return result
  else
    return "sudo -s #{args}".strip
  end
end
ruby_supports_fork?() click to toggle source

Returns whether the Ruby interpreter supports process forking.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 142
def self.ruby_supports_fork?
  # MRI >= 1.9.2's respond_to? returns false for methods
  # that are not implemented.
  return Process.respond_to?(:fork) &&
    RUBY_ENGINE != "jruby" &&
    RUBY_ENGINE != "macruby" &&
    rb_config['target_os'] !~ /mswin|windows|mingw/
end
ruby_tool_command(name) click to toggle source

Locates a Ruby tool command, e.g. 'gem', 'rake', 'bundle', etc. Instead of naively looking in $PATH, this function uses a variety of search heuristics to find the command that's really associated with the current Ruby interpreter. It should never locate a command that's actually associated with a different Ruby interpreter. Returns nil when nothing's found.

Unlike `locate_ruby_tool`, which only returns the path to the tool script, this method returns a full command that you can execute. The returned command guarantees that the tool is run under the correct Ruby interpreter.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 408
def self.ruby_tool_command(name)
  path = locate_ruby_tool(name)
  if path
    if is_ruby_program?(path)
      "#{ruby_command} #{path}"
    else
      # The found tool is a wrapper script, e.g. in RVM's ~/.rvm/wrappers.
      # In this case, don't include the Ruby command in the result.
      path
    end
  else
    nil
  end
end
rvm_installation_mode() click to toggle source

Returns the RVM installation mode: :single - RVM is installed in single-user mode. :multi - RVM is installed in multi-user mode. :mixed - RVM is in a mixed-mode installation. nil - The current Ruby interpreter is not using RVM.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 320
def self.rvm_installation_mode
  if in_rvm?
    if ENV['rvm_path'] =~ /\.rvm/
      return :single
    else
      if GEM_HOME =~ /\.rvm/
        return :mixed
      else
        return :multi
      end
    end
  else
    return nil
  end
end
rvm_paths() click to toggle source

If the current Ruby interpreter is managed by RVM, returns all directories in which RVM places its working files. This is usually ~/.rvm or /usr/local/rvm, but in mixed-mode installations there can be multiple such paths.

Otherwise returns nil.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 220
def self.rvm_paths
  if in_rvm?
    result = []
    [ENV['rvm_path'], "#{PhusionPassenger.home_dir}/.rvm", "/usr/local/rvm"].each do |path|
      next if path.nil?
      rubies_path = File.join(path, 'rubies')
      wrappers_path = File.join(path, 'wrappers')
      gems_path = File.join(path, 'gems')
      if File.directory?(path) && (File.directory?(rubies_path) ||
         File.directory?(wrappers_path) || File.directory?(gems_path))
        result << path
      end
    end
    if result.empty?
      # Failure to locate the RVM path is probably caused by the
      # user customizing $rvm_path. Older RVM versions don't
      # export $rvm_path, making us unable to detect its value.
      STDERR.puts "Unable to locate the RVM path. Your RVM installation " +
        "is probably too old. Please update it with " +
        "'rvm get head && rvm reload && rvm repair all'."
      exit 1
    else
      return result
    end
  else
    return nil
  end
end
rvm_ruby_string() click to toggle source

If the current Ruby interpreter is managed by RVM, returns the RVM name which identifies the current Ruby interpreter plus the currently active gemset, e.g. something like this: “ruby-1.9.2-p0@mygemset”

Returns nil otherwise.

# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 256
def self.rvm_ruby_string
  if in_rvm?
    # RVM used to export the necessary information through
    # environment variables, but doesn't always do that anymore
    # in the latest versions in order to fight env var pollution.
    # Scanning $LOAD_PATH seems to be the only way to obtain
    # the information.

    # Getting the RVM name of the Ruby interpreter ("ruby-1.9.2")
    # isn't so hard, we can extract it from the #ruby_executable
    # string. Getting the gemset name is a bit harder, so let's
    # try various strategies...

    # $GEM_HOME usually contains the gem set name.
    # It may be something like:
    #   /Users/hongli/.rvm/gems/ruby-1.9.3-p392
    # But also:
    #   /home/bitnami/.rvm/gems/ruby-1.9.3-p385-perf@njist325/ruby/1.9.1
    if GEM_HOME && GEM_HOME =~ %r{rvm/gems/(.+)}
      return $1.sub(/\/.*/, '')
    end

    # User might have explicitly set GEM_HOME to a custom directory,
    # or might have nuked $GEM_HOME. Extract info from $GEM_PATH.
    if GEM_PATH
      GEM_PATH.split(':').each do |gem_path|
        if gem_path =~ %r{rvm/gems/(.+)}
          return $1.sub(/\/.*/, '')
        end
      end
    end

    # That failed too. Try extracting info from from $LOAD_PATH.
    matching_path = $LOAD_PATH.find_all do |item|
      item.include?("rvm/gems/")
    end
    if matching_path && !matching_path.empty?
      subpath = matching_path.to_s.gsub(/^.*rvm\/gems\//, '')
      result = subpath.split('/').first
      return result if result
    end

    # On Ruby 1.9, $LOAD_PATH does not contain any gem paths until
    # at least one gem has been required so the above can fail.
    # We're out of options now, we can't detect the gem set.
    # Raise an exception so that the user knows what's going on
    # instead of having things fail in obscure ways later.
    STDERR.puts "Unable to autodetect the currently active RVM gem " +
      "set name. This could happen if you ran this program using 'sudo' " +
      "instead of 'rvmsudo'. When using RVM, you're always supposed to " +
      "use 'rvmsudo' instead of 'sudo!'.\n\n" +
      "Please try rerunning this program using 'rvmsudo'. If that " +
      "doesn't help, please contact this program's author for support."
    exit 1
  end
  return nil
end
string_env(name, default_value = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 211
def self.string_env(name, default_value = nil)
  value = ENV[name]
  if value.nil? || value.empty?
    return default_value
  else
    return value
  end
end
supports_lfence_instruction?() click to toggle source

Returns whether the OS's main CPU architecture supports the x86/x86_64 lfence instruction.

# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 167
def self.supports_lfence_instruction?
  arch = cpu_architectures[0]
  return arch == "x86_64" || (arch == "x86" &&
    try_compile_and_run("Checking for lfence instruction support", :c, %Q{
      int
      main() {
        __asm__ __volatile__ ("lfence" ::: "memory");
        return 0;
      }
    }))
end
supports_sfence_instruction?() click to toggle source

Returns whether the OS's main CPU architecture supports the x86/x86_64 sfence instruction.

# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 152
def self.supports_sfence_instruction?
  arch = cpu_architectures[0]
  return arch == "x86_64" || (arch == "x86" &&
    try_compile_and_run("Checking for sfence instruction support", :c, %Q{
      int
      main() {
        __asm__ __volatile__ ("sfence" ::: "memory");
        return 0;
      }
    }))
end
tmpdir() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 238
def self.tmpdir
  result = ENV['TMPDIR']
  if result && !result.empty?
    return result.sub(/\/+\Z/, '')
  else
    return '/tmp'
  end
end
tmpexedir() click to toggle source

Returns the directory in which test executables should be placed. The returned directory is guaranteed to be writable and guaranteed to not be mounted with the 'noexec' option. If no such directory can be found then it will raise a PlatformInfo::RuntimeError with an appropriate error message.

# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 253
def self.tmpexedir
  basename = "test-exe.#{Process.pid}.#{Thread.current.object_id}"
  attempts = []

  dir = tmpdir
  filename = "#{dir}/#{basename}"
  begin
    File.open(filename, 'w') do |f|
      f.puts("#!/bin/sh")
    end
    File.chmod(0700, filename)
    if system(filename)
      return dir
    else
      attempts << { :dir => dir,
        :error => "This directory's filesystem is mounted with the 'noexec' option." }
    end
  rescue Errno::ENOENT
    attempts << { :dir => dir, :error => "This directory doesn't exist." }
  rescue Errno::EACCES
    attempts << { :dir => dir, :error => "This program doesn't have permission to write to this directory." }
  rescue SystemCallError => e
    attempts << { :dir => dir, :error => e.message }
  ensure
    File.unlink(filename) rescue nil
  end

  dir = Dir.pwd
  filename = "#{dir}/#{basename}"
  begin
    File.open(filename, 'w') do |f|
      f.puts("#!/bin/sh")
    end
    File.chmod(0700, filename)
    if system(filename)
      return dir
    else
      attempts << { :dir => dir,
        :error => "This directory's filesystem is mounted with the 'noexec' option." }
    end
  rescue Errno::ENOENT
    attempts << { :dir => dir, :error => "This directory doesn't exist." }
  rescue Errno::EACCES
    attempts << { :dir => dir, :error => "This program doesn't have permission to write to this directory." }
  rescue SystemCallError => e
    attempts << { :dir => dir, :error => e.message }
  ensure
    File.unlink(filename) rescue nil
  end

  message = "ERROR: Cannot find suitable temporary directory\n" +
    "In order to run certain tests, this program " +
    "must be able to write temporary\n" +
    "executable files to some directory. However no such " +
    "directory can be found. \n" +
    "The following directories have been tried:\n\n"
  attempts.each do |attempt|
    message << " * #{attempt[:dir]}\n"
    message << "   #{attempt[:error]}\n"
  end
  message << "\nYou can solve this problem by telling this program what directory to write\n" <<
    "temporary executable files to, as follows:\n" <<
    "\n" <<
    "  Set the $TMPDIR environment variable to the desired directory's filename and\n" <<
    "  re-run this program.\n" <<
    "\n" <<
    "Notes:\n" <<
    "\n" <<
    " * If you're using 'sudo'/'rvmsudo', remember that 'sudo'/'rvmsudo' unsets all\n" <<
    "   environment variables, so you must set the environment variable *after*\n" <<
    "   having gained root privileges.\n" <<
    " * The directory you choose must writeable and must not be mounted with the\n" <<
    "   'noexec' option."
  raise RuntimeError, message
end
try_compile(description, language, source, flags = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 246
def self.try_compile(description, language, source, flags = nil)
  extension = detect_language_extension(language)
  create_temp_file("passenger-compile-check.#{extension}") do |filename, f|
    f.puts(source)
    f.close
    command = create_compiler_command(language,
      "-c '#{filename}' -o '#{filename}.o'",
      flags)
    return run_compiler(description, command, filename, source)
  end
end
try_compile_and_run(description, language, source, flags = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 307
def self.try_compile_and_run(description, language, source, flags = nil)
  extension = detect_language_extension(language)
  create_temp_file("passenger-run-check.#{extension}", tmpexedir) do |filename, f|
    f.puts(source)
    f.close
    command = create_compiler_command(language,
      "'#{filename}' -o '#{filename}.out'",
      flags, true)
    if run_compiler(description, command, filename, source)
      log("Running #{filename}.out")
      begin
        output = %x'#{filename}.out' 2>&1`
      rescue SystemCallError => e
        log("Command failed: #{e}")
        return false
      end
      status = $?.exitstatus
      log("Command exited with status #{status}. Output:\n--------------\n#{output}\n--------------")
      return status == 0
    else
      return false
    end
  end
end
try_compile_with_warning_flag(description, language, source, flags = nil) click to toggle source

Like ::try_compile, but designed for checking whether a warning flag is supported. Compilers sometimes do not error out upon encountering an unsupported warning flag, but merely print a warning. This method checks for that too.

# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 262
def self.try_compile_with_warning_flag(description, language, source, flags = nil)
  extension = detect_language_extension(language)
  result = nil
  create_temp_file("passenger-compile-check.#{extension}") do |filename, f|
    f.puts(source)
    f.close
    command = create_compiler_command(language,
      "-c '#{filename}' -o '#{filename}.o'",
      flags)
    result = run_compiler(description, command, filename, source, true)
    result = result && result[:result] && result[:output] !~ /unknown warning option/i
  end
  return false if !result

  # For some reason, GCC does not complain about a warning flag
  # not being supported unless the source contains another error. So we
  # check for this.
  create_temp_file("passenger-compile-check.#{extension}") do |filename, f|
    source = %Q{
      void foo() {
        return error;
      }
    }
    f.puts(source)
    f.close
    command = create_compiler_command(language,
      "-c '#{filename}' -o '#{filename}.o'",
      flags)
    result = run_compiler("#{description} (really)", command, filename, source, :always)
  end
  result && !result[:output].include?(flags)
end
uname_command() click to toggle source

Returns the `uname` command, or nil if `uname` cannot be found. In addition to looking for `uname` in `PATH`, this method also looks for `uname` in /bin and /usr/bin, just in case the user didn't configure its PATH properly.

# File src/ruby_supportlib/phusion_passenger/platform_info/operating_system.rb, line 58
def self.uname_command
  if result = find_command("uname")
    result
  elsif File.exist?("/bin/uname")
    return "/bin/uname"
  elsif File.exist?("/usr/bin/uname")
    return "/usr/bin/uname"
  else
    return nil
  end
end
verbose=(val) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 190
def self.verbose=(val)
  @@verbose = val
end
verbose?() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 194
def self.verbose?
  return @@verbose
end
xcode_select_version() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 585
def self.xcode_select_version
  if find_command('xcode-select')
    %xxcode-select --version` =~ /version (.+)\./
    return $1
  else
    return nil
  end
end
zlib_flags() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/zlib.rb, line 29
def self.zlib_flags
  return nil
end
zlib_libs() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/zlib.rb, line 33
def self.zlib_libs
  return '-lz'
end

Private Class Methods

cc_or_cxx_supports_feliminate_unused_debug?(language) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 124
def self.cc_or_cxx_supports_feliminate_unused_debug?(language)
  ext = detect_language_extension(language)
  compiler_type_name = detect_compiler_type_name(language)
  create_temp_file("passenger-compile-check.#{ext}") do |filename, f|
    f.close
    begin
      command = create_compiler_command(language,
        "-c '#{filename}' -o '#{filename}.o'",
        '-feliminate-unused-debug-symbols -feliminate-unused-debug-types')
      result = run_compiler("Checking for #{compiler_type_name} compiler '-feliminate-unused-debug-{symbols,types}' support",
        command, filename, '', true)
      return result && result[:output].empty?
    ensure
      File.unlink("#{filename}.o") rescue nil
    end
  end
end
check_hash_map(flags) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 74
def self.check_hash_map(flags)
  hash_namespace = nil
  ok = false
  ['__gnu_cxx', '', 'std', 'stdext'].each do |namespace|
    ['hash_map', 'ext/hash_map'].each do |hash_map_header|
      ok = try_compile("Checking for #{hash_map_header}", :cxx, %Q{
        #include <#{hash_map_header}>
        int
        main() {
          #{namespace}::hash_map<int, int> m;
          return 0;
        }
      })
      if ok
        hash_namespace = namespace
        flags << "-DHASH_NAMESPACE=\"#{namespace}\""
        flags << "-DHASH_MAP_HEADER=\"<#{hash_map_header}>\""
        flags << "-DHASH_MAP_CLASS=\"hash_map\""
        break
      end
    end
    break if ok
  end
  ['ext/hash_fun.h', 'functional', 'tr1/functional',
   'ext/stl_hash_fun.h', 'hash_fun.h', 'stl_hash_fun.h',
   'stl/_hash_fun.h'].each do |hash_function_header|
    ok = try_compile("Checking for #{hash_function_header}", :cxx, %Q{
      #include <#{hash_function_header}>
      int
      main() {
        #{hash_namespace}::hash<int>()(5);
        return 0;
      }
    })
    if ok
      flags << "-DHASH_FUN_H=\"<#{hash_function_header}>\""
      break
    end
  end
end
check_unordered_map(flags, class_name, header_name, macro_name) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 60
def self.check_unordered_map(flags, class_name, header_name, macro_name)
  ok = try_compile("Checking for unordered_map", :cxx, %Q{
    #include <#{header_name}>
    int
    main() {
      #{class_name}<int, int> m;
      return 0;
    }
  })
  flags << "-D#{macro_name}" if ok
  return ok
end
create_compiler_command(language, flags1, flags2, link = false) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 55
def self.create_compiler_command(language, flags1, flags2, link = false)
  case language
  when :c
    result  = [cc, link ? ENV['EXTRA_PRE_LDFLAGS'] : nil,
      ENV['EXTRA_PRE_CFLAGS'], flags1, flags2, ENV['EXTRA_CFLAGS'],
      ENV['EXTRA_LDFLAGS']]
  when :cxx
    result  = [cxx, link ? ENV['EXTRA_PRE_LDFLAGS'] : nil,
      ENV['EXTRA_PRE_CXXFLAGS'], flags1, flags2, ENV['EXTRA_CXXFLAGS'],
      ENV['EXTRA_LDFLAGS']]
  else
    raise ArgumentError, "Unsupported language #{language.inspect}"
  end
  return result.compact.join(" ").strip
end
create_temp_file(name, dir = tmpdir) { |filename, f| ... } click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 153
def self.create_temp_file(name, dir = tmpdir)
  # This function is mostly used for compiling C programs to autodetect
  # system properties. We create a secure temp subdirectory to prevent
  # TOCTU attacks, especially because we don't know how the compiler
  # handles this.
  PhusionPassenger::Utils.mktmpdir("passenger.", dir) do |subdir|
    filename = "#{subdir}/#{name}"
    f = File.open(filename, "w")
    begin
      yield(filename, f)
    ensure
      f.close if !f.closed?
    end
  end
end
default_extra_c_or_cxxflags(cc_or_cxx) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 116
def self.default_extra_c_or_cxxflags(cc_or_cxx)
  flags = ["-D_REENTRANT", "-I/usr/local/include"]

  if !send("#{cc_or_cxx}_is_sun_studio?")
    flags << "-Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wpointer-arith -Wwrite-strings -Wno-long-long"
    if send("#{cc_or_cxx}_supports_wno_missing_field_initializers_flag?")
      flags << "-Wno-missing-field-initializers"
    end
    if requires_no_tls_direct_seg_refs? && send("#{cc_or_cxx}_supports_no_tls_direct_seg_refs_option?")
      flags << "-mno-tls-direct-seg-refs"
    end
    # Work around Clang warnings in ev++.h.
    if send("#{cc_or_cxx}_is_clang?")
      flags << "-Wno-ambiguous-member-template"
    end
  end

  if !send("#{cc_or_cxx}_is_sun_studio?")
    if send("#{cc_or_cxx}_supports_feliminate_unused_debug?")
      flags << "-feliminate-unused-debug-symbols -feliminate-unused-debug-types"
    end
    if send("#{cc_or_cxx}_supports_visibility_flag?")
      flags << "-fvisibility=hidden -DVISIBILITY_ATTRIBUTE_SUPPORTED"
      if send("#{cc_or_cxx}_visibility_flag_generates_warnings?") &&
         send("#{cc_or_cxx}_supports_wno_attributes_flag?")
        flags << "-Wno-attributes"
      end
    end
  end

  flags << debugging_cflags
  flags << '-DHAS_ALLOCA_H' if has_alloca_h?
  flags << '-DHAVE_ACCEPT4' if has_accept4?
  flags << '-DHAS_SFENCE' if supports_sfence_instruction?
  flags << '-DHAS_LFENCE' if supports_lfence_instruction?
  flags << "-DPASSENGER_DEBUG -DBOOST_DISABLE_ASSERTS"

  if cc_or_cxx == :cxx
    flags << cxx_11_flag if cxx_11_flag

    if cxx_supports_wno_unused_local_typedefs_flag?
      # Avoids some compilaton warnings with Boost on Ubuntu 14.04.
      flags << "-Wno-unused-local-typedefs"
    end

    # There are too many implementations of of the hash map!
    # Figure out the right one.
    check_unordered_map(flags, "std::unordered_map", "unordered_map", "HAS_UNORDERED_MAP") ||
      check_unordered_map(flags, "std::tr1::unordered_map", "unordered_map", "HAS_TR1_UNORDERED_MAP") ||
      check_hash_map(flags)
  end

  if os_name =~ /solaris/
    if send("#{cc_or_cxx}_is_sun_studio?")
      flags << '-mt'
    else
      flags << '-pthreads'
    end
    if os_name =~ /solaris2\.11/
      # skip the _XOPEN_SOURCE and _XPG4_2 definitions in later versions of Solaris / OpenIndiana
      flags << '-D__EXTENSIONS__ -D__SOLARIS__ -D_FILE_OFFSET_BITS=64'
    else
      flags << '-D_XOPEN_SOURCE=500 -D_XPG4_2 -D__EXTENSIONS__ -D__SOLARIS__ -D_FILE_OFFSET_BITS=64'
      flags << '-D__SOLARIS9__ -DBOOST__STDC_CONSTANT_MACROS_DEFINED' if os_name =~ /solaris2\.9/
    end
    flags << '-DBOOST_HAS_STDINT_H' unless os_name =~ /solaris2\.9/
    if send("#{cc_or_cxx}_is_sun_studio?")
      flags << '-xtarget=ultra' if RUBY_PLATFORM =~ /sparc/
    else
      flags << '-mcpu=ultrasparc' if RUBY_PLATFORM =~ /sparc/
    end
  elsif os_name =~ /openbsd/
    flags << '-DBOOST_HAS_STDINT_H -D_GLIBCPP__PTHREADS'
  elsif os_name =~ /aix/
    flags << '-pthread'
    flags << '-DOXT_DISABLE_BACKTRACES'
  elsif RUBY_PLATFORM =~ /(sparc-linux|arm-linux|^arm.*-linux|sh4-linux)/
    # http://code.google.com/p/phusion-passenger/issues/detail?id=200
    # http://groups.google.com/group/phusion-passenger/t/6b904a962ee28e5c
    # http://groups.google.com/group/phusion-passenger/browse_thread/thread/aad4bd9d8d200561
    flags << '-DBOOST_SP_USE_PTHREADS'
  end

  return flags.compact.map{ |str| str.strip }.join(" ").strip
end
detect_compiler_type_name(language) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 43
def self.detect_compiler_type_name(language)
  case language
  when :c
    return "C"
  when :cxx
    return "C++"
  else
    raise ArgumentError, "Unsupported language #{language.inspect}"
  end
end
detect_language_extension(language) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 31
def self.detect_language_extension(language)
  case language
  when :c
    return "c"
  when :cxx
    return "cpp"
  else
    raise ArgumentError, "Unsupported language #{language.inspect}"
  end
end
determine_apr_c_info() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 759
def self.determine_apr_c_info
  determine_apr_info(:c)
end
determine_apr_cxx_info() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 765
def self.determine_apr_cxx_info
  determine_apr_info(:cxx)
end
determine_apr_info(language) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 736
def self.determine_apr_info(language)
  if apr_config.nil?
    [nil, nil]
  else
    flags = %x#{apr_config} --cppflags --includes`.strip
    libs = %x#{apr_config} --link-ld`.strip
    flags.gsub!(/-O\d? /, '')
    if os_name =~ /solaris/
      if (language == :c && !cc_is_sun_studio?) || (language == :cxx && !cxx_is_sun_studio?)
        # Remove flags not supported by non-Sun Studio compilers
        flags = flags.split(/ +/).reject do |f|
          f =~ /^\-mt/
        end
        flags = flags.join(' ')
      end
    elsif os_name =~ /aix/
      libs << " -Wl,-G -Wl,-brtl"
    end
    [flags, libs]
  end
end
determine_apu_c_info() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 792
def self.determine_apu_c_info
  determine_apu_info(:c)
end
determine_apu_cxx_info() click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 798
def self.determine_apu_cxx_info
  determine_apu_info(:cxx)
end
determine_apu_info(language) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 771
def self.determine_apu_info(language)
  if apu_config.nil?
    [nil, nil]
  else
    flags = %x#{apu_config} --includes`.strip
    libs = %x#{apu_config} --link-ld`.strip
    flags.gsub!(/-O\d? /, '')
    if os_name =~ /solaris/
      if (language == :c && !cc_is_sun_studio?) || (language == :cxx && !cxx_is_sun_studio?)
        # Remove flags not supported by non-Sun Studio compilers
        flags = flags.split(/ +/).reject do |f|
          f =~ /^\-mt/
        end
        flags = flags.join(' ')
      end
    end
    [flags, libs]
  end
end
expand_apache2_glob(glob) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 838
def self.expand_apache2_glob(glob)
  if File.directory?(glob)
    glob = glob.sub(/\/*$/, '')
    result = Dir["#{glob}/**/*"]
  else
    result = []
    Dir[glob].each do |filename|
      if File.directory?(filename)
        result.concat(Dir["#{filename}/**/*"])
      else
        result << filename
      end
    end
  end
  result.reject! do |filename|
    File.directory?(filename)
  end
  return result
end
is_ruby_program?(filename) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 472
def self.is_ruby_program?(filename)
  File.open(filename, 'rb') do |f|
    return f.readline =~ /ruby/
  end
rescue EOFError
  return false
end
locate_ruby_tool_by_basename(name) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 424
def self.locate_ruby_tool_by_basename(name)
  if os_name == "macosx" &&
     ruby_command =~ %r(\A/System/Library/Frameworks/Ruby.framework/Versions/.*?/usr/bin/ruby\Z)
    # On OS X we must look for Ruby binaries in /usr/bin.
    # RubyGems puts executables (e.g. 'rake') in there, not in
    # /System/Libraries/(...)/bin.
    filename = "/usr/bin/#{name}"
  else
    filename = File.dirname(ruby_command) + "/#{name}"
  end

  if !File.file?(filename) || !File.executable?(filename)
    # RubyGems might put binaries in a directory other
    # than Ruby's bindir. Debian packaged RubyGems and
    # DebGem packaged RubyGems are the prime examples.
    begin
      require 'rubygems' unless defined?(Gem)
      filename = Gem.bindir + "/#{name}"
    rescue LoadError
      filename = nil
    end
  end

  if !filename || !File.file?(filename) || !File.executable?(filename)
    # Looks like it's not in the RubyGems bindir. Search in $PATH, but
    # be very careful about this because whatever we find might belong
    # to a different Ruby interpreter than the current one.
    ENV['PATH'].split(':').each do |dir|
      filename = "#{dir}/#{name}"
      if File.file?(filename) && File.executable?(filename)
        shebang = File.open(filename, 'rb') do |f|
          f.readline.strip
        end
        if shebang == "#!#{ruby_command}"
          # Looks good.
          break
        end
      end

      # Not found. Try next path.
      filename = nil
    end
  end

  filename
end
log(message) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 170
def self.log(message)
  if verbose?
    @@log_implementation.call(message)
  end
end
memoize(method, cache_to_disk = false, cache_time = 3600) click to toggle source

Turn the specified class method into a memoized one. If the given class method is called without arguments, then its result will be memoized, frozen, and returned upon subsequent calls without arguments. Calls with arguments are never memoized.

If cache_to_disk is true and a cache directory has been set with PlatformInfo.cache_dir= then result is cached to a file on disk, so that memoized results persist over multiple process runs. This cache file expires in cache_time seconds (1 hour by default) after it has been written.

def self.foo(max = 10)
  rand(max)
end
memoize :foo

foo        # => 3
foo        # => 3
foo(100)   # => 49
foo(100)   # => 26
foo        # => 3
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 67
def self.memoize(method, cache_to_disk = false, cache_time = 3600)
    # We use class_eval here because Ruby 1.8.5 doesn't support class_variable_get/set.
    metaclass = class << self; self; end
    metaclass.send(:alias_method, "_unmemoized_#{method}", method)
    variable_name = "@@memoized_#{method}".sub(/\?/, '')
    check_variable_name = "@@has_memoized_#{method}".sub(/\?/, '')
    eval(%Q{
      #{variable_name} = nil
      #{check_variable_name} = false
    })
    line = __LINE__ + 1
    source = %Q{
      def self.#{method}(*args)                                           # def self.httpd(*args)
        if args.empty?                                                    #   if args.empty?
          if !#{check_variable_name}                                      #     if !@@has_memoized_httpd
            if @@cache_dir                                                #       if @@cache_dir
              cache_file = File.join(@@cache_dir, "#{method}")            #         cache_file = File.join(@@cache_dir, "httpd")
            end                                                           #       end
            read_from_cache_file = false                                  #       read_from_cache_file = false
            if #{cache_to_disk} && cache_file && File.exist?(cache_file)  #       if #{cache_to_disk} && File.exist?(cache_file)
              cache_file_stat = File.stat(cache_file)                     #         cache_file_stat = File.stat(cache_file)
              read_from_cache_file =                                      #         read_from_cache_file =
                Time.now - cache_file_stat.mtime < #{cache_time}          #           Time.now - cache_file_stat.mtime < #{cache_time}
            end                                                           #       end
            if read_from_cache_file                                       #       if read_from_cache_file
              data = File.read(cache_file)                                #         data = File.read(cache_file)
              #{variable_name} = Marshal.load(data).freeze                #         @@memoized_httpd = Marshal.load(data).freeze
              #{check_variable_name} = true                               #         @@has_memoized_httpd = true
            else                                                          #       else
              #{variable_name} = _unmemoized_#{method}.freeze             #         @@memoized_httpd = _unmemoized_httpd.freeze
              #{check_variable_name} = true                               #         @@has_memoized_httpd = true
              if cache_file && #{cache_to_disk}                           #         if cache_file && #{cache_to_disk}
                begin                                                     #           begin
                  if !File.directory?(@@cache_dir)                        #             if !File.directory?(@@cache_dir)
                    Dir.mkdir(@@cache_dir)                                #               Dir.mkdir(@@cache_dir)
                  end                                                     #             end
                  File.open(cache_file, "wb") do |f|                      #             File.open(cache_file, "wb") do |f|
                    f.write(Marshal.dump(#{variable_name}))               #               f.write(Marshal.dump(@@memoized_httpd))
                  end                                                     #             end
                rescue Errno::EACCES                                      #           rescue Errno::EACCES
                  # Ignore permission error.                              #             # Ignore permission error.
                end                                                       #           end
              end                                                         #         end
            end                                                           #       end
          end                                                             #     end
          #{variable_name}                                                #     @@memoized_httpd
        else                                                              #   else
          _unmemoized_#{method}(*args)                                    #     _unmemoized_httpd(*args)
        end                                                               #   end
      end                                                                 # end
    }
    class_eval(source, __FILE__, line)
end
portability_c_or_cxx_ldflags(cc_or_cxx) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/cxx_portability.rb, line 203
def self.portability_c_or_cxx_ldflags(cc_or_cxx)
  result = ''
  result << cxx_11_flag if cc_or_cxx == :cxx && cxx_11_flag
  if os_name =~ /solaris/
    result << ' -lxnet -lsocket -lnsl -lpthread'
  else
    result << ' -lpthread'
  end
  result << ' -lrt' if has_rt_library?
  result << ' -lmath' if has_math_library?
  result.strip!
  return result
end
private_class_method(name) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 40
def self.private_class_method(name)
  metaclass = class << self; self; end
  metaclass.send(:private, name)
end
reindent(str, level) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 146
def self.reindent(str, level)
  str = unindent(str)
  str.gsub!(/^/, ' ' * level)
  return str
end
run_compiler(description, command, source_file, source, capture_output = false) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/compiler.rb, line 72
def self.run_compiler(description, command, source_file, source, capture_output = false)
  if verbose?
    message = "#{description}\n" <<
      "Running: #{command}\n"
    if source.strip.empty?
      message << "Source file is empty."
    else
      message << "Source file contains:\n" <<
        "-------------------------\n" <<
        unindent(source) <<
        "\n-------------------------"
    end
    log(message)
  end
  if capture_output
    begin
      output = %x#{command} 2>&1`
      result = $?.exitstatus == 0
    rescue SystemCallError => e
      result = nil
      exec_error_reason = e.message
    end
    log("Output:\n" <<
      "-------------------------\n" <<
      output.to_s <<
      "\n-------------------------")
  elsif verbose?
    result = system(command)
  else
    result = system("(#{command}) >/dev/null 2>/dev/null")
  end
  if result.nil?
    log("Command could not be executed! #{exec_error_reason}".strip)
    return false
  elsif result
    log("Check suceeded")
    if capture_output
      return { :result => true, :output => output }
    else
      return true
    end
  else
    log("Check failed with exit status #{$?.exitstatus}")
    if capture_output == :always
      return { :result => false, :output => output }
    else
      return false
    end
  end
end
scan_for_included_apache2_config_files(config_file, state, options = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 804
def self.scan_for_included_apache2_config_files(config_file, state, options = nil)
  begin
    config = File.open(config_file, "rb") do |f|
      f.read
    end
  rescue Errno::EACCES
    state[:unreadable_files] << config_file
    return
  end

  found_filenames = []

  config.scan(/^[ \t]*(Include(Optional)?|ServerRoot)[ \t]+(.+?)[ \t]*$/i) do |match|
    if match[0].downcase == "serverroot"
      new_root = unescape_apache_config_value(match[2], options)
      state[:root] = new_root if new_root
    else
      filename = unescape_apache_config_value(match[2], options)
      next if filename.nil? || filename.empty?
      if filename !~ /\A\//
        # Not an absolute path. Infer from root.
        filename = "#{state[:root]}/#{filename}"
      end
      expand_apache2_glob(filename).each do |filename2|
        if !state[:files].has_key?(filename2)
          state[:files][filename2] = true
          scan_for_included_apache2_config_files(filename2, state, options)
        end
      end
    end
  end
end
select_executable(dir, *possible_names) click to toggle source

Look in the directory dir and check whether there's an executable whose base name is equal to one of the elements in possible_names. If so, returns the full filename. If not, returns nil.

# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 125
def self.select_executable(dir, *possible_names)
  possible_names.each do |name|
    filename = "#{dir}/#{name}"
    if File.file?(filename) && File.executable?(filename)
      return filename
    end
  end
  return nil
end
transform_according_to_ruby_exec_format(name) click to toggle source

Deduce Ruby's –program-prefix and –program-suffix from its install name and transforms the given input name accordingly.

transform_according_to_ruby_exec_format("rake")    => "jrake", "rake1.8", etc
# File src/ruby_supportlib/phusion_passenger/platform_info/ruby.rb, line 485
def self.transform_according_to_ruby_exec_format(name)
  install_name = rb_config['RUBY_INSTALL_NAME']
  if install_name.include?('ruby')
    format = install_name.sub('ruby', '%s')
    return sprintf(format, name)
  else
    return name
  end
end
unescape_apache_config_value(value, options = nil) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 859
def self.unescape_apache_config_value(value, options = nil)
  if value =~ /^"(.*)"$/
    value = unescape_c_string($1)
  end
  if value.include?("${")
    log "Attempting to substitute environment variables in Apache config value #{value.inspect}..."
  end
  # The Apache config file supports environment variable
  # substitution. Ubuntu uses this extensively.
  value.gsub!(/\$\{(.+?)\}/) do |varname|
    if substitution = httpd_infer_envvar($1, options)
      log "Substituted \"#{varname}\" -> \"#{substitution}\""
      substitution
    else
      log "Cannot substitute \"#{varname}\""
      varname
    end
  end
  if value.include?("${")
    # We couldn't substitute everything.
    return nil
  else
    return value
  end
end
unescape_c_string(s) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info/apache.rb, line 886
def self.unescape_c_string(s)
  state = 0
  res = ''
  backslash = "\\"
  s.each_char do |c|
    case state
    when 0
      case c
      when backslash then state = 1
      else res << c
      end
    when 1
      case c
      when 'n' then res << "\n"; state = 0
      when 't' then res << "\t"; state = 0
      when backslash then res << backslash; state = 0
      else res << backslash; res << c; state = 0
      end
    end
  end
  return res
end
unindent(str) click to toggle source
# File src/ruby_supportlib/phusion_passenger/platform_info.rb, line 136
def self.unindent(str)
  str = str.dup
  str.gsub!(/\A([\s\t]*\n)+/, '')
  str.gsub!(/[\s\t\n]+\Z/, '')
  indent = str.split("\n").select{ |line| !line.strip.empty? }.map{ |line| line.index(/[^\s]/) }.compact.min || 0
  str.gsub!(/^[[:blank:]]{#{indent}}/, '')
  return str
end