Sha256: f69ae45ab2a46b20ad4141f7fb920e63181e7134ae2ba4db41779201de73d27d

Contents?: true

Size: 1.77 KB

Versions: 38

Compression:

Stored size: 1.77 KB

Contents

#!/usr/bin/env ruby

require 'tempfile'
require 'rex/file'
require 'rex/text'

module Rex
module Assembly

###
#
# This class uses nasm to assemble and disassemble stuff.
#
###
class Nasm

	@@nasm_path    = 'nasm'
	@@ndisasm_path = 'ndisasm'

	#
	# Ensures that the nasm environment is sane.
	#
	def self.check
		@@nasm_path =
			Rex::FileUtils.find_full_path('nasm')      ||
			Rex::FileUtils.find_full_path('nasm.exe')  ||
			Rex::FileUtils.find_full_path('nasmw.exe') ||
			raise(RuntimeError, "No nasm installation was found.")

		@@ndisasm_path =
			Rex::FileUtils.find_full_path('ndisasm')      ||
			Rex::FileUtils.find_full_path('ndisasm.exe')  ||
			Rex::FileUtils.find_full_path('ndisasmw.exe') ||
			raise(RuntimeError, "No ndisasm installation was found.")
	end

	#
	# Assembles the supplied assembly and returns the raw opcodes.
	#
	def self.assemble(assembly)
		check

		# Open the temporary file
		tmp = Tempfile.new('nasmXXXX')
		tmp.binmode
		
		tpath = tmp.path
		opath = tmp.path + '.out'

		# Write the assembly data to a file
		tmp.write("BITS 32\n" + assembly)
		tmp.flush()
		tmp.seek(0)

		# Run nasm
		if (system(@@nasm_path, '-f', 'bin', '-o', opath, tpath) == false)
			raise RuntimeError, "Assembler did not complete successfully: #{$?.exitstatus}"
		end

		# Read the assembled text
		rv = ::IO.read(opath)

		# Remove temporary files
		File.unlink(opath)
		tmp.close(true)

		rv
	end

	#
	# Disassembles the supplied raw opcodes
	#
	def self.disassemble(raw)
		check

		tmp = Tempfile.new('nasmout')
		tmp.binmode
		
		tfd = File.open(tmp.path, "wb")

		tfd.write(raw)
		tfd.flush()
		tfd.close

		p = ::IO.popen("\"#{@@ndisasm_path}\" -u \"#{tmp.path}\"")
		o = ''

		begin
			until p.eof?
				o += p.read
			end
		ensure
			p.close
		end

		tmp.close(true)

		o
	end

end

end
end

Version data entries

38 entries across 38 versions & 1 rubygems

Version Path
librex-0.0.63 lib/rex/assembly/nasm.rb
librex-0.0.54 lib/rex/assembly/nasm.rb
librex-0.0.53 lib/rex/assembly/nasm.rb
librex-0.0.52 lib/rex/assembly/nasm.rb
librex-0.0.51 lib/rex/assembly/nasm.rb
librex-0.0.50 lib/rex/assembly/nasm.rb
librex-0.0.49 lib/rex/assembly/nasm.rb
librex-0.0.48 lib/rex/assembly/nasm.rb
librex-0.0.47 lib/rex/assembly/nasm.rb
librex-0.0.46 lib/rex/assembly/nasm.rb
librex-0.0.44 lib/rex/assembly/nasm.rb
librex-0.0.43 lib/rex/assembly/nasm.rb
librex-0.0.42 lib/rex/assembly/nasm.rb
librex-0.0.41 lib/rex/assembly/nasm.rb
librex-0.0.40 lib/rex/assembly/nasm.rb
librex-0.0.39 lib/rex/assembly/nasm.rb
librex-0.0.38 lib/rex/assembly/nasm.rb
librex-0.0.37 lib/rex/assembly/nasm.rb
librex-0.0.36 lib/rex/assembly/nasm.rb
librex-0.0.35 lib/rex/assembly/nasm.rb