code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def encode(coff) opth = super(coff) DIRECTORIES[0, @numrva].each { |d| if d = coff.directory[d] d = d.dup d[0] = Expression[d[0], :-, coff.label_at(coff.encoded, 0)] if d[0].kind_of?(::String) else d = [0, 0] end opth << coff.encode_word(d[0]) << coff.encode_word(d[1]) } opth end
encodes an Optional header and the directories
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def set_default_values(coff) @signature ||= (coff.bitsize == 64 ? 'PE+' : 'PE') @link_ver_maj ||= 1 @link_ver_min ||= 0 @sect_align ||= 0x1000 align = lambda { |sz| EncodedData.align_size(sz, @sect_align) } @code_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_CODE' }.inject(0) { |sum, s| sum + align[s.virtsize] } @data_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_DATA' }.inject(0) { |sum, s| sum + align[s.virtsize] } @udata_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_UDATA' }.inject(0) { |sum, s| sum + align[s.virtsize] } @entrypoint = Expression[@entrypoint, :-, coff.label_at(coff.encoded, 0)] if entrypoint and not @entrypoint.kind_of?(::Integer) tmp = coff.sections.find { |s| s.characteristics.include? 'CONTAINS_CODE' } @base_of_code ||= (tmp ? Expression[coff.label_at(tmp.encoded, 0), :-, coff.label_at(coff.encoded, 0)] : 0) tmp = coff.sections.find { |s| s.characteristics.include? 'CONTAINS_DATA' } @base_of_data ||= (tmp ? Expression[coff.label_at(tmp.encoded, 0), :-, coff.label_at(coff.encoded, 0)] : 0) @file_align ||= 0x200 @os_ver_maj ||= 4 @subsys_maj ||= 4 @stack_reserve||= 0x100000 @stack_commit ||= 0x1000 @heap_reserve ||= 0x100000 @heap_commit ||= 0x1000 @numrva ||= DIRECTORIES.length super(coff) end
find good default values for optheader members, based on coff.sections
set_default_values
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def set_default_values(coff) @name ||= '' @virtsize ||= @encoded.virtsize @virtaddr ||= Expression[coff.label_at(@encoded, 0, 'sect_start'), :-, coff.label_at(coff.encoded, 0)] @rawsize ||= coff.new_label('sect_rawsize') @rawaddr ||= coff.new_label('sect_rawaddr') super(coff) end
find good default values for section header members, defines rawaddr/rawsize as new_label for later fixup
set_default_values
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode(coff, edata) edata['iat'] << EncodedData.new # edata['ilt'] = edata['iat'] label = lambda { |n| coff.label_at(edata[n], 0, n) } rva_end = lambda { |n| Expression[[label[n], :-, coff.label_at(coff.encoded, 0)], :+, edata[n].virtsize] } @libname_p = rva_end['nametable'] @ilt_p = rva_end['ilt'] @iat_p ||= Expression[coff.label_at(edata['iat'].last, 0, 'iat'), :-, coff.label_at(coff.encoded, 0)] edata['idata'] << super(coff) edata['nametable'] << @libname << 0 ord_mask = 1 << (coff.bitsize - 1) @imports.each { |i| edata['iat'].last.add_export i.target, edata['iat'].last.virtsize if i.target if i.ordinal ptr = coff.encode_xword(Expression[i.ordinal, :|, ord_mask]) else edata['nametable'].align 2 ptr = coff.encode_xword(rva_end['nametable']) edata['nametable'] << coff.encode_half(i.hint || 0) << i.name << 0 end edata['ilt'] << ptr edata['iat'].last << ptr } edata['ilt'] << coff.encode_xword(0) edata['iat'].last << coff.encode_xword(0) end
encode one import directory + iat + names in the edata hash received as arg
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_exports edata = @export.encode self # must include name tables (for forwarders) @directory['export_table'] = [label_at(edata, 0, 'export_table'), edata.virtsize] s = Section.new s.name = '.edata' s.encoded = edata s.characteristics = %w[MEM_READ] encode_append_section s end
encodes the export table as a new section, updates directory['export_table']
encode_exports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_imports idata, iat = ImportDirectory.encode(self, @imports) @directory['import_table'] = [label_at(idata, 0, 'idata'), idata.virtsize] s = Section.new s.name = '.idata' s.encoded = idata s.characteristics = %w[MEM_READ MEM_WRITE MEM_DISCARDABLE] encode_append_section s if @imports.first and @imports.first.iat_p.kind_of?(Integer) # ordiat = iat.sort_by { @import[x].iat_p } ordiat = @imports.zip(iat).sort_by { |id, it| id.iat_p.kind_of?(Integer) ? id.iat_p : 1<<65 }.map { |id, it| it } else ordiat = iat end @directory['iat'] = [label_at(ordiat.first, 0, 'iat'), Expression[label_at(ordiat.last, ordiat.last.virtsize, 'iat_end'), :-, label_at(ordiat.first, 0)]] if not ordiat.empty? iat_s = nil plt = Section.new plt.name = '.plt' plt.encoded = EncodedData.new plt.characteristics = %w[MEM_READ MEM_EXECUTE] @imports.zip(iat) { |id, it| if id.iat_p.kind_of?(Integer) and @sections.find { |s_| s_.virtaddr <= id.iat_p and s_.virtaddr + (s_.virtsize || s_.encoded.virtsize) > id.iat_p } id.iat = it # will be fixed up after encode_section else # XXX should not be mixed (for @directory['iat'][1]) if not iat_s iat_s = Section.new iat_s.name = '.iat' iat_s.encoded = EncodedData.new iat_s.characteristics = %w[MEM_READ MEM_WRITE] encode_append_section iat_s end iat_s.encoded << it end id.imports.each { |i| if i.thunk arch_encode_thunk(plt.encoded, i) end } } encode_append_section plt if not plt.encoded.empty? end
encodes the import tables as a new section, updates directory['import_table'] and directory['iat']
encode_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_relocs if @relocations.empty? rt = RelocationTable.new rt.base_addr = 0 rt.relocs = [] @relocations << rt end relocs = @relocations.inject(EncodedData.new) { |edata, rt_| edata << rt_.encode(self) } @directory['base_relocation_table'] = [label_at(relocs, 0, 'reloc_table'), relocs.virtsize] s = Section.new s.name = '.reloc' s.encoded = relocs s.characteristics = %w[MEM_READ MEM_DISCARDABLE] encode_append_section s end
encodes relocation tables in a new section .reloc, updates @directory['base_relocation_table']
encode_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def create_relocation_tables @relocations = [] # create a fake binding with all exports, to find only-image_base-dependant relocs targets # not foolproof, but works in standard cases startaddr = curaddr = label_at(@encoded, 0, 'coff_start') binding = {} @sections.each { |s| binding.update s.encoded.binding(curaddr) curaddr = Expression[curaddr, :+, s.encoded.virtsize] } # for each section.encoded, make as many RelocationTables as needed @sections.each { |s| # rt.base_addr temporarily holds the offset from section_start, and is fixed up to rva before '@reloc << rt' rt = RelocationTable.new s.encoded.reloc.each { |off, rel| # check that the relocation looks like "program_start + integer" when bound using the fake binding # XXX allow :i32 etc if rel.endianness == @endianness and [:u32, :a32, :u64, :a64].include?(rel.type) and rel.target.bind(binding).reduce.kind_of?(Expression) and Expression[rel.target, :-, startaddr].bind(binding).reduce.kind_of?(::Integer) # winner ! # build relocation r = RelocationTable::Relocation.new r.offset = off & 0xfff r.type = { :u32 => 'HIGHLOW', :u64 => 'DIR64', :a32 => 'HIGHLOW', :a64 => 'DIR64' }[rel.type] # check if we need to start a new relocation table if rt.base_addr and (rt.base_addr & ~0xfff) != (off & ~0xfff) rt.base_addr = Expression[[label_at(s.encoded, 0, 'sect_start'), :-, startaddr], :+, rt.base_addr] @relocations << rt rt = RelocationTable.new end # initialize reloc table base address if needed rt.base_addr ||= off & ~0xfff (rt.relocs ||= []) << r elsif $DEBUG and not rel.target.bind(binding).reduce.kind_of?(Integer) puts "W: COFF: Ignoring weird relocation #{rel.inspect} when building relocation tables" end } if rt and rt.relocs rt.base_addr = Expression[[label_at(s.encoded, 0, 'sect_start'), :-, startaddr], :+, rt.base_addr] @relocations << rt end } end
creates the @relocations from sections.encoded.reloc
create_relocation_tables
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def pre_encode_header(target='exe', want_relocs=true) target = {:bin => 'exe', :lib => 'dll', :obj => 'obj', 'sys' => 'kmod', 'drv' => 'kmod'}.fetch(target, target) @header.machine ||= case @cpu.shortname when 'x64'; 'AMD64' when 'ia32'; 'I386' end @optheader.signature ||= case @cpu.size when 32; 'PE' when 64; 'PE+' end @bitsize = (@optheader.signature == 'PE+' ? 64 : 32) # setup header flags tmp = %w[LINE_NUMS_STRIPPED LOCAL_SYMS_STRIPPED DEBUG_STRIPPED] + case target when 'exe'; %w[EXECUTABLE_IMAGE] when 'dll'; %w[EXECUTABLE_IMAGE DLL] when 'kmod'; %w[EXECUTABLE_IMAGE] when 'obj'; [] end if @cpu.size == 32 tmp << 'x32BIT_MACHINE' else tmp << 'LARGE_ADDRESS_AWARE' end tmp << 'RELOCS_STRIPPED' if not want_relocs @header.characteristics ||= tmp @optheader.subsystem ||= case target when 'exe', 'dll'; 'WINDOWS_GUI' when 'kmod'; 'NATIVE' end tmp = [] tmp << 'NX_COMPAT' tmp << 'DYNAMIC_BASE' if want_relocs @optheader.dll_characts ||= tmp end
initialize the header from target/cpu/etc, target in ['exe' 'dll' 'kmod' 'obj']
pre_encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def invalidate_header # set those values to nil, they will be # recomputed during encode_header [:code_size, :data_size, :udata_size, :base_of_code, :base_of_data, :sect_align, :file_align, :image_size, :headers_size, :checksum].each { |m| @optheader.send("#{m}=", nil) } [:num_sect, :ptr_sym, :num_sym, :size_opthdr].each { |m| @header.send("#{m}=", nil) } end
resets the values in the header that may have been modified by your script (eg section count, size, imagesize, etc) call this whenever you decode a file, modify it, and want to reencode it later
invalidate_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_header # encode section table, add CONTAINS_* flags from other characteristics flags s_table = EncodedData.new @sections.each { |s| if s.characteristics.kind_of? Array and s.characteristics.include? 'MEM_READ' if s.characteristics.include? 'MEM_EXECUTE' s.characteristics |= ['CONTAINS_CODE'] elsif s.encoded if s.encoded.rawsize == 0 s.characteristics |= ['CONTAINS_UDATA'] else s.characteristics |= ['CONTAINS_DATA'] end end end s.rawaddr = nil if s.rawaddr.kind_of?(::Integer) # XXX allow to force rawaddr ? s_table << s.encode(self) } # encode optional header @optheader.image_size ||= new_label('image_size') @optheader.image_base ||= label_at(@encoded, 0) @optheader.headers_size ||= new_label('headers_size') @optheader.checksum ||= new_label('checksum') @optheader.subsystem ||= 'WINDOWS_GUI' @optheader.numrva = nil opth = @optheader.encode(self) # encode header @header.machine ||= 'UNKNOWN' @header.num_sect ||= sections.length @header.time ||= Time.now.to_i & -255 @header.size_opthdr ||= opth.virtsize @encoded << @header.encode(self) << opth << s_table end
appends the header/optheader/directories/section table to @encoded
encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_sections_fixup if @optheader.headers_size.kind_of?(::String) @encoded.fixup! @optheader.headers_size => @encoded.virtsize @optheader.headers_size = @encoded.virtsize end @encoded.align @optheader.file_align baseaddr = @optheader.image_base.kind_of?(::Integer) ? @optheader.image_base : 0x400000 binding = @encoded.binding(baseaddr) curaddr = baseaddr + @optheader.headers_size @sections.each { |s| # align curaddr = EncodedData.align_size(curaddr, @optheader.sect_align) if s.rawaddr.kind_of?(::String) @encoded.fixup! s.rawaddr => @encoded.virtsize s.rawaddr = @encoded.virtsize end if s.virtaddr.kind_of?(::Integer) raise "E: COFF: cannot encode section #{s.name}: hardcoded address too short" if curaddr > baseaddr + s.virtaddr curaddr = baseaddr + s.virtaddr end binding.update s.encoded.binding(curaddr) curaddr += s.virtsize pre_sz = @encoded.virtsize @encoded << s.encoded[0, s.encoded.rawsize] @encoded.align @optheader.file_align if s.rawsize.kind_of?(::String) @encoded.fixup! s.rawsize => (@encoded.virtsize - pre_sz) s.rawsize = @encoded.virtsize - pre_sz end } # not aligned ? spec says it is, visual studio does not binding[@optheader.image_size] = curaddr - baseaddr if @optheader.image_size.kind_of?(::String) # patch the iat where iat_p was defined # sort to ensure a 0-terminated will not overwrite an entry # (try to dump notepad.exe, which has a forwarder;) @imports.find_all { |id| id.iat_p.kind_of?(Integer) }.sort_by { |id| id.iat_p }.each { |id| s = sect_at_rva(id.iat_p) @encoded[s.rawaddr + s.encoded.ptr, id.iat.virtsize] = id.iat binding.update id.iat.binding(baseaddr + id.iat_p) } if imports @encoded.fill @encoded.fixup! binding if @optheader.checksum.kind_of?(::String) and @encoded.reloc.length == 1 # won't work if there are other unresolved relocs checksum = self.class.checksum(@encoded.data, @endianness) @encoded.fixup @optheader.checksum => checksum @optheader.checksum = checksum end end
append the section bodies to @encoded, and link the resulting binary
encode_sections_fixup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode(target='exe', want_relocs=true) @encoded = EncodedData.new label_at(@encoded, 0, 'coff_start') pre_encode_header(target, want_relocs) autoimport encode_exports if export encode_imports if imports encode_resource if resource encode_tls if tls create_relocation_tables if want_relocs encode_relocs if relocations encode_header encode_sections_fixup @encoded.data end
encode a COFF file, building export/import/reloc tables if needed creates the base relocation tables (need for references to IAT not known before) defaults to generating relocatable files, eg ALSR-aware pass want_relocs=false to avoid the file overhead induced by this
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def read_c_attrs(cp) cp.toplevel.symbol.each_value { |v| next if not v.kind_of? C::Variable if v.has_attribute 'export' or ea = v.has_attribute_var('export_as') @export ||= ExportDirectory.new @export.exports ||= [] e = ExportDirectory::Export.new begin e.ordinal = Integer(ea || v.name) rescue ArgumentError e.name = ea || v.name end e.target = v.name @export.exports << e end if v.has_attribute('import') or ln = v.has_attribute_var('import_from') ln ||= WindowsExports::EXPORT[v.name] raise "unknown library for #{v.name}" if not ln i = ImportDirectory::Import.new if ln.include? ':' ln, name = ln.split(':') begin i.ordinal = Integer(name) rescue ArgumentError i.name = name end else i.name = v.name end if v.type.kind_of? C::Function i.thunk = v.name i.target = 'iat_'+i.thunk else i.target = v.name end @imports ||= [] if not id = @imports.find { |id_| id_.libname == ln } id = ImportDirectory.new id.libname = ln id.imports = [] @imports << id end id.imports << i end if v.has_attribute 'entrypoint' @optheader.entrypoint = v.name end } end
honors C attributes: export, export_as(foo), import_from(kernel32), entrypoint import by ordinal: extern __stdcall int anyname(int) __attribute__((import_from(ws2_32:28))); can alias imports with int mygpaddr_alias() attr(import_from(kernel32:GetProcAddr))
read_c_attrs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def autoimport(fallback_append='A') WindowsExports rescue return # autorequire autoexports = WindowsExports::EXPORT.dup @sections.each { |s| next if not s.encoded s.encoded.export.keys.each { |e| autoexports.delete e } } @sections.each { |s| next if not s.encoded s.encoded.reloc.each_value { |r| if r.target.op == :+ and not r.target.lexpr and r.target.rexpr.kind_of?(::String) sym = target = r.target.rexpr sym = sym[4..-1] if sym[0, 4] == 'iat_' elsif r.target.op == :- and r.target.rexpr.kind_of?(::String) and r.target.lexpr.kind_of?(::String) sym = thunk = r.target.lexpr end if not dll = autoexports[sym] sym += fallback_append if sym.kind_of?(::String) and fallback_append.kind_of?(::String) next if not dll = autoexports[sym] end @imports ||= [] next if @imports.find { |id| id.imports.find { |ii| ii.name == sym } } if not id = @imports.find { |id_| id_.libname =~ /^#{dll}(\.dll)?$/i } id = ImportDirectory.new id.libname = dll id.imports = [] @imports << id end if not i = id.imports.find { |i_| i_.name == sym } i = ImportDirectory::Import.new i.name = sym id.imports << i end if (target and i.target and (i.target != target or i.thunk == target)) or (thunk and i.thunk and (i.thunk != thunk or i.target == thunk)) puts "autoimport: conflict for #{target} #{thunk} #{i.inspect}" if $VERBOSE else i.target ||= new_label(target || 'iat_' + thunk) i.thunk ||= thunk if thunk end } } end
try to resolve automatically COFF import tables from self.sections.encoded.relocations and WindowsExports::EXPORT if the relocation target is '<symbolname>' or 'iat_<symbolname>, link to the IAT address, if it is '<symbolname> + <expr>', link to a thunk (plt-like) if the relocation is not found, try again after appending 'fallback_append' to the symbol (eg wsprintf => wsprintfA)
autoimport
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def addr_to_off(addr) s = @segments.find { |s_| s_.type == 'LOAD' and s_.vaddr <= addr and s_.vaddr + s_.memsz > addr } if addr addr - s.vaddr + s.offset if s end
transforms a virtual address to a file offset, from mmaped segments addresses
addr_to_off
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def addr_to_fileoff(addr) la = module_address la = (la == 0 ? (@load_address ||= 0) : 0) addr_to_off(addr - la) end
memory address -> file offset handles relocated LoadedELF
addr_to_fileoff
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def fileoff_to_addr(foff) if s = @segments.find { |s_| s_.type == 'LOAD' and s_.offset <= foff and s_.offset + s_.filesz > foff } la = module_address la = (la == 0 ? (@load_address ||= 0) : 0) s.vaddr + la + foff - s.offset end end
file offset -> memory address handles relocated LoadedELF
fileoff_to_addr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def add_label(name, addr) if not o = addr_to_off(addr) puts "W: Elf: #{name} points to unmmaped space #{'0x%08X' % addr}" if $VERBOSE else l = new_label(name) @encoded.add_export l, o end l end
make an export of +self.encoded+, returns the label name if successful
add_label
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_header(off = 0, decode_phdr=true, decode_shdr=true) @encoded.ptr = off @header.decode self raise InvalidExeFormat, "Invalid elf header size: #{@header.ehsize}" if Header.size(self) != @header.ehsize if decode_phdr and @header.phoff != 0 decode_program_header(@header.phoff+off) end if decode_shdr and @header.shoff != 0 decode_section_header(@header.shoff+off) end end
decodes the elf header, section & program header
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_section_header(off = @header.shoff) raise InvalidExeFormat, "Invalid elf section header size: #{@header.shentsize}" if Section.size(self) != @header.shentsize @encoded.add_export new_label('section_header'), off @encoded.ptr = off @sections = [] @header.shnum.times { @sections << Section.decode(self) } # read sections name if @header.shstrndx != 0 and str = @sections[@header.shstrndx] and str.encoded = @encoded[str.offset, str.size] # LoadedElf may not have shstr mmaped @sections[1..-1].each { |s| s.name = readstr(str.encoded.data, s.name_p) add_label("section_#{s.name}", s.addr) if s.name and s.addr > 0 } end end
decodes the section header section names are read from shstrndx if possible
decode_section_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_program_header(off = @header.phoff) raise InvalidExeFormat, "Invalid elf program header size: #{@header.phentsize}" if Segment.size(self) != @header.phentsize @encoded.add_export new_label('program_header'), off @encoded.ptr = off @segments = [] @header.phnum.times { @segments << Segment.decode(self) } if @header.entry != 0 add_label('entrypoint', @header.entry) end end
decodes the program header table marks the elf entrypoint as an export of +self.encoded+
decode_program_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def check_symbols_hash(off = @tag['HASH']) return if not @encoded.ptr = off hash_bucket_len = decode_word sym_count = decode_word hash_bucket = [] ; hash_bucket_len.times { hash_bucket << decode_word } hash_table = [] ; sym_count.times { hash_table << decode_word } @symbols.each { |s| next if not s.name or s.bind != 'GLOBAL' or s.shndx == 'UNDEF' found = false h = ELF.hash_symbol_name(s.name) off = hash_bucket[h % hash_bucket_len] sym_count.times { # to avoid DoS by loop break if off == 0 if ss = @symbols[off] and ss.name == s.name found = true break end off = hash_table[off] } if not found puts "W: Elf: Symbol #{s.name.inspect} not found in hash table" if $VERBOSE end } end
read the dynamic symbols hash table, and checks that every global and named symbol is accessible through it outputs a warning if it's not and $VERBOSE is set
check_symbols_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def check_symbols_gnu_hash(off = @tag['GNU_HASH'], just_get_count=false) return if not @encoded.ptr = off # when present: the symndx first symbols are not sorted (SECTION/LOCAL/FILE/etc) symtable[symndx] is sorted (1st sorted symbol) # the sorted symbols are sorted by [gnu_hash_symbol_name(symbol.name) % hash_bucket_len] hash_bucket_len = decode_word symndx = decode_word # index of first sorted symbol in symtab maskwords = decode_word # number of words in the second part of the ghash section (32 or 64 bits) shift2 = decode_word # used in the bloom filter bloomfilter = [] ; maskwords.times { bloomfilter << decode_xword } # "bloomfilter[N] has bit B cleared if there is no M (M > symndx) which satisfies (C = @header.class) # ((gnu_hash(sym[M].name) / C) % maskwords) == N && # ((gnu_hash(sym[M].name) % C) == B || # ((gnu_hash(sym[M].name) >> shift2) % C) == B" # bloomfilter may be [~0] if shift2 end hash_bucket = [] ; hash_bucket_len.times { hash_bucket << decode_word } # bucket[N] contains the lowest M for which # gnu_hash(sym[M]) % nbuckets == N # or 0 if none hsymcount = 0 part4 = [] hash_bucket.each { |hmodidx| # for each bucket, walk all the chain # we do not walk the chains in hash_bucket order here, this # is just to read all the part4 as we don't know # beforehand the number of hashed symbols next if hmodidx == 0 # no hash chain for this mod loop do fu = decode_word hsymcount += 1 part4 << fu break if fu & 1 == 1 end } # part4[N] contains # (gnu_hash(sym[N].name) & ~1) | (N == dynsymcount-1 || (gnu_hash(sym[N].name) % nbucket) != (gnu_hash(sym[N+1].name) % nbucket)) # that's the hash, with its lower bit replaced by the bool [1 if i am the last sym having my hash as hash] # we're going to decode the symbol table, and we just want to get the nr of symbols to read if just_get_count # index of highest hashed (exported) symbols ns = hsymcount+symndx # no way to get the number of non-exported symbols from what we have here # so we'll decode all relocs and use the largest index we see.. rels = [] if @encoded.ptr = @tag['REL'] and @tag['RELENT'] == Relocation.size(self) p_end = @encoded.ptr + @tag['RELSZ'] while @encoded.ptr < p_end rels << Relocation.decode(self) end end if @encoded.ptr = @tag['RELA'] and @tag['RELAENT'] == RelocationAddend.size(self) p_end = @encoded.ptr + @tag['RELASZ'] while @encoded.ptr < p_end rels << RelocationAddend.decode(self) end end if @encoded.ptr = @tag['JMPREL'] and relcls = case @tag['PLTREL'] when 'REL'; Relocation when 'RELA'; RelocationAddend end p_end = @encoded.ptr + @tag['PLTRELSZ'] while @encoded.ptr < p_end rels << relcls.decode(self) end end maxr = rels.map { |rel| rel.symbol }.grep(::Integer).max || -1 return [ns, maxr+1].max end # TODO end
checks every symbol's accessibility through the gnu_hash table
check_symbols_gnu_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_tags_interpret if @tag['STRTAB'] if not sz = @tag['STRSZ'] puts "W: Elf: no string table size tag" if $VERBOSE else if l = add_label('dynamic_strtab', @tag['STRTAB']) @tag['STRTAB'] = l strtab = @encoded[l, sz].data end end end @tag.keys.each { |k| case k when Integer when 'NEEDED' # array of strings if not strtab puts "W: Elf: no string table, needed for tag #{k}" if $VERBOSE next end @tag[k].map! { |v| readstr(strtab, v) } when 'SONAME', 'RPATH', 'RUNPATH' # string if not strtab puts "W: Elf: no string table, needed for tag #{k}" if $VERBOSE next end @tag[k] = readstr(strtab, @tag[k]) when 'INIT', 'FINI', 'PLTGOT', 'HASH', 'GNU_HASH', 'SYMTAB', 'RELA', 'REL', 'JMPREL' @tag[k] = add_label('dynamic_' + k.downcase, @tag[k]) || @tag[k] when 'INIT_ARRAY', 'FINI_ARRAY', 'PREINIT_ARRAY' next if not l = add_label('dynamic_' + k.downcase, @tag[k]) if not sz = @tag.delete(k+'SZ') puts "W: Elf: tag #{k} has no corresponding size tag" if $VERBOSE next end tab = @encoded[l, sz] tab.ptr = 0 @tag[k] = [] while tab.ptr < tab.length a = decode_addr(tab) @tag[k] << (add_label("dynamic_#{k.downcase}_#{@tag[k].length}", a) || a) end when 'PLTREL'; @tag[k] = int_to_hash(@tag[k], DYNAMIC_TAG) when 'FLAGS'; @tag[k] = bits_to_hash(@tag[k], DYNAMIC_FLAGS) when 'FLAGS_1'; @tag[k] = bits_to_hash(@tag[k], DYNAMIC_FLAGS_1) when 'FEATURES_1'; @tag[k] = bits_to_hash(@tag[k], DYNAMIC_FEATURES_1) end } end
interprets tags (convert flags, arrays etc), mark them as self.encoded.export
decode_segments_tags_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_symbol_export(s) if s.name and s.shndx != 'UNDEF' and %w[NOTYPE OBJECT FUNC].include?(s.type) if @header.type == 'REL' sec = @sections[s.shndx] o = sec.offset + s.value elsif not o = addr_to_off(s.value) # allow to point to end of segment if not seg = @segments.find { |seg_| seg_.type == 'LOAD' and seg_.vaddr + seg_.memsz == s.value } # check end puts "W: Elf: symbol points to unmmaped space (#{s.inspect})" if $VERBOSE and s.shndx != 'ABS' return end # LoadedELF would have returned an addr_to_off = addr o = s.value - seg.vaddr + seg.offset end name = s.name while @encoded.export[name] and @encoded.export[name] != o puts "W: Elf: symbol #{name} already seen at #{'%X' % @encoded.export[name]} - now at #{'%X' % o}) (may be a different version definition)" if $VERBOSE name += '_' # do not modify inplace end @encoded.add_export name, o end end
marks a symbol as @encoded.export (from s.value, using segments or sections)
decode_symbol_export
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_symbols return unless @tag['STRTAB'] and @tag['STRSZ'] and @tag['SYMTAB'] and (@tag['HASH'] or @tag['GNU_HASH']) raise "E: ELF: unsupported symbol entry size: #{@tag['SYMENT']}" if @tag['SYMENT'] != Symbol.size(self) # find number of symbols if @tag['HASH'] @encoded.ptr = @tag['HASH'] # assume tag already interpreted (would need addr_to_off otherwise) decode_word sym_count = decode_word else sym_count = check_symbols_gnu_hash(@tag['GNU_HASH'], true) end strtab = @encoded[@tag['STRTAB'], @tag['STRSZ']].data.to_str @encoded.ptr = @tag['SYMTAB'] @symbols.clear sym_count.times { s = Symbol.decode(self, strtab) @symbols << s decode_symbol_export(s) } check_symbols_hash if $VERBOSE check_symbols_gnu_hash if $VERBOSE end
read symbol table, and mark all symbols found as exports of self.encoded tables locations are found in self.tags XXX symbol count is found from the hash table, this may not work with GNU_HASH only binaries
decode_segments_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_relocs @relocations.clear if @encoded.ptr = @tag['REL'] raise "E: ELF: unsupported rel entry size #{@tag['RELENT']}" if @tag['RELENT'] != Relocation.size(self) p_end = @encoded.ptr + @tag['RELSZ'] while @encoded.ptr < p_end @relocations << Relocation.decode(self) end end if @encoded.ptr = @tag['RELA'] raise "E: ELF: unsupported rela entry size #{@tag['RELAENT'].inspect}" if @tag['RELAENT'] != RelocationAddend.size(self) p_end = @encoded.ptr + @tag['RELASZ'] while @encoded.ptr < p_end @relocations << RelocationAddend.decode(self) end end if @encoded.ptr = @tag['JMPREL'] case reltype = @tag['PLTREL'] when 'REL'; relcls = Relocation when 'RELA'; relcls = RelocationAddend else raise "E: ELF: unsupported plt relocation type #{reltype}" end p_end = @encoded.ptr + @tag['PLTRELSZ'] while @encoded.ptr < p_end @relocations << relcls.decode(self) end end end
decode relocation tables (REL, RELA, JMPREL) from @tags
decode_segments_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_relocs_interpret relocproc = "arch_decode_segments_reloc_#{@header.machine.to_s.downcase}" if not respond_to? relocproc puts "W: Elf: relocs for arch #{@header.machine} unsupported" if $VERBOSE return end @relocations.each { |r| next if r.offset == 0 if not o = addr_to_off(r.offset) puts "W: Elf: relocation in unmmaped space (#{r.inspect})" if $VERBOSE next end if @encoded.reloc[o] puts "W: Elf: not rerelocating address #{'%08X' % r.offset}" if $VERBOSE next end @encoded.ptr = o if rel = send(relocproc, r) @encoded.reloc[o] = rel end } if @header.machine == 'MIPS' and @tag['PLTGOT'] and @tag['GOTSYM'] and @tag['LOCAL_GOTNO'] puts "emulating mips PLT-like relocs" if $VERBOSE wsz = @bitsize/8 dyntab = label_addr(@tag['PLTGOT']) - (@tag['GOTSYM'] - @tag['LOCAL_GOTNO']) * wsz dt_o = addr_to_off(dyntab) @symbols.each_with_index { |sym, i| next if i < @tag['GOTSYM'] or not sym.name r = Metasm::Relocation.new(Expression[sym.name], "u#@bitsize".to_sym, @endianness) @encoded.reloc[dt_o + wsz*i] = r } end end
use relocations as self.encoded.reloc
decode_segments_relocs_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def reloc_target(reloc) target = 0 if reloc.symbol.kind_of?(Symbol) if reloc.symbol.type == 'SECTION' s = @sections[reloc.symbol.shndx] if not target = @encoded.inv_export[s.offset] target = new_label(s.name) @encoded.add_export(target, s.offset) end elsif reloc.symbol.name target = reloc.symbol.name end end target end
returns the target of a relocation using reloc.symbol may create new labels if the relocation targets a section
reloc_target
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_386(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @encoded.ptr, true) end # decode addend if needed case reloc.type when 'NONE', 'COPY', 'GLOB_DAT', 'JMP_SLOT' # no addend else addend = reloc.addend || decode_sword end case reloc.type when 'NONE' when 'RELATIVE' # base = @segments.find_all { |s| s.type == 'LOAD' }.map { |s| s.vaddr }.min & 0xffff_f000 # compiled to be loaded at seg.vaddr target = addend if o = addr_to_off(target) if not label = @encoded.inv_export[o] label = new_label("xref_#{Expression[target]}") @encoded.add_export label, o end target = label else puts "W: Elf: relocation pointing out of mmaped space #{reloc.inspect}" if $VERBOSE end when 'GLOB_DAT', 'JMP_SLOT', '32', 'PC32', 'TLS_TPOFF', 'TLS_TPOFF32' # XXX use versionned version # lazy jmp_slot ? target = reloc_target(reloc) target = Expression[target, :-, reloc.offset] if reloc.type == 'PC32' target = Expression[target, :+, addend] if addend and addend != 0 target = Expression[target, :+, 'tlsoffset'] if reloc.type == 'TLS_TPOFF' target = Expression[:-, [target, :+, 'tlsoffset']] if reloc.type == 'TLS_TPOFF32' when 'COPY' # mark the address pointed as a copy of the relocation target if not reloc.symbol.kind_of?(Symbol) or not name = reloc.symbol.name puts "W: Elf: symbol to COPY has no name: #{reloc.inspect}" if $VERBOSE name = '' end name = new_label("copy_of_#{name}") @encoded.add_export name, @encoded.ptr target = nil else puts "W: Elf: unhandled 386 reloc #{reloc.inspect}" if $VERBOSE target = nil end Metasm::Relocation.new(Expression[target], :u32, @endianness) if target end
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_386
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_mips(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @encoded.ptr, true) end original_word = decode_word # decode addend if needed case reloc.type when 'NONE' # no addend else addend = reloc.addend || Expression.make_signed(original_word, 32) end case reloc.type when 'NONE' when '32', 'REL32' target = reloc_target(reloc) target = Expression[target, :-, reloc.offset] if reloc.type == 'REL32' target = Expression[target, :+, addend] if addend and addend != 0 when '26' target = reloc_target(reloc) addend &= 0x3ff_ffff target = Expression[target, :+, [addend, :<<, 2]] if addend and addend != 0 target = Expression[[original_word, :&, 0xfc0_0000], :|, [[target, :&, 0x3ff_ffff], :>>, 2]] when 'HI16' target = reloc_target(reloc) addend &= 0xffff target = Expression[target, :+, [addend, :<<, 16]] if addend and addend != 0 target = Expression[[original_word, :&, 0xffff_0000], :|, [[target, :>>, 16], :&, 0xffff]] when 'LO16' target = reloc_target(reloc) addend &= 0xffff target = Expression[target, :+, addend] if addend and addend != 0 target = Expression[[original_word, :&, 0xffff_0000], :|, [target, :&, 0xffff]] else puts "W: Elf: unhandled MIPS reloc #{reloc.inspect}" if $VERBOSE target = nil end Metasm::Relocation.new(Expression[target], :u32, @endianness) if target end
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_mips
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_x86_64(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @encoded.ptr, true) end # decode addend if needed case reloc.type when 'NONE' # no addend when '32', 'PC32'; addend = reloc.addend || decode_sword else addend = reloc.addend || decode_sxword end sz = :u64 case reloc.type when 'NONE' when 'RELATIVE' # base = @segments.find_all { |s| s.type == 'LOAD' }.map { |s| s.vaddr }.min & 0xffff_f000 # compiled to be loaded at seg.vaddr target = addend if o = addr_to_off(target) if not label = @encoded.inv_export[o] label = new_label("xref_#{Expression[target]}") @encoded.add_export label, o end target = label else puts "W: Elf: relocation pointing out of mmaped space #{reloc.inspect}" if $VERBOSE end when 'GLOB_DAT', 'JMP_SLOT', '64', 'PC64', '32', 'PC32' # XXX use versionned version # lazy jmp_slot ? target = reloc_target(reloc) target = Expression[target, :-, reloc.offset] if reloc.type == 'PC64' or reloc.type == 'PC32' target = Expression[target, :+, addend] if addend and addend != 0 sz = :u32 if reloc.type == '32' or reloc.type == 'PC32' when 'COPY' # mark the address pointed as a copy of the relocation target if not reloc.symbol.kind_of?(Symbol) or not name = reloc.symbol.name puts "W: Elf: symbol to COPY has no name: #{reloc.inspect}" if $VERBOSE name = '' end name = new_label("copy_of_#{name}") @encoded.add_export name, @encoded.ptr target = nil else puts "W: Elf: unhandled X86_64 reloc #{reloc.inspect}" if $VERBOSE target = nil end Metasm::Relocation.new(Expression[target], sz, @endianness) if target end
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_x86_64
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_leb(ed = @encoded) v = s = 0 loop { b = ed.read(1).unpack('C').first.to_i v |= (b & 0x7f) << s s += 7 break v if (b&0x80) == 0 } end
decode an ULEB128 (dwarf2): read bytes while high bit is set, littleendian
decode_leb
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_debug return if not @sections # assert presence of DWARF sections info = @sections.find { |sec| sec.name == '.debug_info' } abbrev = @sections.find { |sec| sec.name == '.debug_abbrev' } str = @sections.find { |sec| sec.name == '.debug_str' } return if not info or not abbrev # section -> content info = @encoded[info.offset, info.size] abbrev = @encoded[abbrev.offset, abbrev.size] str = @encoded[str.offset, str.size] if str @debug = [] while info.ptr < info.length @debug << DwarfDebug.decode(self, info, abbrev, str) end end
decodes the debugging information if available only a subset of DWARF2/3 is handled right now most info taken from http://ratonland.org/?entry=39 & libdwarf/dwarf.h
decode_debug
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_dynamic(decode_relocs=true) return if not dynamic = @segments.find { |s| s.type == 'DYNAMIC' } @encoded.ptr = add_label('dynamic_tags', dynamic.vaddr) decode_tags decode_segments_tags_interpret decode_segments_symbols return if not decode_relocs decode_segments_relocs decode_segments_relocs_interpret end
decodes the ELF dynamic tags, interpret them, and decodes symbols and relocs
decode_segments_dynamic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments decode_segments_dynamic decode_sections_symbols #decode_debug # too many info, decode on demand @segments.each { |s| case s.type when 'LOAD', 'INTERP' sz = s.filesz pagepad = (-(s.offset + sz)) % 4096 s.encoded = @encoded[s.offset, sz] || EncodedData.new if s.type == 'LOAD' and sz > 0 and not s.flags.include?('W') # align loaded data to the next page boundary for readonly mmap # but discard the labels/relocs etc s.encoded << @encoded[s.offset+sz, pagepad].data rescue nil s.encoded.virtsize = sz+pagepad end s.encoded.virtsize = s.memsz if s.memsz > s.encoded.virtsize end } end
decodes the dynamic segment, fills segments.encoded
decode_segments
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_sections @symbols.clear # the NULL symbol is explicit in the symbol table decode_sections_symbols decode_sections_relocs @sections.each { |s| case s.type when 'PROGBITS', 'NOBITS' when 'TODO' # TODO end } @sections.find_all { |s| s.type == 'PROGBITS' or s.type == 'NOBITS' }.each { |s| if s.flags.include? 'ALLOC' if s.type == 'NOBITS' s.encoded = EncodedData.new '', :virtsize => s.size else s.encoded = @encoded[s.offset, s.size] || EncodedData.new s.encoded.virtsize = s.size end end } end
decodes sections, interprets symbols/relocs, fills sections.encoded
decode_sections
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode decode_header case @header.type when 'DYN', 'EXEC'; decode_segments when 'REL'; decode_sections when 'CORE' end end
decodes the elf header, and depending on the elf type, decode segments or sections
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def cpu_from_headers case @header.machine when 'X86_64'; X86_64.new when '386'; Ia32.new when 'MIPS'; (@header.flags.include?('32BITMODE') ? MIPS64 : MIPS).new @endianness when 'PPC'; PPC.new when 'ARM'; ARM.new when 'SH'; Sh4.new else raise "unsupported cpu #{@header.machine}" end end
returns a metasm CPU object corresponding to +header.machine+
cpu_from_headers
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def get_default_entrypoints ep = [] ep << @header.entry if @header.entry != 0 @symbols.each { |s| ep << s.value if s.shndx != 'UNDEF' and s.type == 'FUNC' } if @symbols ep end
returns an array including the ELF entrypoint (if not null) and the FUNC symbols addresses TODO include init/init_array
get_default_entrypoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def init_disassembler d = super() d.backtrace_maxblocks_data = 4 if d.get_section_at(0) # fixes call [constructor] => 0 d.decoded[0] = true d.function[0] = @cpu.disassembler_default_func end case @cpu.shortname when 'ia32', 'x64' old_cp = d.c_parser d.c_parser = nil d.parse_c <<EOC void *dlsym(int, char *); // has special callback // gcc's entrypoint, need pointers to reach main exe code (last callback) void __libc_start_main(void(*)(), int, int, void(*)(), void(*)()) __attribute__((noreturn)); // standard noreturn, optimized by gcc void __attribute__((noreturn)) exit(int); void _exit __attribute__((noreturn))(int); void abort(void) __attribute__((noreturn)); void __stack_chk_fail __attribute__((noreturn))(void); EOC d.function[Expression['dlsym']] = dls = @cpu.decode_c_function_prototype(d.c_parser, 'dlsym') d.function[Expression['__libc_start_main']] = @cpu.decode_c_function_prototype(d.c_parser, '__libc_start_main') d.function[Expression['exit']] = @cpu.decode_c_function_prototype(d.c_parser, 'exit') d.function[Expression['_exit']] = @cpu.decode_c_function_prototype(d.c_parser, '_exit') d.function[Expression['abort']] = @cpu.decode_c_function_prototype(d.c_parser, 'abort') d.function[Expression['__stack_chk_fail']] = @cpu.decode_c_function_prototype(d.c_parser, '__stack_chk_fail') d.c_parser = old_cp dls.btbind_callback = lambda { |dasm, bind, funcaddr, calladdr, expr, origin, maxdepth| sz = @cpu.size/8 raise 'dlsym call error' if not dasm.decoded[calladdr] if @cpu.shortname == 'x64' arg2 = :rsi else arg2 = Indirection.new(Expression[:esp, :+, 2*sz], sz, calladdr) end fnaddr = dasm.backtrace(arg2, calladdr, :include_start => true, :maxdepth => maxdepth) if fnaddr.kind_of? ::Array and fnaddr.length == 1 and s = dasm.get_section_at(fnaddr.first) and fn = s[0].read(64) and i = fn.index(?\0) and i > sz # try to avoid ordinals bind = bind.merge @cpu.register_symbols[0] => Expression[fn[0, i]] end bind } df = d.function[:default] = @cpu.disassembler_default_func df.backtrace_binding[@cpu.register_symbols[4]] = Expression[@cpu.register_symbols[4], :+, @cpu.size/8] df.btbind_callback = nil when 'mips' (d.address_binding[@header.entry] ||= {})[:$t9] ||= Expression[@header.entry] @symbols.each { |s| next if s.shndx == 'UNDEF' or s.type != 'FUNC' (d.address_binding[s.value] ||= {})[:$t9] ||= Expression[s.value] } d.function[:default] = @cpu.disassembler_default_func when 'sh4' noret = DecodedFunction.new noret.noreturn = true %w[__stack_chk_fail abort exit].each { |fn| d.function[Expression[fn]] = noret } d.function[:default] = @cpu.disassembler_default_func end d end
returns a disassembler with a special decodedfunction for dlsym, __libc_start_main, and a default function (i386 only)
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def section_info if @sections @sections[1..-1].map { |s| [s.name, s.addr, s.size, s.flags.join(',')] } else @segments.map { |s| [nil, s.vaddr, s.memsz, s.flags.join(',')] } end end
returns an array of [name, addr, length, info]
section_info
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments if @load_address == 0 and @segments.find { |s| s.type == 'LOAD' and s.vaddr > @encoded.length } @load_address = @segments.find_all { |s| s.type == 'LOAD' }.map { |s| s.vaddr }.min end decode_segments_dynamic @segments.each { |s| if s.type == 'LOAD' s.encoded = @encoded[addr_to_off(s.vaddr), s.memsz] end } end
decodes the dynamic segment, fills segments.encoded
decode_segments
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_header(off = 0) @encoded.ptr = off @header.decode self decode_program_header(@header.phoff+off) end
do not try to decode the section header by default
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def make_name_p elf return 0 if not name or @name == '' or elf.header.shnum == 0 if elf.header.shstrndx.to_i == 0 or not elf.sections[elf.header.shstrndx] sn = Section.new sn.name = '.shstrtab' sn.type = 'STRTAB' sn.flags = [] sn.addralign = 1 sn.encoded = EncodedData.new << 0 elf.header.shstrndx = elf.sections.length elf.sections << sn end sne = elf.sections[elf.header.shstrndx].encoded return if name_p and sne.data[@name_p, @name.length+1] == @name+0.chr return if @name_p = sne.data.index(@name+0.chr) @name_p = sne.virtsize sne << @name << 0 end
defines the @name_p field from @name and elf.section[elf.header.shstrndx] creates .shstrtab if needed
make_name_p
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def make_name_p(elf, strtab) s = strtab.kind_of?(EncodedData) ? strtab.data : strtab return if name_p and s[@name_p, @name.length+1] == @name+0.chr return if @name_p = s.index(@name+0.chr) @name_p = strtab.length strtab << @name << 0 end
sets the value of @name_p, appends @name to strtab if needed
make_name_p
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_check_section_size(s) if s.size and s.encoded.virtsize < s.size puts "W: Elf: preexisting section #{s} has grown, relocating" if $VERBOSE s.addr = s.offset = nil s.size = s.encoded.virtsize end end
checks a section's data has not grown beyond s.size, if so undefs addr/offset
encode_check_section_size
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_reorder_symbols gnu_hash_bucket_length = 42 # TODO @symbols[1..-1] = @symbols[1..-1].sort_by { |s| if s.bind != 'GLOBAL' -2 elsif s.shndx == 'UNDEF' or not s.name -1 else ELF.gnu_hash_symbol_name(s.name) % gnu_hash_bucket_length end } end
reorders self.symbols according to their gnu_hash
encode_reorder_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_add_section s # order: r rx rw noalloc rank = lambda { |sec| f = sec.flags sec.type == 'NULL' ? -2 : sec.addr ? -1 : f.include?('ALLOC') ? !f.include?('WRITE') ? !f.include?('EXECINSTR') ? 0 : 1 : 2 : 3 } srank = rank[s] nexts = @sections.find { |sec| rank[sec] > srank } # find section with rank superior nexts = nexts ? @sections.index(nexts) : -1 # if none, last if @header.shstrndx.to_i != 0 and nexts != -1 and @header.shstrndx >= nexts @header.shstrndx += 1 end @sections.insert(nexts, s) # insert section end
sorted insert of a new section to self.sections according to its permission (for segment merging)
encode_add_section
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_hash return if @symbols.length <= 1 if not hash = @sections.find { |s| s.type == 'HASH' } hash = Section.new hash.name = '.hash' hash.type = 'HASH' hash.flags = ['ALLOC'] hash.entsize = hash.addralign = 4 encode_add_section hash end hash.encoded = EncodedData.new # to find a symbol from its name : # 1: idx = hash(name) # 2: idx = bucket[idx % bucket.size] # 3: if idx == 0: return notfound # 4: if dynsym[idx].name == name: return found # 5: idx = chain[idx] ; goto 3 bucket = Array.new(@symbols.length/4+1, 0) chain = Array.new(@symbols.length, 0) @symbols.each_with_index { |s, i| next if s.bind == 'LOCAL' or not s.name or s.shndx == 'UNDEF' hash_mod = ELF.hash_symbol_name(s.name) % bucket.length chain[i] = bucket[hash_mod] bucket[hash_mod] = i } hash.encoded << encode_word(bucket.length) << encode_word(chain.length) bucket.each { |b| hash.encoded << encode_word(b) } chain.each { |c| hash.encoded << encode_word(c) } @tag['HASH'] = label_at(hash.encoded, 0) encode_check_section_size hash hash end
encodes the symbol dynamic hash table in the .hash section, updates the HASH tag
encode_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_segments_symbols(strtab) return if @symbols.length <= 1 if not dynsym = @sections.find { |s| s.type == 'DYNSYM' } dynsym = Section.new dynsym.name = '.dynsym' dynsym.type = 'DYNSYM' dynsym.entsize = Symbol.size(self) dynsym.addralign = 4 dynsym.flags = ['ALLOC'] dynsym.info = @symbols[1..-1].find_all { |s| s.bind == 'LOCAL' }.length + 1 dynsym.link = strtab encode_add_section dynsym end dynsym.encoded = EncodedData.new @symbols.each { |s| dynsym.encoded << s.encode(self, strtab.encoded) } # needs all section indexes, as will be in the final section header @tag['SYMTAB'] = label_at(dynsym.encoded, 0) @tag['SYMENT'] = Symbol.size(self) encode_check_section_size dynsym dynsym end
encodes the symbol table should have a stable self.sections array (only append allowed after this step)
encode_segments_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_segments_relocs return if not @relocations or @relocations.empty? arch_preencode_reloc_func = "arch_#{@header.machine.downcase}_preencode_reloc" send arch_preencode_reloc_func if respond_to? arch_preencode_reloc_func list = @relocations.find_all { |r| r.type == 'JMP_SLOT' } if not list.empty? or @relocations.empty? if list.find { |r| r.addend } stype = 'RELA' sname = '.rela.plt' else stype = 'REL' sname = '.rel.plt' end if not relplt = @sections.find { |s| s.type == stype and s.name == sname } relplt = Section.new relplt.name = sname relplt.flags = ['ALLOC'] encode_add_section relplt end relplt.encoded = EncodedData.new('', :export => {'_REL_PLT' => 0}) list.each { |r| relplt.encoded << r.encode(self) } @tag['JMPREL'] = label_at(relplt.encoded, 0) @tag['PLTRELSZ'] = relplt.encoded.virtsize @tag['PLTREL'] = relplt.type = stype @tag[stype + 'ENT'] = relplt.entsize = relplt.addralign = (stype == 'REL' ? Relocation.size(self) : RelocationAddend.size(self)) encode_check_section_size relplt end list = @relocations.find_all { |r| r.type != 'JMP_SLOT' and not r.addend } if not list.empty? if not @tag['TEXTREL'] and @sections.find { |s_| s_.encoded and e = s_.encoded.inv_export[0] and not s_.flags.include? 'WRITE' and list.find { |r| Expression[r.offset, :-, e].reduce.kind_of? ::Integer } # TODO need to check with r.offset.bind(elf_binding) } @tag['TEXTREL'] = 0 end if not rel = @sections.find { |s_| s_.type == 'REL' and s_.name == '.rel.dyn' } rel = Section.new rel.name = '.rel.dyn' rel.type = 'REL' rel.flags = ['ALLOC'] rel.entsize = rel.addralign = Relocation.size(self) encode_add_section rel end rel.encoded = EncodedData.new list.each { |r| rel.encoded << r.encode(self) } @tag['REL'] = label_at(rel.encoded, 0) @tag['RELENT'] = Relocation.size(self) @tag['RELSZ'] = rel.encoded.virtsize encode_check_section_size rel end list = @relocations.find_all { |r| r.type != 'JMP_SLOT' and r.addend } if not list.empty? if not rela = @sections.find { |s_| s_.type == 'RELA' and s_.name == '.rela.dyn' } rela = Section.new rela.name = '.rela.dyn' rela.type = 'RELA' rela.flags = ['ALLOC'] rela.entsize = rela.addralign = RelocationAddend.size(self) encode_add_section rela end rela.encoded = EncodedData.new list.each { |r| rela.encoded << r.encode(self) } @tag['RELA'] = label_at(rela.encoded, 0) @tag['RELAENT'] = RelocationAddend.size(self) @tag['RELASZ'] = rela.encoded.virtsize encode_check_section_size rela end end
encodes the relocation tables needs a complete self.symbols array
encode_segments_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def arch_386_preencode_reloc return if @relocations.empty? # if .got.plt does not exist, the dynamic loader segfaults if not gotplt = @sections.find { |s| s.type == 'PROGBITS' and s.name == '.got.plt' } gotplt = Section.new gotplt.name = '.got.plt' gotplt.type = 'PROGBITS' gotplt.flags = %w[ALLOC WRITE] gotplt.addralign = @bitsize/8 # _DYNAMIC is not base-relocated at runtime encode_add_section gotplt end gotplt.encoded ||= (EncodedData.new('', :export => {'_PLT_GOT' => 0}) << encode_xword('_DYNAMIC') << encode_xword(0) << encode_xword(0)) @tag['PLTGOT'] = label_at(gotplt.encoded, 0) plt = nil shellcode = lambda { |c| Shellcode.new(@cpu).share_namespace(self).assemble(c).encoded } @relocations.dup.each { |r| case r.type when 'PC32' next if not r.symbol if r.symbol.type != 'FUNC' # external data xref: generate a GOT entry # XXX reuse .got.plt ? if not got ||= @sections.find { |s| s.type == 'PROGBITS' and s.name == '.got' } got = Section.new got.name = '.got' got.type = 'PROGBITS' got.flags = %w[ALLOC WRITE] got.addralign = @bitsize/8 got.encoded = EncodedData.new encode_add_section got end prevoffset = r.offset gotlabel = r.symbol.name + '_got_entry' if not got.encoded.export[gotlabel] # create the got thunk got.encoded.add_export(gotlabel, got.encoded.length) got.encoded << encode_xword(0) # transform the reloc PC32 => GLOB_DAT r.type = 'GLOB_DAT' r.offset = Expression[gotlabel] r.addend = 0 if @bitsize == 64 else @relocations.delete r end # prevoffset is label_section_start + int_section_offset target_s = @sections.find { |s| s.encoded and s.encoded.export[prevoffset.lexpr] == 0 } rel = target_s.encoded.reloc[prevoffset.rexpr] # [foo] => [foo - reloc_addr + gotlabel] rel.target = Expression[[rel.target, :-, prevoffset], :+, gotlabel] next end # convert to .plt entry # # [.plt header] # plt_start: # caller set ebx = gotplt if generate_PIC # push [gotplt+4] # jmp [gotplt+8] # # [.plt thunk] # some_func_thunk: # jmp [gotplt+func_got_offset] # some_func_got_default: # push some_func_jmpslot_offset_in_.rel.plt # jmp plt_start # # [.got.plt header] # dd _DYNAMIC # dd 0 # rewritten to GOTPLT? by ld-linux # dd 0 # rewritten to dlresolve_inplace by ld-linux # # [.got.plt + func_got_offset] # dd some_func_got_default # lazily rewritten to the real addr of some_func by jmp dlresolve_inplace # # base_relocated ? # in the PIC case, _dlresolve imposes us to use the ebx register (which may not be saved by the calling function..) # also geteip trashes eax, which may interfere with regparm(3) base = @cpu.generate_PIC ? @bitsize == 32 ? 'ebx' : 'rip-$_+_PLT_GOT' : '_PLT_GOT' if not plt ||= @sections.find { |s| s.type == 'PROGBITS' and s.name == '.plt' } plt = Section.new plt.name = '.plt' plt.type = 'PROGBITS' plt.flags = %w[ALLOC EXECINSTR] plt.addralign = @bitsize/8 plt.encoded = EncodedData.new sz = @bitsize/8 ptqual = @bitsize == 32 ? 'dword' : 'qword' plt.encoded << shellcode["metasm_plt_start:\npush #{ptqual} ptr [#{base}+#{sz}]\njmp #{ptqual} ptr [#{base}+#{2*sz}]"] if @cpu.generate_PIC and @bitsize == 32 and not @sections.find { |s| s.encoded and s.encoded.export['metasm_intern_geteip'] } plt.encoded << shellcode["metasm_intern_geteip:\ncall 42f\n42: pop eax\nsub eax, 42b-metasm_intern_geteip\nret"] end encode_add_section plt end prevoffset = r.offset pltlabel = r.symbol.name + '_plt_thunk' if not plt.encoded.export[pltlabel] # create the plt thunk plt.encoded.add_export pltlabel, plt.encoded.length if @cpu.generate_PIC and @bitsize == 32 plt.encoded << shellcode["call metasm_intern_geteip\nlea #{base}, [eax+_PLT_GOT-metasm_intern_geteip]"] end plt.encoded << shellcode["jmp [#{base} + #{gotplt.encoded.length}]"] plt.encoded.add_export r.symbol.name+'_plt_default', plt.encoded.length reloffset = @relocations.find_all { |rr| rr.type == 'JMP_SLOT' }.length reloffset *= Relocation.size(self) if @bitsize == 32 plt.encoded << shellcode["push #{reloffset}\njmp metasm_plt_start"] # transform the reloc PC32 => JMP_SLOT r.type = 'JMP_SLOT' r.offset = Expression['_PLT_GOT', :+, gotplt.encoded.length] r.addend = 0 if @bitsize == 64 gotplt.encoded << encode_xword(r.symbol.name + '_plt_default') else @relocations.delete r end # mutate the original relocation # XXX relies on the exact form of r.target from arch_create_reloc target_s = @sections.find { |s| s.encoded and s.encoded.export[prevoffset.lexpr] == 0 } rel = target_s.encoded.reloc[prevoffset.rexpr] rel.target = Expression[[[rel.target, :-, prevoffset.rexpr], :-, label_at(target_s.encoded, 0)], :+, pltlabel] # when 'GOTOFF', 'GOTPC' end } encode_check_section_size gotplt encode_check_section_size plt if plt #encode_check_section_size got if got end
creates the .plt/.got from the @relocations
arch_386_preencode_reloc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_segments_dynamic if not strtab = @sections.find { |s| s.type == 'STRTAB' and s.flags.include? 'ALLOC' } strtab = Section.new strtab.name = '.dynstr' strtab.addralign = 1 strtab.type = 'STRTAB' strtab.flags = ['ALLOC'] encode_add_section strtab end strtab.encoded = EncodedData.new << 0 @tag['STRTAB'] = label_at(strtab.encoded, 0) if not dynamic = @sections.find { |s| s.type == 'DYNAMIC' } dynamic = Section.new dynamic.name = '.dynamic' dynamic.type = 'DYNAMIC' dynamic.flags = %w[WRITE ALLOC] # XXX why write ? dynamic.addralign = dynamic.entsize = @bitsize / 8 * 2 dynamic.link = strtab encode_add_section dynamic end dynamic.encoded = EncodedData.new('', :export => {'_DYNAMIC' => 0}) encode_tag = lambda { |k, v| dynamic.encoded << encode_sxword(int_from_hash(k, DYNAMIC_TAG)) << encode_xword(v) } # find or create string in strtab add_str = lambda { |n| if n and n != '' and not ret = strtab.encoded.data.index(n + 0.chr) ret = strtab.encoded.virtsize strtab.encoded << n << 0 end ret || 0 } @tag.keys.each { |k| case k when 'NEEDED'; @tag[k].each { |n| encode_tag[k, add_str[n]] } when 'SONAME', 'RPATH', 'RUNPATH'; encode_tag[k, add_str[@tag[k]]] when 'INIT_ARRAY', 'FINI_ARRAY', 'PREINIT_ARRAY' # build section containing the array if not ar = @sections.find { |s| s.name == '.' + k.downcase } ar = Section.new ar.name = '.' + k.downcase ar.type = k ar.addralign = ar.entsize = @bitsize/8 ar.flags = %w[WRITE ALLOC] ar.encoded = EncodedData.new encode_add_section ar # insert before encoding syms/relocs (which need section indexes) end # fill these later, but create the base relocs now arch_create_reloc_func = "arch_#{@header.machine.downcase}_create_reloc" next if not respond_to?(arch_create_reloc_func) curaddr = label_at(@encoded, 0, 'elf_start') fkbind = {} @sections.each { |s| next if not s.encoded fkbind.update s.encoded.binding(Expression[curaddr, :+, 1]) } @relocations ||= [] off = ar.encoded.length @tag[k].each { |a| rel = Metasm::Relocation.new(Expression[a], "u#@bitsize".to_sym, @endianness) send(arch_create_reloc_func, ar, off, fkbind, rel) off += @bitsize/8 } end } encode_reorder_symbols encode_gnu_hash encode_hash encode_segments_relocs dynsym = encode_segments_symbols(strtab) @sections.find_all { |s| %w[HASH GNU_HASH REL RELA].include? s.type }.each { |s| s.link = dynsym } encode_check_section_size strtab # rm unused tag (shrink .nointerp binaries by allowing to skip the section entirely) @tag.delete('STRTAB') if strtab.encoded.length == 1 # XXX any order needed ? @tag.keys.each { |k| case k when Integer # unknown tags = array of values @tag[k].each { |n| encode_tag[k, n] } when 'PLTREL'; encode_tag[k, int_from_hash(@tag[k], DYNAMIC_TAG)] when 'FLAGS'; encode_tag[k, bits_from_hash(@tag[k], DYNAMIC_FLAGS)] when 'FLAGS_1'; encode_tag[k, bits_from_hash(@tag[k], DYNAMIC_FLAGS_1)] when 'FEATURES_1'; encode_tag[k, bits_from_hash(@tag[k], DYNAMIC_FEATURES_1)] when 'NULL' # keep last when 'STRTAB' encode_tag[k, @tag[k]] encode_tag['STRSZ', strtab.encoded.size] when 'INIT_ARRAY', 'FINI_ARRAY', 'PREINIT_ARRAY' # build section containing the array ar = @sections.find { |s| s.name == '.' + k.downcase } @tag[k].each { |p| ar.encoded << encode_addr(p) } encode_check_section_size ar encode_tag[k, label_at(ar.encoded, 0)] encode_tag[k + 'SZ', ar.encoded.virtsize] when 'NEEDED', 'SONAME', 'RPATH', 'RUNPATH' # already handled else encode_tag[k, @tag[k]] end } encode_tag['NULL', @tag['NULL'] || 0] unless @tag.empty? encode_check_section_size dynamic end
encodes the .dynamic section, creates .hash/.gnu.hash/.rel/.rela/.dynsym/.strtab/.init,*_array as needed
encode_segments_dynamic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def automagic_symbols GNUExports rescue return # autorequire autoexports = GNUExports::EXPORT.dup @sections.each { |s| next if not s.encoded s.encoded.export.keys.each { |e| autoexports.delete e } } @sections.each { |s| next if not s.encoded s.encoded.reloc.each_value { |r| et = r.target.externals extern = et.find_all { |name| autoexports[name] } next if extern.length != 1 symname = extern.first if not @symbols.find { |sym| sym.name == symname } @tag['NEEDED'] ||= [] @tag['NEEDED'] |= [autoexports[symname]] sym = Symbol.new sym.shndx = 'UNDEF' sym.type = 'FUNC' sym.name = symname sym.bind = 'GLOBAL' @symbols << sym end } } end
creates the undef symbol list from the section.encoded.reloc and a list of known exported symbols (e.g. from libc) also populates @tag['NEEDED']
automagic_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def create_relocations @relocations = [] arch_create_reloc_func = "arch_#{@header.machine.downcase}_create_reloc" if not respond_to? arch_create_reloc_func puts "Elf: create_reloc: unhandled architecture #{@header.machine}" if $VERBOSE return end # create a fake binding with all our own symbols # not foolproof, should work in most cases curaddr = label_at(@encoded, 0, 'elf_start') binding = {'_DYNAMIC' => 0, '_GOT' => 0} # XXX @sections.each { |s| next if not s.encoded binding.update s.encoded.binding(curaddr) curaddr = Expression[curaddr, :+, s.encoded.virtsize] } @sections.each { |s| next if not s.encoded s.encoded.reloc.each { |off, rel| t = rel.target.bind(binding).reduce next if not t.kind_of? Expression # XXX segment_encode only send(arch_create_reloc_func, s, off, binding) } } end
reads the existing segment/sections.encoded and populate @relocations from the encoded.reloc hash
create_relocations
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def arch_386_create_reloc(section, off, binding, rel=nil) rel ||= section.encoded.reloc[off] if rel.endianness != @endianness or not [:u32, :i32, :a32].include? rel.type puts "ELF: 386_create_reloc: ignoring reloc #{rel.target} in #{section.name}: bad reloc type" if $VERBOSE return end startaddr = label_at(@encoded, 0) r = Relocation.new r.offset = Expression[label_at(section.encoded, 0, 'sect_start'), :+, off] if Expression[rel.target, :-, startaddr].bind(binding).reduce.kind_of?(::Integer) # this location is relative to the base load address of the ELF r.type = 'RELATIVE' else et = rel.target.externals extern = et.find_all { |name| not binding[name] } if extern.length != 1 puts "ELF: 386_create_reloc: ignoring reloc #{rel.target} in #{section.name}: #{extern.inspect} unknown" if $VERBOSE return end if not sym = @symbols.find { |s| s.name == extern.first } puts "ELF: 386_create_reloc: ignoring reloc #{rel.target} in #{section.name}: undefined symbol #{extern.first}" if $VERBOSE return end r.symbol = sym rel.target = Expression[rel.target, :-, sym.name] if rel.target.bind(binding).reduce.kind_of? ::Integer r.type = '32' elsif Expression[rel.target, :+, label_at(section.encoded, 0)].bind(section.encoded.binding).reduce.kind_of? ::Integer rel.target = Expression[[rel.target, :+, label_at(section.encoded, 0)], :+, off] r.type = 'PC32' # TODO tls ? else puts "ELF: 386_create_reloc: ignoring reloc #{sym.name} + #{rel.target}: cannot find matching standard reloc type" if $VERBOSE return end end @relocations << r end
references to FUNC symbols are transformed to JMPSLOT relocations (aka call to .plt) TODO ET_REL support
arch_386_create_reloc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def invalidate_header @header.shoff = @header.shnum = nil @header.phoff = @header.phnum = nil @header.shstrndx = nil @sections.to_a.each { |s| s.name_p = nil s.offset = nil } @segments.to_a.each { |s| s.offset = nil } self end
resets the fields of the elf headers that should be recalculated, eg phdr offset
invalidate_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_make_segments_from_sections # fixed addresses first seclist = @sections.find_all { |sec| sec.addr.kind_of? Integer }.sort_by { |sec| sec.addr } | @sections seclist.each { |sec| next if not sec.flags.to_a.include? 'ALLOC' # check if we fit in an existing segment loadsegs = @segments.find_all { |seg_| seg_.type == 'LOAD' } if sec.addr.kind_of?(::Integer) and seg = loadsegs.find { |seg_| seg_.vaddr.kind_of?(::Integer) and seg_.vaddr <= sec.addr and seg_.vaddr + seg_.memsz >= sec.addr + sec.size } # sections is already inside a segment: we're reencoding an ELF, just patch the section in the segment seg.encoded[sec.addr - seg.vaddr, sec.size] = sec.encoded if sec.encoded next end if not seg = loadsegs.find { |seg_| sec.flags.to_a.include?('WRITE') == seg_.flags.to_a.include?('W') and #sec.flags.to_a.include?('EXECINSTR') == seg_.flags.to_a.include?('X') and not seg_.memsz and not loadsegs[loadsegs.index(seg_)+1..-1].find { |sseg| # check if another segment would overlap if we add the sec to seg_ o = Expression[sseg.vaddr, :-, [seg_.vaddr, :+, seg_.encoded.length+sec.encoded.length]].reduce o.kind_of? ::Integer and o < 0 } } # nope, create a new one seg = Segment.new seg.type = 'LOAD' seg.flags = ['R'] seg.flags << 'W' if sec.flags.include? 'WRITE' seg.align = 0x1000 seg.encoded = EncodedData.new seg.offset = new_label('segment_offset') seg.vaddr = sec.addr || new_label('segment_address') @segments << seg end seg.flags |= ['X'] if sec.flags.include? 'EXECINSTR' seg.encoded.align sec.addralign if sec.addralign sec.addr = Expression[seg.vaddr, :+, seg.encoded.length] sec.offset = Expression[seg.offset, :+, seg.encoded.length] seg.encoded << sec.encoded } end
put every ALLOC section in a segment, create segments if needed sections with a good offset within a segment are ignored
encode_make_segments_from_sections
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode(type='DYN') @header.type ||= {:bin => 'EXEC', :lib => 'DYN', :obj => 'REL'}.fetch(type, type) @header.machine ||= case @cpu.shortname when 'x64'; 'X86_64' when 'ia32'; '386' when 'mips'; 'MIPS' when 'powerpc'; 'PPC' when 'arm'; 'ARM' end if @header.type == 'REL' encode_rel else encode_elf end end
create the relocations from the sections.encoded.reloc create the dynamic sections put sections/phdr in PT_LOAD segments link TODO support mapped PHDR, obey section-specified base address, handle NOBITS encode ET_REL
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def parse_parser_instruction(instr) readstr = lambda { @lexer.skip_space t = nil raise instr, "string expected, found #{t.raw.inspect if t}" if not t = @lexer.readtok or (t.type != :string and t.type != :quoted) t.value || t.raw } check_eol = lambda { @lexer.skip_space t = nil raise instr, "eol expected, found #{t.raw.inspect if t}" if t = @lexer.nexttok and t.type != :eol } case instr.raw.downcase when '.text', '.data', '.rodata', '.bss' sname = instr.raw.downcase if not @sections.find { |s| s.name == sname } s = Section.new s.name = sname s.type = 'PROGBITS' s.encoded = EncodedData.new s.flags = case sname when '.text'; %w[ALLOC EXECINSTR] when '.data', '.bss'; %w[ALLOC WRITE] when '.rodata'; %w[ALLOC] end s.addralign = 8 encode_add_section s end @cursource = @source[sname] ||= [] check_eol[] if instr.backtrace # special case for magic @cursource when '.section' # .section <section name|"section name"> [(no)wxalloc] [base=<expr>] sname = readstr[] if not s = @sections.find { |s_| s_.name == sname } s = Section.new s.type = 'PROGBITS' s.name = sname s.encoded = EncodedData.new s.flags = ['ALLOC'] @sections << s end loop do @lexer.skip_space break if not tok = @lexer.nexttok or tok.type != :string case @lexer.readtok.raw.downcase when /^(no)?r?(w)?(x)?(alloc)?$/ ar = [] ar << 'WRITE' if $2 ar << 'EXECINSTR' if $3 ar << 'ALLOC' if $4 if $1; s.flags -= ar else s.flags |= ar end when 'base' @lexer.skip_space @lexer.readtok if tok = @lexer.nexttok and tok.type == :punct and tok.raw == '=' raise instr, 'bad section base' if not s.addr = Expression.parse(@lexer).reduce or not s.addr.kind_of? ::Integer else raise instr, 'unknown specifier' end end @cursource = @source[sname] ||= [] check_eol[] when '.entrypoint' # ".entrypoint <somelabel/expression>" or ".entrypoint" (here) @lexer.skip_space if tok = @lexer.nexttok and tok.type == :string raise instr if not entrypoint = Expression.parse(@lexer) else entrypoint = new_label('entrypoint') @cursource << Label.new(entrypoint, instr.backtrace.dup) end @header.entry = entrypoint check_eol[] when '.global', '.weak', '.local', '.symbol' if instr.raw == '.symbol' bind = readstr[] else bind = instr.raw[1..-1] end s = Symbol.new s.name = readstr[] s.type = 'FUNC' s.bind = bind.upcase # define s.section ? should check the section exporting s.target, but it may not be defined now # parse pseudo instruction arguments loop do @lexer.skip_space ntok = @lexer.readtok if not ntok or ntok.type == :eol @lexer.unreadtok ntok break end raise instr, "syntax error: string expected, found #{ntok.raw.inspect}" if ntok.type != :string case ntok.raw when 'undef' s.shndx = 'UNDEF' when 'plt' @lexer.skip_space ntok = @lexer.readtok raise "syntax error: = expected, found #{ntok.raw.inspect if ntok}" if not ntok or ntok.type != :punct or ntok.raw != '=' @lexer.skip_space ntok = @lexer.readtok raise "syntax error: label expected, found #{ntok.raw.inspect if ntok}" if not ntok or ntok.type != :string s.thunk = ntok.raw when 'type' @lexer.skip_space ntok = @lexer.readtok raise "syntax error: = expected, found #{ntok.raw.inspect if ntok}" if not ntok or ntok.type != :punct or ntok.raw != '=' @lexer.skip_space ntok = @lexer.readtok raise "syntax error: symbol type expected, found #{ntok.raw.inspect if ntok}" if not ntok or ntok.type != :string or not SYMBOL_TYPE.index(ntok.raw) s.type = ntok.raw when 'size' @lexer.skip_space ntok = @lexer.readtok raise "syntax error: = expected, found #{ntok.raw.inspect if ntok}" if not ntok or ntok.type != :punct or ntok.raw != '=' @lexer.skip_space ntok = @lexer.readtok raise "syntax error: symbol size expected, found #{ntok.raw.inspect if ntok}" if not ntok or ntok.type != :string or not ntok.raw =~ /^\d+$/ s.size = ntok.raw.to_i else if not s.value s.value = ntok.raw elsif not s.size s.size = Expression[ntok.raw, :-, s.value] else raise instr, "syntax error: eol expected, found #{ntok.raw.inspect}" end end end s.value ||= s.name if not s.shndx and not s.thunk s.shndx ||= 1 if s.value @symbols << s when '.needed' # a required library (@tag['NEEDED'] ||= []) << readstr[] check_eol[] when '.soname' # exported library name @tag['SONAME'] = readstr[] check_eol[] @segments.delete_if { |s_| s_.type == 'INTERP' } @header.type = 'DYN' when '.interp', '.nointerp' # required ELF interpreter interp = ((instr.raw == '.nointerp') ? 'nil' : readstr[]) @segments.delete_if { |s_| s_.type == 'INTERP' } case interp.downcase when 'nil', 'no', 'none' @header.shnum = 0 else seg = Segment.new seg.type = 'INTERP' seg.encoded = EncodedData.new << interp << 0 seg.flags = ['R'] seg.memsz = seg.filesz = seg.encoded.length @segments.unshift seg end check_eol[] when '.pt_gnu_stack' # PT_GNU_STACK marking mode = readstr[] @segments.delete_if { |s_| s_.type == 'GNU_STACK' } s = Segment.new s.type = 'GNU_STACK' case mode when /^rw$/i; s.flags = %w[R W] when /^rwx$/i; s.flags = %w[R W X] else raise instr, "syntax error: expected rw|rwx, found #{mode.inspect}" end @segments << s when '.init', '.fini' # dynamic tag initialization @lexer.skip_space if tok = @lexer.nexttok and tok.type == :string raise instr, 'syntax error' if not init = Expression.parse(@lexer) else init = new_label(instr.raw[1..-1]) @cursource << Label.new(init, instr.backtrace.dup) end @tag[instr.raw[1..-1].upcase] = init check_eol[] when '.init_array', '.fini_array', '.preinit_array' t = @tag[instr.raw[1..-1].upcase] ||= [] loop do raise instr, 'syntax error' if not e = Expression.parse(@lexer) t << e @lexer.skip_space ntok = @lexer.nexttok break if not ntok or ntok.type == :eol raise instr, "syntax error, ',' expected, found #{ntok.raw.inspect}" if nttok != :punct or ntok.raw != ',' @lexer.readtok end else super(instr) end end
handles elf meta-instructions syntax: .section "<name>" [<perms>] [base=<base>] change current section (where normal instruction/data are put) perms = list of 'w' 'x' 'alloc', may be prefixed by 'no' 'r' ignored defaults to 'alloc' shortcuts: .text .data .rodata .bss base: immediate expression representing the section base address .entrypoint [<label>] defines the program entrypoint to the specified label / current location .global "<name>" [<label>] [<label_end>] [type=<FUNC|OBJECT|...>] [plt=<plt_label_name>] [undef] .weak ... .local ... builds a symbol with specified type/scope/size, type defaults to 'func' if plt_label_name is specified, the compiler will build an entry in the plt for this symbol, with this label (PIC & on-demand resolution) XXX plt ignored (automagic) .symbol [global|weak|local] "<name>" ... see .global/.weak/.local .needed "<libpath>" marks the elf as requiring the specified library (DT_NEEDED) .soname "<soname>" defines the current elf DT_SONAME (exported library name) .interp "<interpreter_path>" .nointerp defines the required ELF interpreter defaults to '/lib/ld.so' 'nil'/'none' remove the interpreter specification .pt_gnu_stack rw|rwx defines the PT_GNU_STACK flag (default: unspecified, => rwx) .init/.fini [<label>] defines the DT_INIT/DT_FINI dynamic tags, same semantic as .entrypoint .init_array/.fini_array/.preinit_array <label> [, <label>]* append to the DT_*_ARRAYs
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def assemble(*a) parse(*a) if not a.empty? @source.each { |k, v| raise "no section named #{k} ?" if not s = @sections.find { |s_| s_.name == k } s.encoded << assemble_sequence(v, @cpu) v.clear } end
assembles the hash self.source to a section array
assemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def read_c_attrs(cp) cp.toplevel.symbol.each_value { |v| next if not v.kind_of? C::Variable if v.has_attribute 'export' or ea = v.has_attribute_var('export_as') s = Symbol.new s.name = ea || v.name s.type = v.type.kind_of?(C::Function) ? 'FUNC' : 'NOTYPE' s.bind = 'GLOBAL' s.shndx = 1 s.value = v.name @symbols << s end if v.has_attribute 'import' or ln = v.has_attribute_var('import_from') (@tag['NEEDED'] ||= []) << ln if ln and not @tag['NEEDED'].to_a.include? ln s = Symbol.new s.name = v.name s.type = v.type.kind_of?(C::Function) ? 'FUNC' : 'NOTYPE' s.bind = 'GLOBAL' s.shndx = 'UNDEF' @symbols << s end if v.has_attribute('init') or v.has_attribute('constructor') (@tag['INIT_ARRAY'] ||= []) << v.name end if v.has_attribute('fini') or v.has_attribute('destructor') (@tag['FINI_ARRAY'] ||= []) << v.name end if v.has_attribute 'entrypoint' @header.entry = v.name end } end
handles C attributes: export, export_as(foo), import, import_from(libc.so.6), init, fini, entrypoint
read_c_attrs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def decode_header @header.decode self @header.ncmds.times { @commands << LoadCommand.decode(self) } @commands.each { |cmd| e = cmd.data case cmd.cmd when 'SEGMENT', 'SEGMENT_64'; @segments << e end } end
decodes the Mach header from the current offset in self.encoded
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def segment_at(addr) return if not addr or addr <= 0 if seg = @segments.find { |seg_| addr >= seg_.virtaddr and addr < seg_.virtaddr + seg_.virtsize } seg.encoded.ptr = addr - seg.virtaddr seg end end
return the segment containing address, set seg.encoded.ptr to the correct offset
segment_at
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def parse_parser_instruction(instr) readstr = lambda { @lexer.skip_space t = nil raise instr, "string expected, found #{t.raw.inspect if t}" if not t = @lexer.readtok or (t.type != :string and t.type != :quoted) t.value || t.raw } check_eol = lambda { @lexer.skip_space t = nil raise instr, "eol expected, found #{t.raw.inspect if t}" if t = @lexer.nexttok and t.type != :eol } case instr.raw.downcase when '.text', '.data', '.rodata', '.bss' sname = instr.raw.upcase.sub('.', '__') if not @segments.find { |s| s.kind_of? LoadCommand::SEGMENT and s.name == sname } s = LoadCommand::SEGMENT.new s.name = sname s.encoded = EncodedData.new s.initprot = case sname when '__TEXT'; %w[READ EXECUTE] when '__DATA', '__BSS'; %w[READ WRITE] when '__RODATA'; %w[READ] end s.maxprot = %w[READ WRITE EXECUTE] @segments << s end @cursource = @source[sname] ||= [] check_eol[] if instr.backtrace # special case for magic @cursource when '.section' # .section <section name|"section name"> [(no)wxalloc] [base=<expr>] sname = readstr[] if not s = @segments.find { |s_| s_.name == sname } s = LoadCommand::SEGMENT.new s.name = sname s.encoded = EncodedData.new s.initprot = %w[READ] s.maxprot = %w[READ WRITE EXECUTE] @segments << s end loop do @lexer.skip_space break if not tok = @lexer.nexttok or tok.type != :string case @lexer.readtok.raw.downcase when /^(no)?(r)?(w)?(x)?$/ ar = [] ar << 'READ' if $2 ar << 'WRITE' if $3 ar << 'EXECINSTR' if $4 if $1; s.initprot -= ar else s.initprot |= ar end else raise instr, 'unknown specifier' end end @cursource = @source[sname] ||= [] check_eol[] when '.entrypoint' # XXX thread-specific # ".entrypoint <somelabel/expression>" or ".entrypoint" (here) @lexer.skip_space if tok = @lexer.nexttok and tok.type == :string raise instr if not entrypoint = Expression.parse(@lexer) else entrypoint = new_label('entrypoint') @cursource << Label.new(entrypoint, instr.backtrace.dup) end if not cmd = @commands.find { |cmd_| cmd_.cmd == 'THREAD' or cmd_.cmd == 'UNIXTHREAD' } cmd = LoadCommand.new cmd.cmd = 'UNIXTHREAD' # UNIXTHREAD creates a stack cmd.data = LoadCommand::THREAD.new cmd.data.ctx = {} cmd.data.flavor = 'NEW_THREAD_STATE' # XXX i386 specific @commands << cmd end cmd.data.set_entrypoint(self, entrypoint) check_eol[] else super(instr) end end
handles macho meta-instructions syntax: .section "<name>" [<perms>] change current section (where normal instruction/data are put) perms = list of 'r' 'w' 'x', may be prefixed by 'no' shortcuts: .text .data .rodata .bss .entrypoint [<label>] defines the program entrypoint to the specified label / current location
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def assemble(*a) parse(*a) if not a.empty? @source.each { |k, v| raise "no segment named #{k} ?" if not s = @segments.find { |s_| s_.name == k } s.encoded << assemble_sequence(v, @cpu) v.clear } end
assembles the hash self.source to a section array
assemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def compile_c(source, file='<unk>', lineno=1) cp = @cpu.new_cparser tune_cparser(cp) cp.parse(source, file, lineno) read_c_attrs cp if respond_to? :read_c_attrs asm_source = @cpu.new_ccompiler(cp, self).compile puts asm_source if $DEBUG assemble(asm_source, 'C compiler output', 1) c_set_default_entrypoint end
parses a bunch of standalone C code, compile and assemble it
compile_c
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def compile_setsection(src, section) src << section end
add directive to change the current assembler section to the assembler source +src+
compile_setsection
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def init_disassembler @disassembler ||= Disassembler.new(self) @disassembler.cpu ||= cpu each_section { |edata, base| edata ||= EncodedData.new @disassembler.add_section edata, base } @disassembler end
returns the exe disassembler if it does not exist, creates one, and feeds it with the exe sections
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def disassemble(*entrypoints) entrypoints = get_default_entrypoints if entrypoints.empty? disassembler.disassemble(*entrypoints) @disassembler end
disassembles the specified entrypoints initializes the disassembler if needed uses get_default_entrypoints if the argument list is empty returns the disassembler
disassemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def disassemble_fast_deep(*entrypoints) entrypoints = get_default_entrypoints if entrypoints.empty? disassembler.disassemble_fast_deep(*entrypoints) @disassembler end
disassembles the specified entrypoints without backtracking initializes the disassembler if needed uses get_default_entrypoints if the argument list is empty returns the disassembler
disassemble_fast_deep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def encode_string(*a) encode(*a) raise ["Unresolved relocations:", @encoded.reloc.map { |o, r| "#{r.target} " + (Backtrace.backtrace_str(r.backtrace) if r.backtrace).to_s }].join("\n") if not @encoded.reloc.empty? @encoded.data end
encodes the executable as a string, checks that all relocations are resolved, and returns the raw string version
encode_string
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def encode_file(path, *a) encode_string(*a) File.open(path, 'wb') { |fd| fd.write(@encoded.data) } end
saves the result of +encode_string+ in the specified file overwrites existing files
encode_file
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def int_from_hash(val, hash) val.kind_of?(Integer) ? hash.index(val) || val : hash.index(val) or raise "unknown constant #{val.inspect}" end
converts a constant name to its numeric value using the hash {1 => 'toto', 2 => 'tata'}: 'toto' => 1, 42 => 42, 'tutu' => raise
int_from_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def bits_from_hash(val, hash) val.kind_of?(Array) ? val.inject(0) { |val_, bitname| val_ | int_from_hash(bitname, hash) } : int_from_hash(val, hash) end
converts an array of flag constants to its numeric value using the hash {1 => 'toto', 2 => 'tata'}: ['toto', 'tata'] => 3, 'toto' => 2, 42 => 42
bits_from_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def int_to_hash(val, hash) val.kind_of?(Integer) ? hash.fetch(val, val) : (hash.index(val) ? val : raise("unknown constant #{val.inspect}")) end
converts a numeric value to the corresponding constant name using the hash {1 => 'toto', 2 => 'tata'}: 1 => 'toto', 42 => 42, 'tata' => 'tata', 'tutu' => raise
int_to_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def bits_to_hash(val, hash) (val.kind_of?(Integer) ? (hash.find_all { |k, v| val & k == k and val &= ~k }.map { |k, v| v } << val) : val.kind_of?(Array) ? val.map { |e| int_to_hash(e, hash) } : [int_to_hash(val, hash)]) - [0] end
converts a numeric value to the corresponding array of constant flag names using the hash {1 => 'toto', 2 => 'tata'}: 5 => ['toto', 4]
bits_to_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def assemble(*a) parse(*a) if not a.empty? @body << assemble_sequence(@source, @cpu) @body.fixup @body.binding # XXX should create @relocs here @source.clear end
assembles the source in the body, clears the source
assemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def pre_encode relocs = @relocs.inject(EncodedData.new) { |edata, r| edata << r.encode(self) } header = @header.encode self, relocs [header, relocs, @body] end
encodes the header and the relocation table, return them in an array, with the body.
pre_encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def parse_parser_instruction(instr) case instr.raw.downcase when '.entrypoint' # ".entrypoint <somelabel/expression>" or ".entrypoint" (here) @lexer.skip_space if tok = @lexer.nexttok and tok.type == :string raise instr, 'syntax error' if not entrypoint = Expression.parse(@lexer) else entrypoint = new_label('entrypoint') @cursource << Label.new(entrypoint, instr.backtrace.dup) end @header.ip = Expression[entrypoint, :-, label_at(@body, 0, 'body')] @lexer.skip_space raise instr, 'eol expected' if t = @lexer.nexttok and t.type != :eol end end
defines the exe-specific parser instructions: .entrypoint [<label>]: defines the program entrypoint to label (or create a new label at this location)
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def encode pre_encode.inject(@encoded) { |edata, pe| edata << pe } @encoded.fixup @encoded.binding encode_fix_checksum end
concats the header, relocation table and body
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def decode_header @header.decode self end
decodes the MZ header from the current offset in self.encoded
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def decode_body @body = @encoded[@header.cparhdr*[email protected]*[email protected]] @body.virtsize += @header.minalloc * 16 @body.add_export 'start', @header.cs * 16 + @header.ip end
decodes the main part of the program mostly defines the 'start' export, to point to the MZ entrypoint
decode_body
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def decode_header @header = Header.decode(self) end
decodes the header from the current offset in self.encoded
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/nds.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/nds.rb
BSD-3-Clause
def decode_header @cursection ||= self @encoded.ptr = 0x3c @encoded.ptr = decode_word(@encoded) @signature = @encoded.read(4) raise InvalidExeFormat, "Invalid PE signature #{@signature.inspect}" if @signature != MAGIC @coff_offset = @encoded.ptr if @mz.encoded.empty? @mz.encoded << @encoded[0, @coff_offset-4] @mz.encoded.ptr = 0 @mz.decode_header end super() end
overrides COFF#decode_header simply sets the offset to the PE pointer before decoding the COFF header also checks the PE signature
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def encode_default_mz_header # XXX use single-quoted source, to avoid ruby interpretation of \r\n @mz.cpu = Ia32.new(386, 16) @mz.assemble <<'EOMZSTUB' db "Needs Win32!\r\n$" .entrypoint push cs pop ds xor dx, dx ; ds:dx = addr of $-terminated string mov ah, 9 ; output string int 21h mov ax, 4c01h ; exit with code in al int 21h EOMZSTUB mzparts = @mz.pre_encode # put stuff before 0x3c @mz.encoded << mzparts.shift raise 'OH NOES !!1!!!1!' if @mz.encoded.virtsize > 0x3c # MZ header is too long, cannot happen until mzparts.empty? break if mzparts.first.virtsize + @mz.encoded.virtsize > 0x3c @mz.encoded << mzparts.shift end # set PE signature pointer @mz.encoded.align 0x3c @mz.encoded << encode_word('pesigptr') # put last parts of the MZ program until mzparts.empty? @mz.encoded << mzparts.shift end # ensure the sig will be 8bytes-aligned @mz.encoded.align 8 @mz.encoded.fixup 'pesigptr' => @mz.encoded.virtsize @mz.encoded.fixup @mz.encoded.binding @mz.encoded.fill @mz.encode_fix_checksum end
creates a default MZ file to be used in the PE header this one is specially crafted to fit in the 0x3c bytes before the signature
encode_default_mz_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def encode_header(*a) encode_default_mz_header if @mz.encoded.empty? @encoded << @mz.encoded.dup # append the PE signature @signature ||= MAGIC @encoded << @signature super(*a) end
encodes the PE header before the COFF header, uses a default mz header if none defined the MZ header must have 0x3c pointing just past its last byte which should be 8bytes aligned the 2 1st bytes of the MZ header should be 'MZ'
encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def mini_copy(share_ns=true) ret = self.class.new(@cpu) ret.share_namespace(self) if share_ns ret.header.machine = @header.machine ret.header.characteristics = @header.characteristics ret.optheader.entrypoint = @optheader.entrypoint ret.optheader.image_base = @optheader.image_base ret.optheader.subsystem = @optheader.subsystem ret.optheader.dll_characts = @optheader.dll_characts @sections.each { |s| rs = Section.new rs.name = s.name rs.virtaddr = s.virtaddr rs.characteristics = s.characteristics rs.encoded = s.encoded ret.sections << s } ret.resource = resource ret.tls = tls if imports ret.imports = @imports.map { |id| id.dup } ret.imports.each { |id| id.timestamp = id.firstforwarder = id.ilt_p = id.libname_p = nil } end ret.export = export ret end
a returns a new PE with only minimal information copied: section name/perm/addr/content exports imports (with boundimport cleared) resources
mini_copy
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def get_xrefs_x(dasm, di) if @cpu.shortname =~ /^ia32|^x64/ and a = di.instruction.args.first and a.kind_of?(Ia32::ModRM) and a.seg and a.seg.val == 4 and w = get_xrefs_rw(dasm, di).find { |type, ptr, len| type == :w and ptr.externals.include? 'segment_base_fs' } and dasm.backtrace(Expression[w[1], :-, 'segment_base_fs'], di.address).to_a.include?(Expression[0]) sehptr = w[1] sz = @cpu.size/8 sehptr = Indirection.new(Expression[Indirection.new(sehptr, sz, di.address), :+, sz], sz, di.address) a = dasm.backtrace(sehptr, di.address, :include_start => true, :origin => di.address, :type => :x, :detached => true) puts "backtrace seh from #{di} => #{a.map { |addr| Expression[addr] }.join(', ')}" if $VERBOSE a.each { |aa| next if aa == Expression::Unknown dasm.auto_label_at(aa, 'seh', 'loc', 'sub') dasm.addrs_todo << [aa] } super(dasm, di) else super(dasm, di) end end
handles writes to fs:[0] -> dasm SEH handler (first only, does not follow the chain) TODO seh prototype (args => context) TODO hook on (non)resolution of :w xref
get_xrefs_x
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def init_disassembler d = super() d.backtrace_maxblocks_data = 4 case @cpu.shortname when 'ia32', 'x64' old_cp = d.c_parser d.c_parser = nil d.parse_c '__stdcall void *GetProcAddress(int, char *);' d.parse_c '__stdcall void ExitProcess(int) __attribute__((noreturn));' d.c_parser.lexer.define_weak('__MS_X86_64_ABI__') if @cpu.shortname == 'x64' gpa = @cpu.decode_c_function_prototype(d.c_parser, 'GetProcAddress') epr = @cpu.decode_c_function_prototype(d.c_parser, 'ExitProcess') d.c_parser = old_cp d.parse_c '' d.c_parser.lexer.define_weak('__MS_X86_64_ABI__') if @cpu.shortname == 'x64' @getprocaddr_unknown = [] gpa.btbind_callback = lambda { |dasm, bind, funcaddr, calladdr, expr, origin, maxdepth| break bind if @getprocaddr_unknown.include? [dasm, calladdr] or not Expression[expr].externals.include? :eax sz = @cpu.size/8 break bind if not dasm.decoded[calladdr] if @cpu.shortname == 'x64' arg2 = :rdx else arg2 = Indirection[[:esp, :+, 2*sz], sz, calladdr] end fnaddr = dasm.backtrace(arg2, calladdr, :include_start => true, :maxdepth => maxdepth) if fnaddr.kind_of? ::Array and fnaddr.length == 1 and s = dasm.get_section_at(fnaddr.first) and fn = s[0].read(64) and i = fn.index(?\0) and i > sz # try to avoid ordinals bind = bind.merge @cpu.register_symbols[0] => Expression[fn[0, i]] else @getprocaddr_unknown << [dasm, calladdr] puts "unknown func name for getprocaddress from #{Expression[calladdr]}" if $VERBOSE end bind } d.function[Expression['GetProcAddress']] = gpa d.function[Expression['ExitProcess']] = epr d.function[:default] = @cpu.disassembler_default_func end d end
returns a disassembler with a special decodedfunction for GetProcAddress (i386 only), and the default func
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def decode_section_body(s) s.encoded = @encoded[s.virtaddr, s.virtsize] || EncodedData.new end
use the virtualaddr/virtualsize fields of the section header
decode_section_body
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def memdump_imports(memory, dump, unk_iat_p=nil) puts 'rebuilding imports...' if $VERBOSE if unk_iat_p # read iat data from unk_iat_p iat_p = unk_iat_p else return if not imports # read iat data from @imports imports = @imports.dup imports.each { |id| id.iat = id.iat.dup } iat_p = imports.first.iat_p # used for iat_p end failcnt = 0 # bad pointers in iat table (unk_ only) dump.imports ||= [] loaded_dll = nil # the dll from who we're importing the current importdirectory ptrsz = (@optheader.signature == 'PE+' ? 8 : 4) cache = [] # optimize forwarder target search loop do if unk_iat_p # read imported pointer from the table ptr = decode_xword(EncodedData.new(memory[@load_address + iat_p, ptrsz])) iat_p += ptrsz else # read imported pointer from the import structure while not ptr = imports.first.iat.shift imports.shift break if imports.empty? iat_p = imports.first.iat_p end break if imports.empty? iat_p += ptrsz end if not loaded_dll or not e = loaded_dll.export.exports.find { |e_| loaded_dll.label_rva(e_.target) == ptr - loaded_dll.load_address } # points to unknown space # find pointed module start if not dll = cache.find { |dll_| ptr >= dll_.load_address and ptr < dll_.load_address + dll_.optheader.image_size } addr = ptr & ~0xffff 256.times { break if memory[addr, 2] == MZ::MAGIC or addr < 0x10000 ; addr -= 0x10000 } if memory[addr, 2] == MZ::MAGIC dll = LoadedPE.load memory[addr, 0x1000_0000] dll.load_address = addr dll.decode_header dll.decode_exports cache << dll end end if dll and dll.export and e = dll.export.exports.find { |e_| dll.label_rva(e_.target) == ptr - dll.load_address } if loaded_dll and ee = loaded_dll.export.exports.find { |ee_| ee_.forwarder_name == e.name } # it's a forwarder from the current loaded_dll puts "forwarder #{ee.name} -> #{dll.export.libname}!#{e.name}" if $DEBUG e = ee else # new library, start a new importdirectory # XXX if 1st import is forwarded, loaded_dll will points to the bad module... loaded_dll = dll id = ImportDirectory.new id.libname = loaded_dll.export.libname puts "lib #{id.libname}" if $VERBOSE id.imports = [] id.iat_p = iat_p - ptrsz dump.imports << id end else puts 'unknown ptr %x' % ptr if $DEBUG # allow holes in the unk_iat_p table break if not unk_iat_p or failcnt > 4 loaded_dll = nil failcnt += 1 next end failcnt = 0 end # dumped last importdirectory is correct, append the import field i = ImportDirectory::Import.new if e.name puts e.name if $DEBUG i.name = e.name else puts "##{e.ordinal}" if $DEBUG i.ordinal = e.ordinal end dump.imports.last.imports << i end end
rebuilds an IAT from the loaded pe and the memory for each loaded iat, find the matching dll in memory for each loaded iat entry, retrieve the exported name from the loaded dll OR from a base iat address in memory (unk_iat_p, rva), retrieve the 1st dll, find all iat pointers/forwarders to this dll, on failure try to find another dll allows gaps of 5 invalid pointers between libraries dll found by scanning pages 16 by 16 backward from the first iat address (XXX the 1st must not be forwarded) TODO bound imports
memdump_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def code_at_off(off) @all_code.find { |c| c[:fileoff] <= off and c[:fileoff] + c[:code].length > off } end
return the :code part which contains off
code_at_off
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pyc.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pyc.rb
BSD-3-Clause
def new_field(name, decode, encode, defval, enum=nil, bits=nil) if name attr_accessor name name = "@#{name}".to_sym end (@@fields[self] ||= []) << [name, decode, encode, defval, enum, bits] end
defines a new field adds an accessor
new_field
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def new_int_field(*types) recv = class << self ; self ; end types.each { |type| recv.send(:define_method, type) { |name, *args| new_field(name, "decode_#{type}".to_sym, "encode_#{type}".to_sym, args[0] || 0, args[1]) } # shortcut to define multiple fields of this type with default values recv.send(:define_method, "#{type}s") { |*names| names.each { |name| send type, name } } } end
creates a field constructor for a simple integer relies on exe implementing (en,de)code_#{type}
new_int_field
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def virtual(*a) a.each { |f| new_field(f, nil, nil, nil) } end
standard fields: virtual field, handled explicitly in a custom encode/decode
virtual
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def bitfield(inttype, h) # XXX encode/decode very not threadsafe ! this is a Georges Foreman Guarantee. # could use a me.instance_variable.. # decode the value in a temp var d = lambda { |exe, me| @bitfield_val = exe.send("decode_#{inttype}") } # reset a temp var e = lambda { |exe, me, val| @bitfield_val = 0 ; nil } new_field(nil, d, e, nil) h = h.sort h.length.times { |i| # yay closure ! # get field parameters next if not name = h[i][1] off = h[i][0] nxt = h[i+1] mask = (nxt ? (1 << (nxt[0]-off))-1 : -1) # read the field value from the temp var d = lambda { |exe, me| (@bitfield_val >> off) & mask } # update the temp var with the field value, return nil e = lambda { |exe, me, val| @bitfield_val |= (val & mask) << off ; nil } new_field(name, d, e, 0) } # free the temp var d = lambda { |exe, me| @bitfield_val = nil } # return encoded temp var e = lambda { |exe, me, val| val = @bitfield_val @bitfield_val = nil exe.send("encode_#{inttype}", val) } new_field(nil, d, e, nil) end
define a bitfield: many fields inside a single word/byte/whatever usage: bitfield :word, 0 => :lala, 1 => nil, 4 => :lolo, 8 => :foo => a bitfield read using exe.decode_word, containing 3 subfields: :lala (bits 0...1), (discard 3 bits), :lolo (bits 4...8), and :foo (bits 8..-1) fields default to 0
bitfield
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def decode_hook(before=nil, &b) @@fields[self] ||= [] idx = (before ? @@fields[self].index(fld_get(before)) : -1) @@fields[self].insert(idx, [nil, b]) end
inject a hook to be run during the decoding process
decode_hook
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause