summaryrefslogtreecommitdiff
path: root/test/dtrace/helper.rb
blob: 5a2ff796823bcdc61221cfdbce9878cb93967850 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# -*- coding: us-ascii -*-
# frozen_string_literal: false
require 'test/unit'
require 'tempfile'

if Process.euid == 0
  ok = true
elsif (sudo = ENV["SUDO"]) and !sudo.empty? and (`#{sudo} echo ok` rescue false)
  ok = true
else
  ok = false
end
ok &= (`dtrace -V` rescue false)
module DTrace
  class TestCase < Test::Unit::TestCase
    INCLUDE = File.expand_path('..', File.dirname(__FILE__))

    case RUBY_PLATFORM
    when /solaris/i
      # increase bufsize to 8m (default 4m on Solaris)
      DTRACE_CMD = %w[dtrace -b 8m]
    end

    DTRACE_CMD ||= %w[dtrace]

    case rubybin = EnvUtil.rubybin
    when /\/ruby-runner#{Regexp.quote(RbConfig::CONFIG["EXEEXT"])}\z/
      RUBYBIN = File.dirname(rubybin)+"/miniruby#{RbConfig::CONFIG["EXEEXT"]}"
    else
      RUBYBIN = rubybin
    end

    def trap_probe d_program, ruby_program
      d = Tempfile.new(%w'probe .d')
      d.write d_program
      d.flush

      rb = Tempfile.new(%w'probed .rb')
      rb.write ruby_program
      rb.flush

      d_path  = d.path
      rb_path = rb.path

      cmd = [*DTRACE_CMD, "-q", "-s", d_path, "-c", "#{RUBYBIN} -I#{INCLUDE} #{rb_path}"]
      if sudo = @@sudo
        [RbConfig::CONFIG["LIBPATHENV"], "RUBY", "RUBYOPT"].each do |name|
          if name and val = ENV[name]
            cmd.unshift("#{name}=#{val}")
          end
        end
        cmd.unshift(sudo)
      end
      probes = IO.popen(cmd, err: [:child, :out]) do |io|
        io.readlines
      end
      d.close(true)
      rb.close(true)
      yield(d_path, rb_path, probes)
    end
  end
end if ok

if ok
  DTrace::TestCase.class_variable_set(:@@sudo, sudo)
end