#!/usr/bin/env ruby
# -*- coding: binary -*-

#`brew install radare2` <-- older version :(
#`git clone https://github.com/radare/radare2 && cd radare2 && ./sys/install.sh`

def grab_offset(lib_file, function)
  offset_string = `r2 -2qQ -c 'aa; afl | grep #{function}' #{lib_file}`
  offset_string[0..9]
end

version = `sw_vers -productVersion`.strip
puts "      '#{version}' => {"
puts "        :dyld_stub_loader => '#{grab_offset("/usr/lib/system/libdyld.dylib", "dyld_stub_binder")}',"
puts "        :dlopen => '#{grab_offset("/usr/lib/system/libdyld.dylib", "sym._dlopen")}',"
puts "        :confstr => '#{grab_offset("/usr/lib/system/libsystem_c.dylib", "sym._confstr")}',"
puts "        :strlen => '#{grab_offset("/usr/lib/system/libsystem_c.dylib", "sym._strlen")}',"

strlen_disasm = `r2 -2qQ -c "iS | grep nl_symbol_ptr; s sym.imp.strlen; pd 1" /System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore`
#strlen_disasm = '''
#12 0x00b67000    16 0x00b66000    16 -rw- 12.__DATA.__nl_symbol_ptr
            #;-- imp.strlen:
            #0x00ace162      ff25808d0900   jmp qword [0x00b66ee8]      ; [0xb66ee8:8]=0xacf30e
#'''
got_offset = strlen_disasm.split(" ")[3].to_i(16)
strlen_got_entry = strlen_disasm.scan(/\[(\S+)\]/).first.first.to_i(16)
strlen_got_offset = (strlen_got_entry - got_offset).to_s(16)
puts "        :strlen_got => '0x#{strlen_got_offset}',"
puts "      },"

