Skip to content

Instantly share code, notes, and snippets.

@rednaxelafx
Created May 14, 2013 15:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rednaxelafx/5577012 to your computer and use it in GitHub Desktop.
Save rednaxelafx/5577012 to your computer and use it in GitHub Desktop.
Ruby script to determine the architecture of a PE file. A port of the Perl version from http://stackoverflow.com/questions/495244/how-can-i-test-a-windows-dll-to-determine-if-it-is-32bit-or-64bit, courtesey of Paul Dixon
D:\temp>ruby petype.rb petype.rb
Not an executable
D:\temp>ruby petype.rb C:\Windows\system32\notepad.exe
amd64
D:\temp>ruby petype.rb C:\Windows\system32\jscript9.dll
amd64
D:\temp>ruby petype.rb C:\Windows\syswow64\jscript9.dll
i386
#!/usr/bin/env ruby
#
# port from http://stackoverflow.com/questions/495244/how-can-i-test-a-windows-dll-to-determine-if-it-is-32bit-or-64bit,
# courtesey of Paul Dixon
#
# usage: petype.rb <exefile>
exe = ARGV.first
File.open(exe, 'rb') do |file|
doshdr = file.read 68
magic, skip, offset = doshdr.unpack 'a2a58l'
unless magic == 'MZ'
puts 'Not an executable'
return
end
file.pos = offset
pehdr = file.read 6
sig, skip, arch = pehdr.unpack 'a2a2v'
unless sig == 'PE'
puts 'Not a PE file'
return
end
archname = case arch
when 0x014c; 'i386'
when 0x0200; 'IA-64'
when 0x8664; 'amd64'
end
puts archname
end
@edwinacunav
Copy link

Did you know you can get the very same results if you reduce the DOS header maximum position from 68 to 64?
Yeah, I just stumbled upon the same issue and work on the same kind of script after checking out some perl and python scripts. XD
It's quite easy to achieve the same with Ruby even if you need to verify multiple files' architectures. Just in case anybody wants to know this, add:

filenames = Dir['.exe'].sort + Dir['.dll'].sort
filenames.each {|fn| arch_of(fn) }

I assumed you'd name your method arch_of(filename) so...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment