Class: FFI::ExecutableMemoryPointer

Inherits:
Pointer
  • Object
show all
Defined in:
lib/ffi/executable_memory.rb

Defined Under Namespace

Modules: C

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Pointer

#read, #read_array_of, #write, #write_array_of

Constructor Details

#initialize(size) ⇒ ExecutableMemoryPointer

Returns a new instance of ExecutableMemoryPointer.



57
58
59
60
61
62
63
64
65
# File 'lib/ffi/executable_memory.rb', line 57

def initialize (size)
	address, size = self.class.alloc(size)

	ObjectSpace.define_finalizer self, self.class.finalizer(address, size)

	super(address)

	@size = size
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



55
56
57
# File 'lib/ffi/executable_memory.rb', line 55

def size
  @size
end

Class Method Details

.alloc(size) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/ffi/executable_memory.rb', line 35

def self.alloc (size)
	size = round_up(size)
	base = C.mmap(nil, size, 0x01 | 0x02 | 0x04, 0x02 | 0x20, -1, 0)
	# PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS

	return nil if base.address == -1

	return base, size
end

.finalizer(address, size) ⇒ Object



67
68
69
70
71
# File 'lib/ffi/executable_memory.rb', line 67

def self.finalizer (address, size)
	proc {
		self.free(address, size)
	}
end

.free(pointer, size) ⇒ Object



45
46
47
# File 'lib/ffi/executable_memory.rb', line 45

def self.free (pointer, size)
	C.munmap(address, size)
end

.from_string(string) ⇒ Object



49
50
51
52
53
# File 'lib/ffi/executable_memory.rb', line 49

def self.from_string (string)
	new(string.size).tap {|p|
		p.write_string(string)
	}
end

.round_up(base) ⇒ Object



28
29
30
31
32
33
# File 'lib/ffi/executable_memory.rb', line 28

def self.round_up (base)
	page_size = C.getpagesize
	over      = base % page_size

	base + (over > 0 ? page_size - over : 0)
end

Instance Method Details

#inspectObject



73
74
75
# File 'lib/ffi/executable_memory.rb', line 73

def inspect
	"#<FFI::ExecutableMemoryPointer address=0x#{'%x' % address} size=#{size}>"
end