Class: Cirron::Injector

Inherits:
Object
  • Object
show all
Defined in:
lib/injector.rb

Constant Summary collapse

VALID_ACTIONS =
[
  'error', 'retval', 'signal', 'syscall', 'delay_enter', 'delay_exit',
  'poke_enter', 'poke_exit', 'when'
].freeze

Instance Method Summary collapse

Constructor Details

#initializeInjector

Returns a new instance of Injector.



13
14
15
# File 'lib/injector.rb', line 13

def initialize
  @rules = []
end

Instance Method Details

#inject(syscall, action, value, when_condition = nil) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/injector.rb', line 17

def inject(syscall, action, value, when_condition = nil)
  unless VALID_ACTIONS.include?(action)
    raise ArgumentError, "Invalid action: #{action}. Valid actions are: #{VALID_ACTIONS.join(', ')}"
  end

  @rules << Rule.new(syscall, action, value, when_condition)
end

#run(timeout = 10) ⇒ Object



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
# File 'lib/injector.rb', line 25

def run(timeout = 10)
  trace_file = Tempfile.new('cirron_inject')
  trace_file_path = trace_file.path
  trace_file.close
  trace_file.unlink
  parent_pid = Process.pid

  cmd = ["strace", "--quiet=attach,exit", "-f", "-o", trace_file_path, "-p", parent_pid.to_s]

  @rules.each do |rule|
    inject_arg = "inject=#{rule.syscall}:#{rule.action}=#{rule.value}"
    inject_arg += ":when=#{rule.when}" if rule.when
    cmd.concat(["-e", inject_arg])
  end

  strace_proc = spawn(*cmd, :out => "/dev/null", :err => "/dev/null")

  begin
    deadline = Time.now + timeout
    until File.exist?(trace_file_path)
      if Time.now > deadline
        raise Timeout::Error, "Failed to start strace within #{timeout}s."
      end
      sleep 0.1
    end

    sleep 0.1

    yield if block_given?
  ensure
    Process.kill('INT', strace_proc) rescue nil
    Process.wait(strace_proc) rescue nil
  end
end