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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
require 'dl'
module LIBC
begin
LIB = DL.dlopen('libc.so.6')
rescue RuntimeError
LIB = DL.dlopen('libc.so.5')
end
SYM = {
:atoi => LIB['atoi', 'IS'],
:isdigit => LIB['isdigit', 'II'],
}
def atoi(str)
r,rs = SYM[:atoi].call(str)
return r
end
def isdigit(c)
r,rs = SYM[:isdigit].call(c)
return (r != 0)
end
end
module LIBC
SYM[:strcat] = LIB['strcat', 'SsS']
def strcat(str1,str2)
r,rs = SYM[:strcat].call(str1 + "\0#{str2}",str2)
return rs[0]
end
end
module LIBC
SYM[:fopen] = LIB['fopen', 'PSS']
SYM[:fclose] = LIB['fclose', '0P']
SYM[:fgetc] = LIB['fgetc', 'IP']
def fopen(filename, mode)
r,rs = SYM[:fopen].call(filename, mode)
return r
end
def fclose(ptr)
SYM[:fclose].call(ptr)
return nil
end
def fgetc(ptr)
r,rs = SYM[:fgetc].call(ptr)
return r
end
end
module LIBC
SYM[:strlen] = LIB['strlen', 'IP']
def strlen(str)
r,rs = SYM[:strlen].call(str)
return r
end
end
$cb1 = DL.set_callback('IPP', 0){|ptr1, ptr2|
str1 = ptr1.ptr.to_s
str2 = ptr2.ptr.to_s
str1 <=> str2
}
module LIBC
SYM[:qsort] = LIB['qsort', '0aIIP']
def qsort(ary, comp)
len = ary.length
r,rs = SYM[:qsort].call(ary, len, DL.sizeof('P'), comp)
return rs[0].to_a('S', len)
end
end
include LIBC
p atoi("10")
p isdigit(?1)
p isdigit(?a)
p strcat("a", "b")
p qsort(["a","c","b"],$cb1)
|